Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Looping through elements with specific Attribute

Tags:

I know how to loop through the inputs below, searching for the ones with a specific class of "testers"

And here's how I do that:

<input type='text' name='firstname' class="testing" value='John'> <input type='text' name='lastname' class="testing" value='Smith'>  <script type="text/javascript"> $(document).ready(function(){   $.each($('.testing'), function() {     console.log($(this).val());  });  }); </script> 

It outputs the "John", "Smith" as expected.

I want to not use the class="testing" and use a custom attribute: testdata="John".

So this is what I'd be doing:

<input type='text' name='firstname' testdata='John'> <input type='text' name='lastname' testdata='Smith'> 

My goal is to auto-populate the values of each input with whatever is inside testdata, but only those detected to have the testdata attribute.

This was my failed attempt at using the $.each loop:

$.each($('input').attr('testdata'), function() {   var testdata = $(this).attr('testdata');   $(this).val(testdata);     }); 

I get this response: Uncaught TypeError: Cannot read property 'length' of undefined Can anyone see what I'm doing wrong?

like image 299
coffeemonitor Avatar asked Apr 18 '13 14:04

coffeemonitor


People also ask

How to loop through elements in jQuery?

jQuery's each() function is used to loop through each element of the target jQuery object — an object that contains one or more DOM elements, and exposes all jQuery functions. It's very useful for multi-element DOM manipulation, as well as iterating over arbitrary arrays and object properties.

How to loop through elements with the same class in jQuery?

Answer: Use the jQuery each() Method You can simply use the jQuery each() method to loop through elements with the same class and perform some action based on the specific condition.

How to get same class value in jQuery?

Explanation: Open an empty array, Use forEach respective to the selector that you want to receive values in. Use jQuery to put empty objects in the array as much as the length of selector. Whenever you input anything in the input field, it would modify it's original value and thus modifying the array itself.


1 Answers

Here it is using the HTML5 data-* attribute:

HTML:

<input type='text' name='firstname' data-test='John'> <input type='text' name='lastname' data-test='Smith'> 

JS:

$("input[data-test]").each(function(){     var testdata = $(this).data('test');     $(this).val(testdata); }); 

Here it is working: http://jsfiddle.net/SFVYw/

An even shorter way of doing it would be using this JS:

$("input[data-test]").val(function(){     return $(this).data('test'); }); 

Internally it's doing the same as the other JS code but it's just a little more concise.

like image 92
Joe Avatar answered Sep 28 '22 07:09

Joe