jQuery - Looping through elements with specific Attribute -


i know how loop through inputs below, searching ones specific class of "testers"

and here's how 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 "john", "smith" expected.

i want not use class="testing" , use custom attribute: testdata="john".

so i'd doing:

<input type='text' name='firstname' testdata='john'> <input type='text' name='lastname' testdata='smith'> 

my goal auto-populate values of each input whatever inside testdata, detected have testdata attribute.

this failed attempt @ using $.each loop:

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

i response: uncaught typeerror: cannot read property 'length' of undefined can see i'm doing wrong?

here using 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 working: http://jsfiddle.net/sfvyw/

an shorter way of doing using js:

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

internally it's doing same other js code it's little more concise.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -