Get the value of 'this' input box with jQu

2019-08-17 12:39发布

问题:

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?

回答1:

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/>");
});


回答2:

With your current structure, prev() should work:

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

$('button.enter').click(function() {    
    var myVal = $(this).prev('input.player-input').val();
}):


回答3:

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);
}):


标签: jquery input