1

I need to add a text to input text field after clicking on a button. The button class is always the same (".button") so I think that I need to use "$(this)" but I don't know how to do it.

My code is:

HTML:

<div class="add">
    <input type="text" name="input[1]" value="" class="input[1]">
    <input type="button" class="button" value="add">
</div>
<div class="add">
    <input type="text" name="input[2]" value="" class="input[2]">
    <input type="button" class="button" value="add" value="add">
</div>
<div class="add">
    <input type="text" name="input[3]" value="" class="input[3]">
    <input type="button" class="button" value="add">
</div>

jQuery:

$('.button').click(function(e) {
    $(this).parent('input[type=text]').val('hhh');
});

Regards :)

1
  • $(this).prev().val('hhh'); Commented Jan 24, 2016 at 1:59

2 Answers 2

1

Try substituting .prev() for .parent() ; input type="text" appear to be .previousElementSibling of .button element

  $(this).prev("input[type=text]").val("hhh");
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Works perfectly ;)
0

Use closest

$(this).closest('input[type="text"]').val('hhh')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.