1

我想根据用户使用 jQuery Mobile 从选择菜单中选择的值添加动态输入文本字段。

我正在创建一个应用程序,当用户选择孩子的数量时,应该显示两个新的输入框,询问该孩子的姓名和生日。

这两个框应根据用户选择的值显示,例如;如果用户选择 2,则应显示四个输入框。

我还想知道如何使用 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> 
4

2 回答 2

2

To create the number of inputs based on how many children are selected you could do the following:

$(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
    });
});​

Here is a working example for that -> http://jsfiddle.net/codaniel/CDUth/1/

As for reading the values you can see that i used .val(). That is the easiest way of reading a specific input. Check documentation for more examples-> http://api.jquery.com/val/

You can also serialize the whole form like with serialize(). Read more here -> http://api.jquery.com/serialize/

于 2012-05-17T12:17:44.120 回答
0

这是 codaniel 所拥有的稍微改进的版本。他很好,但是在附加提交按钮时几乎没有“错误”,如果你改回让我们说 1 个孩子,输入的数量不会改变。

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() 来获取里面的文本!

于 2012-05-18T21:57:38.197 回答