动态的字段数取决于另一个字段的值

时间:2015-12-04 22:13:51

标签: javascript jquery

我有表格,看起来像这样:

<div class="fieldWrapper">
    <label for="id_rooms">Rooms:</label>
    <input id="id_rooms" type="number" name="rooms" min="1">
</div>

<div class="extrafieldWrapper">    
</div>

我有脚本根据字段'room'的值添加或删除几个字段'adult'和'children'。现在我想对字段'children'做同样的事情:根据字段的值,'children'脚本应该添加或删除字段'children_age'。我试图意识到这样的事情,但它不起作用。

$(function () {
   $('#id_rooms').bind('blur keyup change', function () {
      var n = $('#id_rooms').val() || 0;
      $("input[id='id_form-TOTAL_FORMS']").attr('value', n);
      $(".extrafieldWrapper").empty();
      for (var i = 0; i < n; i++) {
         $(".extrafieldWrapper").append("<br/><label for='id_form-" + i + "-adult'>Adult:</label> <input id='id_form-" + i + "-adult' type='number' name='form-" + i + "-adult'/> <label for='id_form-" + i + "-children'>Children:</label> <input id='id_form-" + i + "-children' type='number'  name='form-" + i + "-children'/><div id='extrafieldWrapperChAge'></div>");
             $("#id_form" + i + "children").bind('blur keyup change', function() {
                 var n = $("#id_form" + i + "children").val() || 0;
                 $(".extrafieldWrapperChAge").empty();
                 for (var i = 0; i < n; i++) {
                    $(".extrafieldWrapperChAge").append("<br/><label for='id_form-" + i + "-childrenage'></label><input id='id_form-" + i + "-childrenage' type='number' name='form-" + i + "childrenage' />");
                 }
              });
           }
        });
    });

我是java-script的新手,你能告诉我我做错了什么吗?非常感谢。

1 个答案:

答案 0 :(得分:1)

提取内部代码,并仅为儿童年龄字段使用一个事件处理程序。在下面的代码中,我将类children_age添加到输入字段,然后附加一个事件处理程序来监听该类的所有元素的更改。

注1:听取变化事件应该足够了。 注意2:使用 on 而不是 bind ,因为它是jQuery团队推荐的

$(function(){

  $('#id_rooms').on('change', function(e){

    var n = $('#id_rooms').val() || 0;
    var html = "";

      for (var i = 0; i < n; i++) {
        html += "<br/><label for='id_form-" + i + "-adult'>Adult:</label>"
             + "<input id='id_form-" + i + "-adult' type='number' name='form-" + i + "-adult'/>"
             + "<label for='id_form-" + i + "-children'>Children:</label>"
             + "<input id='id_form-" + i + "-children' type='number' name='form-" + i + "-children' class='children_age'/>"
             + "<div class='extrafieldWrapperChAge'></div>";
      }
      $(".extrafieldWrapper").html(html);
  });

  $(".extrafieldWrapper").on('change', '.children_age', function(e){

    // $(this) refers to the element that changed
    var n = $(this).val() || 0;
    var html = "";

      for (var i = 0; i < n; i++) {
        html += "<br/><label for='id_form-" + i + "-childrenage'>Age of child "+(i+1)+"</label>"
             + "<input id='id_form-" + i + "-childrenage' type='number' name='form-" + i + "childrenage' />";
      }
      //.next - finds the next occurrence that matches the selector
      $(this).next('.extrafieldWrapperChAge').html(html);
  });

});