Robert Ross Robert Ross - 1 month ago 24
jQuery Question

Getting the value and the id of the closest input field

I have an edit icon and when clicked this icon invokes a method. In this method I will need the value and the ID attribute's value.
I tried to do this with jquery in a couple of ways, non of which worked.

Here is my html :

<div class="col-sm-2">
<div class="input-group">
<input type="text" class="form-control" id="phone" placeholder="Enter Phone" readonly="readonly">
<div class="input-group-addon">
<span onclick="editUserInfo()"><i class="fa fa-pencil" aria-hidden="true"></i></span>
</div>
</div>
</div>


When the span is clicked, i'd like to get the value of the input field in left, as well as it's id (in this case "phone").

What I tried and didn't work :

For the ID :

$('selector').closest('[id]')


For the value :

$(this).parent().find('.form-control').val();


Of course, I tried many variations of there, but nothing worked(i am very new to this).

Answer

You need to pass the current element that was clicked (using onclick="editUserInfo(this)"), this way you can use that element as a reference inside your function. Otherwise - the this variable will reference to the window object, (which is not what you are looking for).

Inside the function you can find the input.form-control by going to the parent element that has the input-group class.

Check this example:

function editUserInfo(el) {
  input_element = $(el).parents('.input-group').find('input.form-control');
  console.log(input_element.attr('id'));
  console.log(input_element.val());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-2">
  <div class="input-group">
    <input type="text" class="form-control" id="phone" placeholder="Enter Phone" readonly="readonly">
    <div class="input-group-addon">
      <span onclick="editUserInfo(this)"><i  class="fa fa-pencil" aria-hidden="true">click</i></span>
    </div>
  </div>
</div>

I added the click text inside the <span> tag only for visibility...