Javascript 基于所选选项值的表单输入值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7802235/
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
Form input value based on option value selected
提问by algorithmicCoder
for the following form
对于以下表格
<form action ='search.php' method = 'post'>
<select name="filter">
<option id="A" value="A">A</option>
<option id="B" value="B">B</option>
</select>
<input type ='text' name="key" id ="field" value ="something that changes based on what option is selected" />
<input type ='submit' value = 'Search' />
</form>
How do i make the value of the input field change based on whether A
or B
is selected? I assume it has to be done in javascript. I have used jquery here and there so it is ok to make suggestions based on it. Thanks alot!
如何根据是否选择A
或被B
选择来更改输入字段的值?我认为它必须在 javascript 中完成。我在这里和那里都使用过 jquery,因此可以根据它提出建议。非常感谢!
回答by Joe
You don't have to use jQuery, (but jQuery does makes life easier):
您不必使用 jQuery,(但 jQuery 确实让生活更轻松):
HTML:
HTML:
<form action ='search.php' method = 'post'>
<select id="filter" name="filter">
<option id="A" value="A">A</option>
<option id="B" value="B">B</option>
</select>
<input type ='text' name="key" id ="field" value ="something that changes based on what option is selected" />
<input type ='submit' value = 'Search' />
</form>
Javascript:
Javascript:
document.getElementById('filter').onchange = function () {
document.getElementById('field').value = event.target.value
}
回答by Arun Kumar
you may try this
你可以试试这个
<script type="text/javascript">
function changeValue(){
var option=document.getElementById('filter').value;
if(option=="A"){
document.getElementById('field').value="A Selected";
}
else if(option=="B"){
document.getElementById('field').value="B Selected";
}
}
</script>
<form action ='search.php' method = 'post'>
<select name="filter" id="filter" onchange="changeValue();">
<option id="A" value="A">A</option>
<option id="B" value="B">B</option>
</select>
<input type ='text' name="key" id ="field" value ="something that changes based on what option is selected" />
<input type ='submit' value = 'Search' />
</form>
回答by Punit
give id filter
to select
给 idfilter
选择
$(document).ready(function(){
var text_val;
$('#filter').change(function(){
text_val = $(this).val();
$('#field').attr('value',text_val);
return false;
});
});
回答by imm
Try....
尝试....
$('select[name=filter]').change(function() {
var input_field = $('input#field');
switch ($(this).val()) {
case 'A': input_field.val('Value if A is chosen'); break;
case 'B': input_field.val('Value if B is chosen'); break;
}
});