AnonyMouse
AnonyMouse

Reputation: 18630

Jquery how to set an input's value within the same div

I'm trying to set the value of an input to the value of the list item clicked. Where they both exist within the same div where the class = container

jQuery

$('li').click(function(){

    /* Somehow set the value of the input that is within the same div 
    with class equal container to the data-personguid on this li. */

});

HTML

<div class="container">
    <div>
        <ul>
            <li data-personguid="3" />
            </li>
        </ul>
    </div>
    <input type="hidden" class="personguid" id="thirdinput" />
</div>

<div class="container">
    <div>
        <ul>
            <li data-personguid="4" />
            </li>
        </ul>
    </div>
    <input type="hidden" class="personguid" id="fourthinput />
</div>

So if the li with data-personguid = 3 was clicked I would want input with id = thirdinput to have it's value set to 3.

Likewise if the li with data-personguid = 4 was clicked I would want input with id = fourthinput to have it's value set to 4.

So I think what I would be trying to do is find the input of class personguid that is within the same div with class = container as the clicked list item and set its value.

Currently unsure how to do this.

The jquery needs to be generic so the same code is used for each container block.

Upvotes: 0

Views: 947

Answers (2)

adeneo
adeneo

Reputation: 318182

$('li').on('click', function(){
    $(this).closest('.container').find('.personguid').val($(this).data('personguid'));
});

Upvotes: 2

wirey00
wirey00

Reputation: 33661

It would be easier if you would just append numbers to your id so you don't have to hardcode each one in

$('li').click(function(){
    var x = $(this).data('personguid');
    $('#input'+ x).val(x);
});

So your inputs would be id=input1, id=input2, id=input3 etc

Upvotes: 0

Related Questions