Getting values ​​from dynamic form elements using javascript

I am creating a dynamic form with javascript that contains a drop down list and input text, as shown below:

$(document).ready(function() { document.write("<FORM>"); document.write("<SELECT NAME='SelectMenu'>"); for (var i = 1; i <= 3; i++) document.write("<OPTION>" +"one"+"</OPTION>"); document.write("<OPTION>" +"two"+"</OPTION>"); document.write("<OPTION>" +"three"+"</OPTION>"); document.write('</SELECT>'); document.write("<br>Entry <input type='text' name='myInputs[]'>"); document.write("<button onClick="ChoixDeQuestion()">Show</button>"); document.write('</FORM>'); }); 

The problem here is that I cannot access these fields since they do not even exist in the source code of the page. I want to get the entered text value and the selected list item. So any idea please!

thanks

+4
source share
3 answers

Using document.write should be avoided. This is not a good practice.

You use jQuery and very easily dynamically create elements in jQuery.

You can do something like this,

 $(document).ready(function() { var options = ''; for (var i = 1; i <= 3; i++) options +='<option>one</option>'; options +='<option>two</option><option>three</option>'; var html = '<select>' + options + '</select><br>Entry <input type="text" name="myInputs[]" />'; var button = $('<button>Show</button>').click(function(e){ // Code to be executed when button is clicked e.preventDefault(); // since by default button submits the form alert('button is clicked'); }); $("<form></form>").append(html).append(button).appendTo('body'); }); 

jsFiddle

If you know basic jQuery, everything is self-explanatory, but let me know if something bothers you :)

+2
source

Instead of using the basic syntax document.write (...) "you should use dynamic elements and create new HTML elements.

Document.write actually displays the text without pasting it. If you want to edit your HTML later, you will need an element to be created and added to the document.

Using, for example, the "CreateElement" syntax. Here is a good tutorial to get you started on how to create a form dynamically. Subsequently, you can add elements to it and create several more elements in this way.

+2
source

If you are already using jQuery, use it more:

 $(document).ready(function() { var form = $('<form />'), dropdown = $('<select />', { name: 'SelectMenu' }), textbox = $('<input />', { type: 'text', name: 'myInputs[]' }), button = $('<button />', { text: 'Show' }).on('click', ChoixDeQuestion); for (var i = 1; i <= 3; i++) { $('<option />', { text: i }).appendTo(dropdown); } form .append(dropdown) .append('<br />Entry') .append(textbox) .append(button) .appendTo('body'); }); 

This creates all the nodes and inserts them into the DOM in a beautiful way; you can also just create one large string of contents with your html and then do the following:

 $(contents).appendTo('body'); 
+2
source

Source: https://habr.com/ru/post/1415386/


All Articles