2012-05-17 29 views
1

我想根據用戶使用jQuery Mobile從選擇菜單中選擇的值添加動態輸入文本字段。使用jQuery Mobile的動態輸入文本框?

我正在創建一個應用程序,當用戶選擇孩子的數量時,應顯示兩個新的輸入框,要求輸入該孩子的姓名和生日。

這兩個框應顯示基於用戶選擇的值例如;如果用戶選擇2個,則應顯示四個輸入框。

我也想知道如何從這些輸入框中讀取數值usinh jQuery Mobile。下面是一些HTML代碼

<li data-role="fieldcontain"> 
     <label for="children" class="select">Number of Kids</label> 
     <select name="children" id="children" data-mini="true"> 
      <option value="0">0</option> 
      <option value="1">1</option> 
      <option value="2">2</option> 
      <option value="3">3</option> 
     </select> 
    </li> 

回答

2

要創建的投入基礎上有多少孩子被選中,你可以做以下數量:

$(document).on('pageinit',function(){ // use this instead of dom ready, .on is dependent upon jQuery 1.7 + use bind or delegate if you have older version 
    $('#children').on('change',function(){ // this function runs each time the select menu is changed 
     children = $(this).val(); //set variable for number of children 

     while(i <= children){ //loop through as long as i is less than number of children 
      $('form').append('<label>Name</label><input type="text" name="child'+i+'Name" /><label>Age</label><input type="text" name="child'+i+'Age" />'); // append the input to form 
      i++ // add one to our incremnt variable 
     } 

     $('.ui-content').append('<input type="submit" value="Submit" />'); // add our submit button on end 
     $('.ui-page').trigger('create'); // then tell JQM to recreate page because we added new content 
    }); 
});​ 

這裏是一個工作的例子 - >http://jsfiddle.net/codaniel/CDUth/1/

至於讀值,你可以看到,我用.VAL()。這是閱讀特定輸入的最簡單方法。檢查文檔更examples->http://api.jquery.com/val/

還可以序列整個形式像連載()。在這裏閱讀更多 - >http://api.jquery.com/serialize/

0

這裏是有什麼codaniel略微改進版。他很好,但附加提交按鈕的時候沒有什麼「bug」,如果你改回來讓一個孩子說,輸入的數量不會改變。

var html = ''; 
$('#children').on('change', function() { 
    children = $(this).val(); 
    html = ''; 

    for (var i = 0; i < children; i++) { 
     html += '<label>Name</label><input type="text" id="textName' + i + '" name="child' + i + 'Name" /><label>Age</label><input type="text" name="child' + i + 'Age" id="textAge' + i + '" />'; 
    } 

    $('#kidsFields').html(html); 
    $('#kidsFields').append('<input type="submit" value="Submit" />'); 

    $('.ui-page').trigger('create'); 
}); 

http://jsfiddle.net/HwFFU/1/

對於讀取值,很難幫你不知道你想與他們做什麼。但正如Codaniel所說,最簡單的方法是循環輸入並使用.val()來獲取文本!