Got undefined when try to get the value of input

Viewed 83

When clicking on input element instead of it's value I'm getting undefined, this is what I am trying:

$(document).ready(function() {
    $(".card_click").click(function() {
        var slug = $(this).closest("div.skill").find("input[type='hidden']").val();
        console.log(slug);
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col s6  cardboard">
    <div class=" card card_click">

        <div class="content">
            <img src='img/tools_1.png' width='30' height='30'>
            <div class="count-to">php</div>
        </div>
        <div class="skill">
            <input type="hidden" name="php" value="php" class="skill_selected">
        </div>
    </div>

</div>
<div class="col s6  cardboard">
    <div class=" card creport card_click">
        <div class="content">
            <img src='img/tools_2.png' width='30' height='30'>
            <div class=" count-to">python</div>
        </div>
        <div class="skill">
            <input type="hidden" name="python" value="python" class="skill_selected">
        </div>

    </div>
</div>
<div class="col s6  cardboard">
    <div class=" card creport card_click">
        <div class="content">
            <img src='img/tools_2.png' width='30' height='30'>
            <div class=" count-to">react</div>
        </div>
        <div class="skill">
            <input type="hidden" name="react" value="react" class="skill_selected">
        </div>

    </div>
</div>

I need to be able to obtain the value of an input element inside each div with class card_click with the div's click() event listener.

2 Answers
$(document).ready(function() {
    $(".card_click").click(function() {
        var slug = $(this).find("div.skill input[type='hidden']").val();
        console.log(slug);
    });
});

The .closest() selector traverses up the DOM to find the parent that matches the conditions.

The .find() selector traverses down the DOM where the event occurred, that matches the conditions

You can use any of the following variants

//Using jQuery
$(document).ready(function() {
    $(".card_click").click(function(currentCard) {
        var inputElem = currentCard.find("input");
        alert(inputElem.val());
    });
});

//Using plain javascript
$(document).ready(function() {
    $(".card_click").click(function(currentCard) {
        var inputElem = currentCard[0].querySelector("input");
        alert(inputElem.value);
    });
});

Related