使用由 JavaScript 下拉更改事件触发的参数重新加载页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3351845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reload the page with parameter triggered by JavaScript dropdown change event
提问by Naveed
I want a form to be reloaded and preselected with the selection made. Here's the HTML form I have:
我想要一个表单被重新加载并通过所做的选择进行预选。这是我拥有的 HTML 表单:
<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 Selectoption 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?
我需要什么 JavaScript 函数来实现这一点?
回答by Sarfraz
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>
回答by Andy E
sAc's answertells you how you can use the onchange event to modify the location.hrefproperty. 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 onchangeevent. This way, users with JavaScript can still press the return key to reload the page with the same effect:
sAc 的回答告诉您如何使用 onchange 事件来修改location.href属性。这会起作用,但禁用 JS 的用户无法访问它。我会在表单的 action 属性中设置一个 url,并让 select 元素在onchange事件中提交表单。这样,使用 JavaScript 的用户仍然可以按返回键重新加载页面,效果相同:
<?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.
最终结果是禁用 JavaScript 的用户也可以访问该功能。

