选择值更改时更新输入字段?

时间:2011-02-24 17:08:49

标签: php javascript javascript-events

更新输入字段事件onchange?

$A = array(A,B,C,D);

<select name="A" id="A" onchange="change_val()">
<?php 
foreach($A as $key=>$val){?>
    <option value="<?php echo $key?><?php echo $val?"></option>
<?php }?>
 </select>
<input name="seleted_value" id="seleted_value" value="Hello first time" >

我想写一个执行此任务的onchange方法change_val()

如果选择A(默认情况下)在输入字段seleted_value

中显示“Hello first time”值

其他显示值已选择输入字段seleted_valueDisable this input field for read only.

任何人都可以指导我如何做到这一点?

  if selected= A =>show 'Hello first time'
  if selected= B =>show 'B'
  if selected= C =>show 'C'
  if selected= D =>show 'D'

2 个答案:

答案 0 :(得分:3)

不确定

function change_val() { 
   var sel = document.getElementById('A'),
       lbl = document.getElementById('selected_value');

   lbl.disabled = (sel.selectedIndex !== 0);

   if(sel.selectedIndex === 0) {
      lbl.value = 'Hello first time';
   } else {
      lbl.value = sel.options[sel.selectedIndex].value;
   }
}

jsFiddle example

答案 1 :(得分:2)

<强>的jQuery

我建议使用jQuery。然后你的代码看起来像这样:

$(function()
{
    $('select#A').change(function()
    {
        var this_value = $(this).val();

        if(this_value == 0)
        {
            //you made a typo (seleted), so i did this too on purpose
            $('input#seleted_value').val('Hello first time');
        }
        else
        {
            $('input#seleted_value').val(this_value);
            $('input#seleted_value').attr('disabled', 'disabled');
        }
    });
});