RetroCoder
RetroCoder

Reputation: 2685

jQuery: For each attribute of an input element how do I get that input element's name?

I'm looking at each input element that has an attribute named "isDate". I want to find that attributes parent input element's name attribute.

<input name="A0000" isDate="true" value="01/01/2020" />
<input name="A0001" isDate="true" value="01/01/2021" />
<input name="A0002" isDate="true" value="01/01/2022" />
<input name="A0003" isDate="true" value="01/01/2023" />
<input name="A0004" isDate="true" value="01/01/2024" />
<input name="A0005" isDate="true" value="01/01/2025" />


  $("input[isDate="true"]).each(function(){
     var _this = this;
// do stuff then... 

// get name of input
     var name =  $(_this).parent().attr("name").val(); // this doesn't work
  });


Upvotes: 1

Views: 2789

Answers (4)

PeeHaa
PeeHaa

Reputation: 72672

Check out the fiddle: http://jsfiddle.net/SEsBH/

  $('input[isDate="true"]').each(function(){
     var _this = this;
// do stuff then... 

// get name of input
     console.log($(this).attr('name'));
  });

You have a wrong " in $("input[isDate. And one missing :)

Also you can just reference the current element using $(this)

Upvotes: 1

ingo
ingo

Reputation: 5569

Skip the parent and val part

See here

Upvotes: 1

Funka
Funka

Reputation: 4278

Is this what you were looking for?

<input name="A0000" isDate="true" value="01/01/2020" />
<input name="A0001" isDate="true" value="01/01/2021" />
<input name="A0002" isDate="true" value="01/01/2022" />
<input name="A0003" isDate="true" value="01/01/2023" />
<input name="A0004" isDate="true" value="01/01/2024" />
<input name="A0005" isDate="true" value="01/01/2025" />


$("input[isDate="true"]).each(function(){
    var _this = this;
    // do stuff then... 

    // get name of input
    var name =  _this.name;
});

Good luck!

Upvotes: 0

Jon
Jon

Reputation: 12992

this will reference the element, not the attribute, so you won't need .parent()

$("input[isDate='true']").each(function(){
    // get name of input
    var name =  $(this).attr("name");
});

I also fixed some of your syntax too!

Upvotes: 2

Related Questions