GuerillaRadio
GuerillaRadio

Reputation: 1297

Changing an input fields value in jQuery on click

My site searches the Spotify Library and returns a list of results. The idea is that users can click on one of the results and have it added to a playlist which will in turn be posted as part of a form submit. The code below adds the clicked song to a .selected-list container, then adds a hidden input to the DOM with the value of the Spotify song href.

This all works, but each time I click a new song and a new input is added, the href of all the previous added inputs changes too. I know that it's because I am identifying the .track which all the inputs have, but I can't quite figure out how to go about it.

$('.spotify-result').click(function() {
        $(this).clone().appendTo($('.selected-list'));
        $('.submit-spotify').before('<input type="hidden" id="track_href" class="track" value="" name="track_href" />');
        $('.track').val($('.track-href', this).text());
});

Upvotes: 1

Views: 131

Answers (3)

hradac
hradac

Reputation: 2491

So if the idea is to create a new hidden input each time an item is added to the list I suggest doing the following.

$('.spotify-result').click(function() {
        var $input = $('<input type="hidden" id="track_href" class="track" value="" name="track_href" />');

        $(this).clone().appendTo($('.selected-list'));
        $('.submit-spotify').before($input);
        $input.val($('.track-href', this).text());
});

This creates a jQuery object called $input that you can manipulate as if it were an element on the page and when you're ready inject it somewhere on your page. This way it doesn't matter what order it appears in the DOM so if you have to change where it goes on your page you won't have to wrestle with .prev() methods.

Upvotes: 1

talemyn
talemyn

Reputation: 7950

It's because you are using the .track class as the selector in the final line of your code ($('.track').val($('.track-href', this).text());). That will update all elements that have a class="track", which, as shown in the prior line of code, every new input will have.

If we could see a sample of your HTML output, it might be a little easier to help you with a solution . . . hard to tell what some of the things are that you are selecting . . .

My best guess right now, though, would be to try combining the last two lines into one and set the value when you create the input:

    $('.submit-spotify').before('<input type="hidden" id="track_href" class="track" value="' + $('.track-href', this).text() + '" name="track_href" />');

Upvotes: 1

Replace your following code:

$('.track').val($('.track-href', this).text());

for this one:

$('.submit-spotify').prev('.track').val($('.track-href', this).text());

Upvotes: 1

Related Questions