7

I have the following HTML

 <input type="text" name="first" expression="firstExpression"/>
 <input type="text" name="last" expression="secondExpression"/>
 <input type="text" name="age" expression="thirdExpression"/>

I have a custom expression attribute.

I using jQuery to iterate over all the input elements, and although I will need to do something later, I need to be able to grab the expression value for each of these input elements, and compare it to the value of that input element.

I am able to grab the expression value by doing the following

    var expressionValue = inputs.attr("expression");

but that only grabs the expression value of the following, I need to be able to do the same thing such as the following scenario

 function showValues()
 {
    var inputs = $(":input[expression]");
    inputs.each(function(index){ 
    var input = inputs[index];
    //need to be able to get 'expression' from input var here 
    });
 }

the code above is correctly grabbing all the elements I need, but I am unable to figure out how to grab the value of the expression attribute

Domenic
  • 110,262
  • 41
  • 219
  • 271
TheJediCowboy
  • 8,924
  • 28
  • 136
  • 208

5 Answers5

20

use the $.each like this:

function showValues()
 {
    var inputs = $("input[expression]");
    console.log(inputs); //output input for debug
    inputs.each(function(){ 
       console.log(this,$(this).attr('expression'));//show expression (for debug)
    });
 }

showValues();

fiddle: http://jsfiddle.net/maniator/LmW8P/

Naftali
  • 144,921
  • 39
  • 244
  • 303
3

try this

$("input[expression]").each(function(){
    console.log($(this).attr('expression'));
})
Fatih Acet
  • 28,690
  • 9
  • 51
  • 58
1

If all you care about is the attribute value you can optionally pass a function() into .attr() which will allow you iterate the collection.

function showValues() {
    var inputs = $(":input[expression]");
    inputs.attr("expression", function(index, expression){

    });
}

Code example on jsfiddle.

Mark Coleman
  • 40,542
  • 9
  • 81
  • 101
0

try

    $(input).attr('expression');//expression

Karsten
  • 1,814
  • 2
  • 17
  • 32
0

Also if you have the liberty of using HTML5, it would be best to append the word "data-" to the custom attribute as this would not invalidate the document.

More details on Custom Attributes: Yay or Nay

And w3.org talks about custom attributes in more details and also mentions a dataset property to be able to access all such elements quite easily in script, details on W3.Org - Using Custom Attributes

Hope this helps!

Community
  • 1
  • 1
Azerax
  • 41
  • 1
  • 8