简体   繁体   中英

Jquery Closest getting Attributes of Elements of Parent Div

I have a repetitive div structure

<div class="parent">
  <input type="text" name="name" class="name" value="test">
  <input type="hidden" name="id" class="id" value="123">
  <span class="btns">
  <button name="btn_clr" class="clear" type="button" value="Clear"></button>
  </span> 
  </div>

in Jquery i have a onclick function for clear button as

$('.clear').bind("click", function (e){ 
    $(this).closest('.parent').find('input').each(function (index){                    
        console.log(this);
    });
}); 

I want to clear out the values of input elements of Paret Class DIV but its not getting the INPUT elements in the each function

Try with .parent() like

$('.clear').bind("click", function (e){ 
     $(this).closest('.btns').parent().find('input').each(function (index){                    
          console.log(this);
     });
});

Or even try like

$('.clear').bind("click", function (e){ 
     $(this).closest('.parent').find('input').each(function (index){                    
          console.log(this);
     });
});

parent is the class value of the target element, so you need to use it with a class selector like .parent

$('.clear').bind("click", function (e) {
    $(this).closest('.parent').find('input').each(function (index) {
        console.log(this);
    });
});

Try this,

$('.clear').bind("click", function (e){ 
   $(this).closest('.parent').find('input').each(function (index){
        $(this).val(''); // to clear the value
   });
});

Demo

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