Sylar Sylar - 4 months ago 30
jQuery Question

Get input value using htmlfor

What’s the best way to accomplish something like this:

html.erb



<!-- inside a loop -->
<i htmlfor="wish">
<!-- name or icon -->
</i>
<input type="hidden" class="wish-cls" name="wish" value="<%= product.id %>" />
<!-- end loop -->


JavaScript



$(".wish").click(function(e){
e.preventDefault();
//var id = document.getElementsByTagName('wish-cls');
console.log("Clicked: " + e.target.value);
});


If I click the input, when not hidden, I get the value but how to achieve this using
htmlfor
? Is it possible?

Answer

You can use jQuery attribute selector and next() method to do this like following.

$("[data-id=wish]").click(function(e){
    e.preventDefault();

    var value = $(this).next(".wish-cls").val();
    console.log("Clicked: " + value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<i data-id="wish">Click</i>
<input type="hidden" class="wish-cls" name="wish" value="1000" />

Comments