Reputation: 7891
I am trying to get the current value of the INPUT field when I click on the signs.
HTML:
<li>
<ul>
<li class="name">Name:</li>
<li><a spc_action="minus" class="ignite_form_counter fas fa-minus-circle"></a></li>
<li><input type="text" name="count_cat_2_x" value="0"></li>
<li><a spc_action="plus" class="ignite_form_counter fas fa-plus-circle"></a></li>
</ul>
</li>
JS:
$('li').delegate('.ignite_form_counter', 'click', function(){
console.log( $(this).parent().parent('li').closest('input').val() );
return false;
});
I've tried the approach above but it doesn't work.
Preferably I wouldn't use closest
because I want to be 100% certain I get the correct value.
Any suggestions how to accomplish this?
Upvotes: 1
Views: 506
Reputation: 337560
Firstly, delegate
is a deprecated. You should use the delegated signature of the on()
method instead. It would also be worth checking your version of jQuery is up to date. You should ideally be using 3.3.1, or 1.12.1 if you need legacy IE support. Secondly, closest()
is for going up the DOM, not down. As such you could couple it with a find()
call to do what you need:
$(document).on('click', '.ignite_form_counter', function(e) {
e.preventDefault();
var value = $(this).closest('ul').find('input').val()
console.log(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>
<ul>
<li class="name">Name:</li>
<li>
<a spc_action="minus" class="ignite_form_counter fas fa-minus-circle">-</a>
</li>
<li><input type="text" name="count_cat_2_x" value="0"></li>
<li>
<a spc_action="plus" class="ignite_form_counter fas fa-plus-circle">+</a>
</li>
</ul>
</li>
</ul>
Note that the on()
call is made on the document
. Using li
as you were will attach the event to every li
in the DOM and end up repeating multiple times. You could potentially improve this by using a closer static single parent element which is available in the DOM when the page loads, but your HTML didn't show that to give you an example.
Upvotes: 2
Reputation: 4587
console.log( $(this).parent().next().find("input").val() );
will help you if you have multiple inputs with plus and minus sign.
$('li').delegate('.ignite_form_counter', 'click', function(){
console.log( $(this).parent().next().find("input").val() );
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li>
<ul>
<li class="name">Name:</li>
<li><a spc_action="minus" class="ignite_form_counter fas fa-minus-circle">minus</a></li>
<li><input type="text" name="count_cat_2_x" value="50"></li>
<li><a spc_action="plus" class="ignite_form_counter fas fa-plus-circle">plus</a></li>
<li><input type="text" name="count_cat_2_x" value="20"></li>
<li><a spc_action="minus" class="ignite_form_counter fas fa-minus-circle">minus</a></li>
<li><input type="text" name="count_cat_2_x" value="30"></li>
</ul>
</li>
You can test it here also.. https://jsfiddle.net/nimittshah/1gvsc8rh/
Upvotes: 0