使用Javascript的交互式HTML表单

时间:2011-11-16 07:48:19

标签: php javascript jquery html forms

如何制作交互式HTML表单,例如:

<select name="command">
    <option value="send">Send</option>
    <option value="cancel">Cancel</option>
</select>

<!-- 
    I want the following text input hidden by default,
    but active only if option "Cancel" is selected
-->
<input type="text" name="cancel_reason" id="needreason">

我想默认隐藏“cancel_reason”输入字段,如果之前选择了“取消”选项,则会显示,否则它应保持隐藏状态。

3 个答案:

答案 0 :(得分:5)

$('select[name=command]').change(function(){
    if($(this).val() == 'cancel')
    {
       $('#needreason').show();
    }
    else
    {
       $('#needreason').hide();
    }
});

答案 1 :(得分:2)

看看this jsFiddle。非jQuery

<select id="command" name="command" onchange="javascript:selectChanged()">
    <option value="send">Send</option>
    <option value="cancel">Cancel</option>
</select>

<!-- 
    I want the following text input hidden by default,
    but active only if option "Cancel" is selected
-->
<input type="text" id="needreason" name="cancel_reason" style="display:none">

<script>
    function selectChanged()
    {
        if (document.getElementById('command').value == "cancel")
            document.getElementById('needreason').style.display = 'block';
        else
            document.getElementById('needreason').style.display = 'none';
    }
</script>

答案 2 :(得分:0)

使用此javascript函数

function show_text_box(value)
{
  if(value=='cancel')
  {
    $('#needreason').show();
  }
  else
  {
    $('#needreason').hide();
  }
}

onchange事件

选择中调用此功能
<select name="command" onchange="show_text_box(this.value);">

并设置文本框隐藏

<input style="display:none;" type="text" name="cancel_reason" id="needreason">