KateTheGreat
KateTheGreat

Reputation: 107

Jquery how to find only the first occurance

I have a few text inputs on a page & a button (well, an <a>) next to each input. On click I want to target the closest text input to the <a> that is clicked and add the text from the <a> into the closest text input area to the end of the text input. My code below does bring the <a> text over, but it brings the clicked <a> text over into ALL the text inputs. Can you wonderful folks help me limit it to ONLY the actual closest text input to the <a> clicked?

$('#somestuff').on('click', 'a', function(){
    var aTagText = $(this).text();
    var textboxtext = $(this).parent().parent().find('input[type=text]').focus();
    textboxtext.val(textboxtext.val() + aTagText );
    textboxtext.focus();
});

Thanks!

Upvotes: 0

Views: 34

Answers (1)

Rohan Kumar
Rohan Kumar

Reputation: 40639

Use the :first selector like,

var textboxtext = $(this).parent().parent().find('input[type=text]:first').focus();

Also you can short your code like,

$('#somestuff').on('click', 'a', function(e){
    e.preventDefault(); // use if href is specified in anchor tag, and the page is reloading
    var aTagText = $(this).text();
    $(this).parent().parent().find('input[type=text]:first')
           .focus().val(function(index,value){
              return value + aTagText; 
           });
});

Upvotes: 2

Related Questions