I'm following a tutorial, this version of the form works, where I use onchange. However, the second version below where I try to use onsubmit doesn't work. Can anyone help please?

<form>
<select name="users" onchange="showUser(users.value)">
    <option value="">Select a person:</option>
    <option value="1">Peter Griffin</option>
    <option value="2">Lois Griffin</option>
    <option value="3">Glenn Quagmire</option>
    <option value="4">Joseph Swanson</option>
</select>

This is the one that doesn't work and I'm not sure why?

<form onsubmit="showUser(users.value)">
<select name="users">
    <option value="">Select a person:</option>
    <option value="1">Peter Griffin</option>
    <option value="2">Lois Griffin</option>
    <option value="3">Glenn Quagmire</option>
    <option value="4">Joseph Swanson</option>
</select>
<input type="submit" value="Submit"  >

share|improve this question

33% accept rate
replace the showUser(users.value) with showUser(this.value) – AMember 17 hours ago
feedback

1 Answer

up vote 2 down vote accepted

Try this:

<select name="users" onchange="showUser(this[this.selectedIndex].value);">
    <option value="">Select a person:</option>
    <option value="1">Peter Griffin</option>
    <option value="2">Lois Griffin</option>
    <option value="3">Glenn Quagmire</option>
    <option value="4">Joseph Swanson</option>
</select>

For the other one:

<form onsubmit="showUser(this.users[this.users.selectedIndex].value); return false;">
<select name="users">
    <option value="">Select a person:</option>
    <option value="1">Peter Griffin</option>
    <option value="2">Lois Griffin</option>
    <option value="3">Glenn Quagmire</option>
    <option value="4">Joseph Swanson</option>
</select>
<input type="submit" value="Submit" />

Using return false; prevents the browser from posting the form to the url and thus reloading the page.

share|improve this answer
Sorry my mistake, I have the code snippets the wrong way around. The one with onchange works, but the one with onsubmit doesn't. Sorry. I am trying to edit the original post. – user1149620 17 hours ago
Works brilliant - thanks a lot for the help. – user1149620 17 hours ago
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.