Apoorva
Apoorva

Reputation: 81

How to get the value of previous `<input type="text">` in jQuery?

How can I get the ID of the upper <td>’s <input> on click, in the up function? I tried so many ways like parent ID and previous ID but can not get that id.

function up(id) {
  var data = $(this).prev("input[type=text]").attr('id');

  alert(data)
}
<table>
  <tr>
    <td class="row">
      <input class="latest" id="old" type="text" name="">
    </td>
    <td class="second margin_t8">
      <a href="javascript:void(0)" class="col-md-12"  onclick="up(this);">up</a>
    </td>
    <td class="first margin_t8">
      <input class="latest" id="news" type="text" name="" value="data">
    </td>
  </tr>
</table>

In that case, I get undefined. I want to get the previous <input> id in the alert. I need to find the data by id not by class.

Upvotes: 0

Views: 2938

Answers (4)

Bilal Khoukhi
Bilal Khoukhi

Reputation: 1040

Try this out (not tested)

var data=$(this).closest('.form-grid-view-row').first().children("input[type=text]").attr('id');

Upvotes: 0

Mulet Enguix
Mulet Enguix

Reputation: 60

  function up(element) {
      var data = $(element).parent().prev().find("input[type=text]").attr('id');
      alert(data)
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>

  <td class="row">
    <input class="latest" id="old"  type="text" name="" >
  </td>
  <td class="second  margin_t8">

  <a href="javascript:void(0)" class="col-md-12"  onclick="up(this);">ss</a>

  </td>
  <td class="first margin_t8">
    <input class="latest" id="news"  type="text" name="" value="data">
  </td>


</table>

Upvotes: 0

sanatsathyan
sanatsathyan

Reputation: 1763

Try passing the sender (which element is calling the function) as an argument to the function like :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>

  <td class="row">
    <input class="latest" id="old"  type="text" name="" >
  </td>
  <td class="second  margin_t8">

  <a href="javascript:void(0)" class="col-md-12"  onclick="up(this);"></a>

  </td>
  <td class="first margin_t8">
    <input class="latest" id="news"  type="text" name="" value="data">
  </td>


</table>
<script>
  function up(sender) {
 
    var data = $(sender).prev("tr").find("input[type=text].latest").attr('id');
    alert(data);
  }
</script>

Hope this helps in getting the previous row's input's id!!

Upvotes: 0

xjmdoo
xjmdoo

Reputation: 1736

Firstly, this is not pointing to the button which is clicked in this case as you don't use jQuery to add the event handler. However, you can use event.target to get the clicked element. Also, .prev() will return the previous element to the i tag which is undefined as it does not have any siblings.

Updated:

function up(id){
  var data = $(event.target).closest('td').prev().find('input[type="text"]').attr('id');
  alert(data);
}

Upvotes: 1

Related Questions