简体   繁体   中英

Find an element value with jQuery

In the following HTML markup, how can I get the value of the input field which has the name module_id[] , by clicking on the span class .click .

HTML:

<div class="module">
    <div class="info">..</div>
    <div class="ctrl"><span class="click">Click</span></div>
    <input type="hidden" value="module1" name="module_id[]" /> 
    <input type="hidden" value="title" name="module_title[]" />
</div>

I have tried this:

jQuery:

$('.module').on('click','.click',function(){
     var target_module = $(this).parent();
     var module_id = target_module.find('input[name=module_id\\[\\]]').val();

    alert(module_id);

 });

Demo: http://jsfiddle.net/FKdNJ/

$(this).parent(); is giving you the <div class="ctrl"> instead.

You could use $(this).parent().parent() , but a more flexible solution is to use closest() instead;

$(this).closest('.module');

You can see this working here; http://jsfiddle.net/FKdNJ/5/


FWIW, you could also change your approach completely, and use e.delegateTarget to retrieve the .module element directly ( http://jsfiddle.net/FKdNJ/7/ );

$('.module').on('click','.click',function(e){
     var target_module = $(e.delegateTarget);
     var module_id = target_module.find('input[name=module_id\\[\\]]').val();

     alert(module_id);
});

With:

$('input[name="module_id[]"').val();

jsFiddle example 1

$('.module').on('click', '.click', function () {
    console.log($('input[name="module_id[]"').val());
});

If you have more than one set of this block of code, use $(this).closest('.ctrl').next().val() :

as in:

$('.module').on('click', '.click', function () {
    console.log($(this).closest('.ctrl').next().val());
});

jsFiddle example 2

Try this

$('.module').on('click','.click',function(){
    alert($(this).closest('.module').find('[name="module_id[]"]:first').val())
 });

http://jsfiddle.net/FKdNJ/3/

Try this . You're probably better off using html 5 data- attributes if possible.

$('span.click').click(function(){     
    var moduleId = $(this).closest("div.module").find("input[name='module_id[]']").val()
    alert(moduleId);
 });

I have added a answer in fiddle:

$('.click').on('click',function(){
     alert($('input[name=module_id\\[\\]]').val());
})

http://jsfiddle.net/FKdNJ/6/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM