jquery get previous input text

2019-06-16 16:11发布

问题:

I have the following html:

    <div class="active_string">
                <input type="text" class="answer" /><div class="images"><img src="/images/myImage.png" alt="" /></div>
                <a href="" class="check_quest" id="1">Click me</a>
</div>
    <div class="active_string">
                <input type="text" class="answer" /><div class="images"><img src="/images/myImage.png" alt="" /></div>
                <a href="" class="check_quest" id="2">Click me</a>
</div>

For every click on check_quest I want to get value of a corresponding input. How can I do it using query. I`ve tried the following:

$(this).prev().prev().text()

but this one and other combinations of prev text() and val are not showing the text Ive put into that textfield.

回答1:

Have you tried $(this).prev('input')?

EDIT:

I mean: $(this).prevAll('input').val().



回答2:

It should work with val().

Here is working demo

Even it is working with

$(this).prevAll("input[type=text]").val()


回答3:

Try

$(this).prevAll("input[type=text]").val()

Live example



回答4:

$(".check_quest").click(function() {
    var answer = $(this).prevAll("input").first().val();
});


回答5:

I think

$(this).parent().find('input').val();

would be the best way to go.



回答6:

Here is a working example with two inputs that will show you the different values when you click the links



回答7:

Try this:

HTML Code

<div class="active_string">
    <input type="text" id="answer" />
    <div class="images"><img src="/images/myImage.png" alt="" /></div>
    <a href="" class="check_quest" id="1">Click me</a>
</div>

JavaScript

$(".check_quest").click(function(event)
 {
     event.preventDefault();
     alert ($("#answer").val())
 });      

Here is a working demo: http://jsfiddle.net/tVcKS/