选择选项:jQuery,Case和show/hide表单字段

Ada*_*m C 3 forms jquery select input case

根据select控件的值显示/隐藏表单字段的最有效方法是什么?我有一个选择控件和三个输入字段,根据您工作的业务类型显示/隐藏.

<select id="business-type">
  <option value="1">Sole Trader</option>
  <option value="2">Partnership</option>
  <option value="3">Public Sector</option>
  <option value="4">Public Limited Company (Plc)</option>
  <option value="5">Charity</option>
</select>

// This should appear if you are a Sole Trader (option 1 in the select box)
<div id="soletrader">
<label for="tax">VAT Number</label>
<input type="text" name="tax" id="tax" /> 
</div>

// This should appear if you are a Public Sector business (option 3 in the select box)
<div id="publicsector">
<label for="urn">URN Number</label>
<input type="text" name="urn" id="urn" />   
</div>

// This should appear if you are a Charity (option 5 in the select box)
<div id="charity">
<label for="charityref">Charity Reference No.</label>
<input type="text" name="charity" id="charityref" />    
</div>
Run Code Online (Sandbox Code Playgroud)

用jquery编写的案例陈述是否是最合适的方法?我怎么写这样的陈述?

默认情况下,需要隐藏三个输入字段.任何帮助将不胜感激.我在javascript/jquery上很沮丧.

Kos*_*gos 6

首先,您应该为每个字段div添加"class ='field'".

然后,使用此代码,您将在下拉列表中显示/隐藏选择的相应字段:

$('#business-type').change(function(){
    var selection = $('#business-type').val();
    $('.field').hide();
    switch(selection){
        case 0:
            $('#soletrader').show();
            break;
        case 1:
            $('#publicsector').show();
            break;
        case 2:
            $('#charity').show();
            break;
    }
});
Run Code Online (Sandbox Code Playgroud)