How would I dynamically create input boxes on the fly?

后端 未结 4 835
走了就别回头了
走了就别回头了 2021-01-23 19:55

I want to use the value of a HTML dropdown box and create that number of input boxes underneath. I\'m hoping I can achieve this on the fly. Also if the value changes it should a

4条回答
  •  天涯浪人
    2021-01-23 20:19

    Here is an example that uses jQuery to achieve your goals:

    Assume you have following html:

      

    And this is the js code for your task:

      $('#input_count').change(function() {
          var selectObj = $(this);
          var selectedOption = selectObj.find(":selected");
          var selectedValue = selectedOption.val();
    
          var targetDiv = $("#inputs");
          targetDiv.html("");
          for(var i = 0; i < selectedValue; i++) {
            targetDiv.append($(""));
          }
      });
    

    You can simplify this code as follows:

      $('#input_count').change(function() {
          var selectedValue = $(this).val();
    
          var targetDiv = $("#inputs").html("");
          for(var i = 0; i < selectedValue; i++) {
            targetDiv.append($(""));
          }
      });
    

    Here is a working fiddle example: http://jsfiddle.net/melih/VnRBm/

    You can read more about jQuery: http://jquery.com/

提交回复
热议问题