简体   繁体   中英

Using $(this) scope to find parent previous element

I have a HTML that looks like: I am trying to get current parent closest object value. In this case I'm trying to get values of owner_address, owner_name.

<div class = "form-group row">
  <div class="col-xs-6 form-group">
      <input id="owner_name" type="text></input>
  </div>
  <div class="col-xs-6 form-group">
      <input id="owner_address" type="text></input>
  </div>
</div>
<div class="form-group row">
   <div class="col-xs-6 form-group">
      <input onclick="runFunction($(this))" id="update" type="text></input>
  </div>

</div>

JS part where I try to get values.

<script>
  function runFunction(thisObj){
      var owner_name = thisObj.parent().closest('#owner_name').val()
      #Gives me undefined.
  } 
</script>

I already tried selecting it using ID; it doesn't work in my case because the data are being rendered inside a modal; where each modals are unique. I want to get specific owner name inside my each unique modal; that is why I thought using $(this) would be convenient.

尝试这个

     var owner_name = thisObj.parent().parent().closest('.form-group').find('#owner_name).val()

try this demo: https://jsfiddle.net/xianshenglu/4nt42cso/4/

i change the js,if you use id selector you don't have to use other selectors.

function runFunction(thisObj){
  var owner_name = $('#owner_name').val()
  alert(owner_name);
} 

also change your html,just correct the syntax error.for example,there should not be code like this:</input>,,,,

    <div class="form-group row">
    <div class="col-xs-6 form-group">
        <input id="owner_name" type="text" />
    </div>
    <div class=" col-xs-6 form-group ">
        <input id="owner_address " type="text" />
    </div>
</div>
<div class="form-group row">
    <div class="col-xs-6 form-group">
        <input onclick="runFunction($(this))" id="update" type="text" />
    </div>
</div>

Put this in your fucntion and check it return desired value or not.

thisObj.parent().parent().parent().find( "#owner_name" ).val();

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