I have code like this:
<form action="checkin.php" method="post">
<select name="roomname" onchange="???">
<option value="">New Room:</option>
<option value="room1">Room 1:</option>
<option value="room2">Room 2:</option>
</form>
I want to set up an action so that when an option is selected to direct the user to the checkin.php
page without them having to use a submit button. I've been told to use onChange
, but I don't know how to use it.
I have code like this:
<form action="checkin.php" method="post">
<select name="roomname" onchange="???">
<option value="">New Room:</option>
<option value="room1">Room 1:</option>
<option value="room2">Room 2:</option>
</form>
I want to set up an action so that when an option is selected to direct the user to the checkin.php
page without them having to use a submit button. I've been told to use onChange
, but I don't know how to use it.
- Please modify the last part of your post. I have no idea what you are trying to ask. – rayryeng Commented May 26, 2014 at 2:04
- Should "New Room" be a submittable option too? and should it auto-submit using the onchange? You should be aware that you cannot change to the same option that the select was on at page load so whichever option is the default will not be accessible. I'd remend using a place-holder eg: with no value and text of: "Choose a room" – nettux Commented May 26, 2014 at 2:04
- Please don't. If you want to react to a change event, load new content into the page and leave the dropdown there. I hate unexpected reloads. Especially if I have to navigate back because I've misclicked. Especially if the page and/or my device is slow as hell. – John Dvorak Commented May 26, 2014 at 2:25
2 Answers
Reset to default 5<select name="roomname" onchange="this.form.submit()">
...
</select>
How about this?
You can use this simple function. It should be generic enough to work for other forms too:
<head>
<script>
function submitForm(elem) {
if (elem.value) {
elem.form.submit();
}
}
</script>
</head>
<body>
<form action="checkin.php" method="post">
<select name="roomname" onchange="submitForm(this)">
<option value="">New Room:</option>
<option value="room1">Room 1:</option>
<option value="room2">Room 2:</option>
</select>
</form>
</body>
The function checks that you have a value in the select IE you haven't changed to the place-holder entry. If New Room
is not a place holder I'd suggest making one otherwise it won't be accessible, with or without the check for a value.
Basically the functions stops the following behavior:
- You go to this form and choose "Room 1"
- The form is auto submitted and you go to
checkin.php
- You change your mind and hit the Back button
- The browser remembers the state of the form and the "Room 1" option is still selected
- You change the drop-down back to "New Room" and the form detects the change and submits.
EDIT : Also note you are missing a closing </select>
tag.