2014-04-04 29 views
0

我想添加字段取決於用戶在下拉列表中選擇的內容。例如,如果用戶從列表中選擇1沒有任何反應,如果他們選擇2出現文本字段,如果他們選擇3出現兩個文本框等等。到目前爲止,我有:顯示字段取決於使用jQuery選擇

$(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票fields1和2出現,4票字段1,2和3出現。

任何幫助將不勝感激。

+0

_「,如果他們挑2張車票FIELD1出現,3票fields1和2出現和3票字段1,2和3出現。「_沒有意義。你有三張票條件兩次。這個,不應該是$('#tickets2')。change(function(){'be'$('#tickets1')。change(function(){' – j08691

+0

沒有一個選擇器匹配,第一個有兩個'field1',第二個有'tickets2',但是選擇ID是'tickets1','$(this).toggle()'意味着切換select元素,但是爲什麼要切換?爲了很多不一致! – adeneo

+0

對不起,它是一個漫長的一天。編輯 – Hatzi

回答

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撥弄

+0

@Hatzi這對你有意義嗎? – Stphane