Get the value of 'this' input box with jQu

2019-08-17 12:28发布

So I have multiple div containing same HTML structure, class names, and attributes. They are identical except the content it outputs. Each div has an input box within with the same class. How do I get the specific value of each input box? I am guessing I would use 'this' but I cannot figure out how to exactly use 'this' to get the specific value of each text box. I don't want to use each because that outputs an array of values.

<div>
    <input class="player-input" type="text"></input>
    <button class="enter">Enter</button>
    <p>Lorem Ipsum<p>
</div>

<div>
    <input class="player-input" type="text"></input>
    <button class="enter">Enter</button>
    <p>Lorem Ipsum<p>
</div>

I am using Meteorjs and events are set up like so:

Template.players.events({
    'click .enter': function(){
          //code
    },
    'keydown .player-input': function(e){
        if (e.which == 13){
            //code
        }
    }
});

How would I get the value of each specific input element with jQuery?

标签: jquery input
3条回答
Summer. ? 凉城
2楼-- · 2019-08-17 12:58

You may want to use .closest

Description: For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

http://api.jquery.com/closest/

$('.enter').click(function() {    
    var myVal = $(this).closest('.player-input').val();
    $(this).closest('p').html(myVal);
}):
查看更多
男人必须洒脱
3楼-- · 2019-08-17 13:09

With your current structure, prev() should work:

http://api.jquery.com/prev/

$('button.enter').click(function() {    
    var myVal = $(this).prev('input.player-input').val();
}):
查看更多
别忘想泡老子
4楼-- · 2019-08-17 13:20

Here's how I appended each to paragraph, let me know if it works: http://jsfiddle.net/VtMRx/

$(".player-input").each(function() {
    //alert(this.value);
    $("#paragraphID").append(this.value + "<br/>");
});
查看更多
登录 后发表回答