JQuery: create a Javascript MACHINE from a CHILDREN element

I am trying to create JavaScript ARRAY and get the name of the child.
(I don't need span elements, only input, select and textarea)

HTML:

<div id="new"> ID: <input name="id" /> <span>Date: </span> <input name="date" /> <select name="status"> <option>New</option> <option>Old</option> </select> <textarea name="memo"></textarea> ... etc. </div> <!-- END: #new --> 


Jquery

 var elements=new Array(); $("#new").each(function() { elements = $(this).children('input, select, textarea').attr("name"); }); 


With this code, I get only one element name ("id"). When I test an array with index 0, it works. BUT, when I use a different index, say ... to warn the "date" or "status", it does not work:

 alert( elements[0] ); //Output: "id" alert( elements[2] ); //Output: "undefined". It should alert "status" instead 
+6
source share
3 answers

cleaner version that captures all fields requiring user input:

JQuery

 var elements = []; //iterates through each input field and pushes the name to the array $("#new :input").each(function() { var name = $(this).attr("name"); elements.push(name); }); 

And yes, you need to clear your HTML. It should look like this:

HTML

 <div id="new"> ID: <input name="id" /> <span>Date: </span> <input name="date" /> <select name="status"> <option>New</option> <option>Old</option> </select> <textarea name="memo"></textarea> </div> 
+11
source

You can use map ( docs ) -

 var arr = $("#new").children('input, select, textarea').map(function() { return $(this).attr("name"); }); 

map will iterate over each element in the selected set of elements and return the specified value to the arr array.

You also need to tidy up your HTML code a bit, as you are missing some closing tags, which is why the children collection fills up incorrectly -

 <div id="new"> ID: <input name="id"/> <span>Date: </span> <input name="date"/> <select name="status"> <option>New</option> <option>Old</option> </select> <textarea name="memo"></textarea> </div> 

Demo - http://jsfiddle.net/M52G4/1

+5
source

quick and dirty, would not recommend for real life, but theoretically:

 var arr = new Array(); //initialise array $('#new').children().each(function(){ //iterate through the children of the div - //there shouldn't be more than one #new, unless you aren't //following best practices :) if ($(this).attr('name')) { //if the name attr is defined, push it to the array arr.push($(this).attr('name')); } }); alert(arr); 

script: http://jsfiddle.net/GMNKm/

0
source

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


All Articles