简体   繁体   中英

jQuery How to set the value to previous input element?

Here is the code I have

<input type="text" value="Select" class="inputClass"></input>
<div class="divClass">
<table>
    <tr><td>Value1</td></tr>
    <tr><td>Value2</td></tr>
</table>
</div>

I want to set the value of input field when the user clicks on a tr and I am doing something like this:

$("tr").click(function() {
  $(this).parent("div.divClass")
   .prev("input.inputClass")
   .val("SomeValue");    
});

But it is not working. Here is the link to the fiddle -> Fiddle

Can anyone tell me where am I going wrong?

The parent() method returns the direct parent element of the selected element.

You can try this:

$("tr").click(function() {
  $(this).closest("div.divClass").prev("input.inputClass").val("SomeValue");    
});

You could just add an id field to the input element and avoid moving up and down the DOM.

and then do something like this:

$("td").click(function() {
  $('#input').val($(this).text());    
});

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