Reputation: 1333
I've got an ajax call that returns something like this:
<p>
<a href="javascript:void(0);" class="addressOpt">
John Paul Jones <br/>
399 OAK ST <br/>
DELROY ND 30254 <br/>
<input type="hidden" name="XNAME" value=" John Paul Jones">
<input type="hidden" name="XADD1" value="399 OAK ST">
<input type="hidden" name="XADD2" value="">
<input type="hidden" name="XCITY" value="DELROY">
<input type="hidden" name="XSTA" value="ND">
<input type="hidden" name="XZIP" value="30254">
<input type="hidden" name="XPHON" value="">
</a>
</p>
<p>
<a href="javascript:void(0);" class="addressOpt">
John Paul Jones <br/>
2680 PALUMBO DRIVE <br/>
LEXINGTON KY 40509 <br/>
8592667227
<input type="hidden" name="XNAME" value="John Paul Jones">
<input type="hidden" name="XADD1" value="2680 PALUMBO DRIVE">
<input type="hidden" name="XADD2" value="">
<input type="hidden" name="XCITY" value="LEXINGTON">
<input type="hidden" name="XSTA" value="KY">
<input type="hidden" name="XZIP" value="40509">
<input type="hidden" name="XPHON" value="8592667227">
</a>
</p>
So I want to get every hidden value when any of those links are clicked.
I tried:
$(document).on('click', '.addressOpt', function(e) {
alert($("[name=XCITY]").val());
});
But always gives me back the value of the first element (DELROY), even if I click the second.
I know I've got to use 'this' but don't know who to use it with the attribute equals selector.
Any help would be appreciated.
Upvotes: 0
Views: 6429
Reputation: 781
You can use the each function to get all the hidden data when you click the link using this code
$(document).on('click', '.addressOpt', function (e) {
$(this).find('input[type="hidden"]').each(function () {
alert($(this).val());
});
});
Upvotes: 2
Reputation: 43
I think something like this would work:
$(".addressOpt").on("click", function(e) {
alert($(this).find("input[name='XCITY']").val());
});
It should find the hidden fields within the <a>
that has been clicked.
I would also use e.preventDefault();
instead of href=javascript:void(0);
.
Upvotes: 1
Reputation: 25892
Problem because you are saying
alert($("[name=XCITY]").val());
So it's returning value of first element with that name.
Say this. It'll get the current clicked anchor
and give the value of element having name XCITY
in that anchor
.
$(document).on('click', '.addressOpt', function(e) {
alert($(this).find("[name=XCITY]").val());
});
Upvotes: 0
Reputation: 4808
well first I suggest you to put the result in an array and show the value you need like this
var elems = $("[name=XCITY]");
alert($(elems[0]).val()); // will show "DELROY"
alert($(elems[1]).val()); // will show "LEXINGTON"
Upvotes: 0
Reputation: 4572
You have to do this:
$(document).on('click', '.addressOpt', function(e) {
alert($(this).find("[name=XCITY]").val());
});
You can use $(this) to find the html dom element and get this value.
Upvotes: 4