我正在尝试根据用户在下拉列表中选择的内容添加字段。例如,如果用户从列表中选择1没有任何反应,如果他们选择2,则出现文本字段,如果他们选择3则出现两个文本框,依此类推。到目前为止,我有:
$(document).ready(function() {
$('#field1, #field1, #field3').hide();
$('#tickets1').change(function () {
$(this).toggle(this.value == '2')
$('#field1').show();
});
});
<!--the select just comes from xml/example in html is fine-->
<select name="tickets1" id="tickets1" title="{outbound_inbound/number_of_tickets/@title}">
<xsl:for-each select="outbound_inbound/tickets/number">
<option value="{self::node()}"><xsl:value-of select="self::node()" /></option>
</xsl:for-each>
</select>
<input type="text" name="field1" id="field1" title="" /><br />
<input type="text" name="field2" id="field2" title="" /><br />
<input type="text" name="field3" id="field3" title="" /><br />
所以,如果他们选择2票,则出现field1,出现3个票据字段1和2,并出现4个票证字段1,2和3。
非常感谢任何帮助。
答案 0 :(得分:0)
HTML
<select name="tickets1" id="tickets1"">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<input type="text" name="field1" id="field1" value="1" /><br />
<input type="text" name="field2" id="field2" value="2" /><br />
<input type="text" name="field3" id="field3" value="3" /><br />
JS
/* Considering that the select element and text inputs are siblings */
$('#tickets1').change(function(e) {
// Get all text input fields
var $input = $(this).nextAll('input[type="text"]'),
// Calculate index of the input that match the select value selected
// -2 because of the 0 based index and constraint "if they pick 2 tickets field1 appears"
sliceIndex = +this.value -2;
if(sliceIndex < 0){
$input.hide();
} else $input.slice(sliceIndex).add( $input.prevAll('input')).show().end().nextAll('input').hide();
});
小提琴here