Question

I'm testing out using a normal HTML drop-down menu, and I've encountered a problem when it comes to the submit button of this...

The following is my code:

<head>
<script>
function submitButton()
{
var mylist=document.getElementById("myList");
document.getElementById("favorite").innerHTML=mylist.options[mylist.selectedIndex].text;
}
</script>
</head>

<body>
<form>
<select id="myList">
  <option> </option>
  <option>A</option>
  <option>B</option>  
  <option>C</option>
  <option>D</option>
</select>
<button onclick= 'submitButton()'> Submit </button>
<p>You chose: <span id= 'favorite'> </span></p>
</form>
</body>

Now when I run this code through Live in Adobe Dreamweaver, it works exactly how I want it to; when I choose something from my drop-down menu and press the submit button, the specific letter turns up after 'You chose:'.

However, when I run it in Google Chrome and Safari, it turns out different. When I choose from the drop-down and press 'Submit', the letter appears in its spot for a split second, then the page seems to automatically refresh, leaving the drop-down at its original value, and the <span> blank. Does anyone know why, and how I can solve this from happening?

Was it helpful?

Solution

By default a <button> in a form will submit the form loading the action url of the form or the same page if it doesn't have one.
Just change the button type to button which will prevent it from submitting the form.

<button type="button" onclick= 'submitButton()'> Submit </button>

OTHER TIPS

you could try this also

<head>
<script>
function submitButton()
{
var mylist=document.getElementById("myList");
document.getElementById("favorite").innerHTML=mylist.options[mylist.selectedIndex].text;
}
</script>
</head>

<body>
<form>
<select id="myList">
  <option> </option>
  <option>A</option>
  <option>B</option>  
  <option>C</option>
  <option>D</option>
</select>
<input type="button" onclick= 'submitButton()' value="Submit" /> 
<p>You chose: <span id= 'favorite'> </span></p>
</form>
</body>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top