Adding Javascript Dynamic Input Field

I am not good at Javascript, so I came here to ask for help.

I have a form with a link that says "Add extra URL field." I want it to be when the user clicks on it, it will fill in an extra field under the default url field with a unique input name such as url_input1, and if they click it again to add another url, the name of this input will be url_input2 etc.

How can I do this using javascript?

+3
source share
4 answers

This is the perfect job for a JS library like jQuery. An example implementation of this example in jQuery see this .

, JavaScript DOM, 2 :

  • createElement appendChild (. this this) insertBefore (. this this), . ( Sonic Soul).
  • innerHTML , HTML- , jQuery, . ( )

1 , 2.

jQuery, DOM, , , .

+1

createElement http://www.adp-gmbh.ch/web/js/elements/createelement.html

var someCounter = 0;
...
var i  = document.createElement('input');
i.type = 'text';
i.id = 'myInput_' + someCounter++;

id, , (. )

0

, , HTML javascript. document.createElement, :

function get_parent_add_input() {
var parent_element = this.parentNode;// here, we get the parent node
var current_innerHTML = String(parent_element.innerHTML);
var new_input_html = '<input type="text" name="inputs[]" />';
parent_element.innerHTML = current_innerHTML + new_input_html;
}

, innerHTML.

1 id , . PHP, $_POST['inputs'], .

0

In this example, you can add and remove dynamic inputs.

try something like this:

   $(document).ready(function() {

    var MaxInputs       = 8; //maximum input boxes allowed
   var InputsWrapper   = $("#InputsWrapper"); //Input boxes wrapper ID
   var AddButton       = $("#AddMoreFileBox"); //Add button ID

  var x = InputsWrapper.length; //initlal text box count
  var FieldCount=1; //to keep track of text box added

  $(AddButton).click(function (e)  //on add input button click
 {
    if(x <= MaxInputs) //max input box allowed
    {
            FieldCount++; //text box added increment
           //add input box
        $(InputsWrapper).append('<div><input type="text" name="mytext[]"                            
         id="field_'+ FieldCount +'" value="Text '+ FieldCount +'"/><a href="#" class="removeclass">&times;</a></div>');
        x++; //text box increment
    }
  return false;
  });

 $("body").on("click",".removeclass", function(e){ //user click on remove text
    if( x > 1 ) {
            $(this).parent('div').remove(); //remove text box
                x--; //decrement textbox
            }
      return false;
})

});
-1
source

All Articles