xtr3mz
xtr3mz

Reputation: 73

jquery get attr value from array

var t=new Array('title','placeholder','alt');

$.each(t,function(k,v){
    alert(typeof $(this).attr(v));//PROBLEM $(this) is not the right object
});

goal: Get attribute's (title or placeholder or alt) value that exist.

if element has title, then return title, if not, check placeholder, and then alt.

for example:

>> var v='title';
>> $(this).attr(v);
>> $(this).attr('title');(I want this)

old SOLUTION:

for(var i=0;i<t.length;i++){
    alert($(this).attr(t[i]));
}

REAL SOLUTION: (thanks to mplungjan)

var o=$(this);
$.each(t,function(k,v){
    alert(typeof o.attr(v));//PROBLEM $(this) is not the right object
});

Upvotes: 0

Views: 2943

Answers (2)

mplungjan
mplungjan

Reputation: 177691

Here is what I believe you are trying to do.

Click on the field and look in the console

$(function() {
  var t=['title','placeholder','alt'];
  $("input").on("focus",function() { // we need an event 
    var inp = $(this); // the input as a jQuery object
    $.each(t,function(_,key) { // in here, $(this) is NOT the input
      console.log(key+":"+inp.prop(key)); // we use prop instead of attr
    });
  });  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="inp1" type="text" title="Some input field" placeholder="Enter some text" />

Upvotes: 2

Deenadhayalan Manoharan
Deenadhayalan Manoharan

Reputation: 5444

Try this..

The $.each() function is not the same as $(selector).each(), which is used to iterate, exclusively, over a jQuery object. The $.each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time. (The value can also be accessed through the this keyword, but Javascript will always wrap the this value as an Object even if it is a simple string or number value.) The method returns its first argument, the object that was iterated.

$.each([ 52, 97 ], function( index, value ) {
  alert( index + ": " + value );
});

http://api.jquery.com/jquery.each/

Your code:

var t=new Array('title','placeholder','alt');

    $.each(t,function(k,v){
        alert("key:"+k+"value:"+v);
    });

Demo:http://jsfiddle.net/so2pp1tp/

Upvotes: 1

Related Questions