Reload the page with parameter triggered by JavaScript dropdown change event
I want a form to be reloaded and preselected with the selection made. Here's the HTML开发者_如何学Python form I have:
<form name='vehicleform'>
<select name='vehiclelist'>
<option value=''>Select</option>
<option value='bus'>Bus</option>
<option value='bike'>Bike</option>
<option value='car'>Car</option>
</select>
<input type='text' name='current'></input>
</form>
When the user opens the page for the first time the dropdown box will be on the Select option by default and the textbox (current) will be empty.
When the user selects any option from dropdown the page needs to reload and that dropdown item should be selected and the value of that dropdown should be in the text input field.
What's the JavaScript function that I need to make this happen?
Like this:
<select name='soemname' id="myid" onchange="document.location.href = 'page.php?var=' + this.value">
<option value=''>Select</option>
<option value='bus'>Bus</option>
<option value='bike'>Bike</option>
<option value='car'>Car</option>
</select>
<script type="text/javascript">
document.getElementById('myid').value = "<?php echo $_GET['var'];?>";
</script>
sAc's answer tells you how you can use the onchange event to modify the location.href property. This will work, but it's not accessible to users with JS disabled. I would set a url in the form's action attribute and have the select element submit the form in the onchange event. This way, users with JavaScript can still press the return key to reload the page with the same effect:
<?php $sel = isset($_GET['vehiclelist']) ? $_GET['vehiclelist'] : ""; ?>
<form name='vehicleform' action="thispage.php">
<select name='vehiclelist' onchange="this.parentNode.submit();">
<option value='' >Select</option>
<option value='bus' <?php echo $sel == "bus" ? "selected" : "";?>>Bus</option>
<option value='bike' <?php echo $sel == "bike" ? "selected" : "";?>>Bike</option>
<option value='car' <?php echo $sel == "car" ? "selected" : "";?>>Car</option>
</select>
<input type='text' name='current' value="<?php echo htmlspecialchars($_GET['var']); ?>"></input>
</form>
The end result is a feature that is accessible to users with JavaScript disabled too.
精彩评论