使用Javascript的交互式HTML表单

Interactive HTML Form Using Javascript

本文关键字:HTML 表单 交互式 Javascript 使用      更新时间:2023-09-26

如何制作交互式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"输入字段默认是隐藏的,如果之前选择了下拉选项"Cancel",则显示,否则它应该保持隐藏

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

看看这个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>

使用这个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">