0

So my code is simple html, I need it to select value when submit and if value= that number, submits something like: "Your number is 1"(without refreshing the page).
Thanks a million!

<form action="">
<select name="list">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
</select>
<input type="button" value="Submit!" onclick="">
</form>
2
Contributors
1
Reply
3
Views
5 Years
Discussion Span
Last Post by rajesh1158
0

First, your form wont submit. You should use <input type="submit"> instead of type="button".

Now to accomplish what you want, we can do in 2 ways.

1) Upon selecting a value, print the result

<html>
<head>
<script type="text/javascript">
function printResult()
{

    var selectedVal = document.forms[0].list.options[document.forms[0].list.selectedIndex].value;
    document.getElementById("showResult").innerText = "Your number is: " + selectedVal;
    return false; //dont submit the form
}
</script>
</head>

<body>
<form action="" onSubmit="return printResult(this);">
<select name="list" onChange="printResult();">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
</select>
<input type="submit" value="Submit">
</form>

<span id="showResult"></span>

</body>
</html>

2) Print result only when clicking the submit button

<html>
<head>
<script type="text/javascript">
function printResult(form)
{
    var sel = form.list;
    var selectedVal = sel.options[sel.selectedIndex].value;
    document.getElementById("showResult").innerText = "Your number is: " + selectedVal;
    return false; //dont submit the form
}
</script>
</head>

<body>
<form action="" onSubmit="return printResult(this);">
<select name="list">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
</select>
<input type="submit" value="Submit">
</form>

<span id="showResult"></span>

</body>
</html>
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.