Reload the page with parameter triggered by JavaSc

2019-06-27 05:51发布

I want a form to be reloaded and preselected with the selection made. Here's the HTML 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?

2条回答
欢心
2楼-- · 2019-06-27 06:27

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>
查看更多
三岁会撩人
3楼-- · 2019-06-27 06:29

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.

查看更多
登录 后发表回答