根据所选的选项值形成输入值

时间:2011-10-18 03:53:42

标签: php javascript jquery html

以下表格

<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>

如何根据是选择A还是B来更改输入字段的值?我认为它必须在javascript中完成。我在这里和那里使用过jquery所以可以根据它提出建议。非常感谢!

4 个答案:

答案 0 :(得分:9)

你不必使用jQuery,(但jQuery确实让生活更轻松):

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:

document.getElementById('filter').onchange = function () {
    document.getElementById('field').value = event.target.value  
}

Example

答案 1 :(得分:3)

你可以试试这个

<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>

答案 2 :(得分:2)

提供ID filter以选择

 $(document).ready(function(){  
   var text_val;  
   $('#filter').change(function(){  
     text_val = $(this).val();
     $('#field').attr('value',text_val);  
     return false;  

   });

});

答案 3 :(得分:0)

...试

$('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;
  }
});