使用jQuery Mobile的动态输入文本框?

时间:2012-05-17 10:52:59

标签: jquery jquery-mobile

我想根据用户使用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> 

2 个答案:

答案 0 :(得分: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
    });
});​

以下是一个工作示例 - &gt; http://jsfiddle.net/codaniel/CDUth/1/

至于读取值,你可以看到我使用了.val()。这是阅读特定输入的最简单方法。查看文档以获取更多示例 - &gt; http://api.jquery.com/val/

您也可以像使用serialize()一样序列化整个表单。在这里阅读更多 - &gt; http://api.jquery.com/serialize/

答案 1 :(得分: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()来获取文本!