Reputation: 143
This is my situation
<div id='cont-qty'></div>
<a href="#" class="bottontest">aaa<input class="inp" value="1" /></a>
<a href="#" class="bottontest">bbb<input class="inp" value="2" /></a>
<a href="#" class="bottontest">ccc<input class="inp" value="3" /></a>
<script>
var $j = jQuery.noConflict();
$j(document).ready(function(){
$j("a").click(function(){
$j("#cont-qty").html($j('.inp').val());
return false;
});
});
</script>
When I click on the first tag or on the second one I would like to take the value of each respective input. For example if I click on the second I want me to take the value of the second input and so on.
At the moment if I click on the second or third it always takes me only the value of the first input.
How can I do?
Upvotes: 0
Views: 76
Reputation: 178413
Your HTML is not valid. Instead use label and IDs
<label for="input1" class="bottontest">Aaaa<input id="input1" class="inp" value="1" /></label>
You can then use
$j("label.bottontest").on("click",function() {
$j("#cont-qty").html(
$j("#"+$j(this).attr("for")).val()
);
});
Upvotes: 0
Reputation: 16
I would not use the 'this' keyword. I try to avoid it as much as posible when I write Javascript
var $j = jQuery.noConflict();
$j(function(){
$j("a").on("click",function(element){
$j("#cont-qty").html($j(element.target).find(".inp").val());
return false;
});
})
Upvotes: 0
Reputation: 82251
Use context of clicked anchor(this
) to find input element in it:
$j("a").click(function(){
$j("#cont-qty").html($j(this).find('.inp').val());
return false;
});
Upvotes: 0
Reputation: 12880
You need to adjust the context of your $('.inp')
selector to this
, which represents the a
clicked.
You can do that by using : $('.inp',this)
$("a").click(function() {
$("#cont-qty").html($('.inp',this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='cont-qty'></div>
<a href="#" class="bottontest">aaa<input class="inp" value="1" /></a>
<a href="#" class="bottontest">bbb<input class="inp" value="2" /></a>
<a href="#" class="bottontest">ccc<input class="inp" value="3" /></a>
Upvotes: 1