Click here to Skip to main content
15,887,846 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a div. It has a table. It has input elements inside the table.
How should i write the code so that i get the elements name and id of all the elements using jQuery .each function. As i am cloning all the div element these are required to modify the cloned element randomly.

structure is like


text field
select field
text field
text fieldselect field

Posted

Try this ... might give bit idea..

JavaScript
$('div table tbody tr').each(function(){
console.log($(this).find('input[type=text], select ').attr('id'));
console.log($(this).find('input[type=text], select ').attr('name'));
});
 
Share this answer
 
v2
Try this:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){

  $("#btn").click(function(){

    var elementids = [];
    var elementnames = [];
    $('#div1 :input').each(function() {
             elementids.push($(this).attr('id'));
             elementnames.push($(this).attr('name'));
    });

    alert("By ids => " + elementids.join(','));
    alert("By names => " + elementnames.join(','));

  });
});
</script>
</head>
<body>

<div id="div1">
<table>
<tr><td>
   <input type="text" id="text-id" name="text-name"> <br/>
</td></tr>
<tr><td>
   <input type="radio" id="radio-id" name="radio-name">Radio
</td></tr>
<tr><td>
   <input type="checkbox" id="checkbox-id" name="checkbox-name">Checkbox <br/>
</td></tr>
</table>
</div>

<button id="btn" type="button">Click Me</button>

</body>
</html>
 
Share this answer
 
v2
Comments
Richard Deeming 5-Nov-14 12:11pm    
The input selector won't find select or textarea elements. Try the :input selector[^] instead.

$('#div1 :input').each(...
Peter Leow 5-Nov-14 19:48pm    
Thank you, Richard. Yes, should be':input' which will include button and select elements. Amended the solution. Virtual 5!.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900