2014-01-31 22 views
1

我在這裏已經完成了我所應用和嘗試的代碼。使用下面的JS,我錯誤地顯示了有序列表。它必須在1,2,3 ...(如此來回)。爲此,它堅持1.,1.,1. ...。另一個是,使用下面的JS,如何定製它,我會得到dynamic輸入字段?因爲如果我輸入5會怎麼樣?字段的結果也必須是5。但是,發生了什麼情況,在當前的字段數中添加/附加了5個字段(樣本,我之前輸入了3個字段,顯示了3個字段,所以當輸入5時,總共有8個字段)。我想要的是從輸入的數字的確切數量的字段。 (對JS不太好,但我非常想學習它的本質)。創建有序列表加上生成輸入字段HTML&JS

<html> 
<head> 
<script type="text/javascript" src="js/jquery.js"></script> 
<script type="text/javascript" src="js/jquery-1.8.3.js"></script> 

<script type="text/javascript"> 
$(document).ready(function() { 
    $("ul").each(function() { 
    $(this).find("li").each(function(count) { 
     $(this) 
     .css("list-style-type", "none") 
     .prepend("<div class='listnumber'>" + (count + 1) + ".</div>"); 
     }); 
    }); 
})  
</script> 

<script type="text/javascript"> 
    $(document).ready(function() { 
    $('[name="cand_no"]').on('change', function() { 
     if (this.value != '') { 
      var val = parseInt(this.value, 10); 

      for (var i = 0; i < val; i++) { 
       var $cloned = $('.template tbody').clone(); 
       $('#studentTable tbody').append($cloned.html()); 
     } 
    }); 
    }) 
</script> 

</head> 
<body> 
     <p> 
     <label><strong>No.: </strong></label> 
     <label><input name="cand_no" type="number" placeholder="Enter no. of fields." /></label> 
     <div class="clear"></div> 
    </p> 
    <div class="cand_fields"> 
     <table id="studentTable" width="630" border="0"> 
      <tr> 
       <td>Name</td> 
      </tr> 
      <tr> 
       <td><input name="cand_name" type="text" placeholder="Name" required="required" /></td> 
      </tr> 
     </table> 

    </div> 

    <div class="template" style="display: none"> 
     <table> 
     <tr > 
      <td><ul><li><input name="cand_name" type="text" placeholder="Name" required="required" /></li></ul></td> 



      </tr> 
     </table> 
     </div> 
    </body> 
</html> 

萬分感謝..

回答

2

嘗試

$(document).ready(function() { 
    $(".template ul li").css("list-style-type", "none").prepend("<div class='listnumber'></div>"); 
}) 
$(document).ready(function() { 
    var $tmpl = $('.template tbody'), 
     $target = $('#studentTable tbody'); 
    $('[name="cand_no"]').on('change', function() { 
     if (this.value != '') { 
      var val = (parseInt(this.value, 10) || 0) + 2; 
      var len = $target.children().length; 

      if (val < len) { 
       $target.children().slice(val).remove(); 
      } else { 
       for (var i = len; i < val; i++) { 
        $($tmpl.html()).appendTo($target).find('.listnumber').text(i - 1); 
       } 
      } 
     } 
    }); 
}) 

演示:Fiddle

+0

非常感謝。它工作得很好! – Cecil