0

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"  >

1
  • replace the showUser(users.value) with showUser(this.value) Commented Dec 12, 2012 at 11:14

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.