简体   繁体   中英

JS reading of inputs into dynamically created HTML form fields

Help sought;

I've been playing around with code snippets from here and there that dynamically add text fields to an HTML form. The page is basic: a form prompts for at least one text field input; has a button to offer to add more text fields; has a button to submit the entries in all fields that were presented - the idea is that field entries are read into variables then simply displayed to the user by the same html page.

The addition of fields to the form works ok.

What I cannot figure out is how to read inputs made into the fields, using just JS in the same page (ie there is no PHP or other server based reading of the data).

Extract from the code, that creates the additional fields is as below:

        <div class="input_fields_wrap">
            <button class="add_field_button">Add More Fields</button>
            <div><input type="text" name=mytext[]></div>
        </div>

and the portion of the JS used to dynamically add fields appears as:

var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
    e.preventDefault();
    if(x < max_fields){ //max input box allowed
        x++; //text box increment
        $(wrapper).append('<div><input type="text" name=mytext[]/><a href="#" class="remove_field">x</a></div>'); //add input box
    }
});

then, the forms "submit" button is as follows:

<input name="button" onclick="addtext()" type="button" value="Show" />

then, the function (in the same page) addtext() is basically:

   function addtext() {
       var f2 = document.myform.?????????????
       document.writeln(f2,'<br>')
    }

where the "?????????????" represents an attempt to read the entry from any of the mytext[] dynamically added fields....this is the part I cannot figure.

Suggestions appreciated. Thx.

You have almost got it through.

var readInputVariables = function(){
  $('input:text').each(function(index,element){
      console.log(element.val()); // do whatever you want with the value;
  })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM