jQuery - Looping through elements with specific Attribute

coffeemonitor picture coffeemonitor · Apr 18, 2013 · Viewed 52.8k times · Source

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?

Answer

Joe picture Joe · Apr 18, 2013

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.