1

I need to get value from input. But the forms are generated dynamically and they have the same class. How can i get for example the input value of only one? In the fiddle below if i click on modify always the first button get triggered.

<form class="myForm">
    <label for='newName'>file</label>
    <input type='text' class='newName' placeholder='new name'/>
    <input type='button' name='change' class='btnSelected' value='Modify'/>
</form>
<form class="myForm">
    <label for='newName'>file</label>
    <input type='text' class='newName' placeholder='new name'/>
    <input type='button' name='change' class='btnSelected' value='Modify'/>
</form>

<script>
$(document).ready(function(){

$(".myForm").on('click', '.btnSelected', function() {

        newName = $(".newName").val();
      console.log(newName);
});


});    
</script>

Fiddle: https://jsfiddle.net/jkwv0oha/2/

Aogiri14
  • 65
  • 10
  • 2
    change `$(".newName").val()` to `$(this).prev().val()` – Swati Jun 08 '21 at 14:35
  • 2
    You need to find the ".newName" element that is a sibling of the button that was clicked. Many ways to do it – epascarello Jun 08 '21 at 14:35
  • Thank you both of you it worked. I think we can close the question. thx – Aogiri14 Jun 08 '21 at 14:48
  • 1
    The [`for` attribute of the `label` element should point to the `id` attribute of the element it labels](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label#attr-for), not the `name`. – Heretic Monkey Jun 08 '21 at 15:18
  • 1
    Does this answer your question? [jQuery: find input field closest to button](https://stackoverflow.com/questions/20357017/jquery-find-input-field-closest-to-button) – Heretic Monkey Jun 08 '21 at 15:30

1 Answers1

1

Without jQuery, register the <body> to listen for 'click' event then simply delegate the click event so that the event handler getValue() is fired only if the user clicked anything with class .btnSelected. In order to get the correct <input> value, .previousElementSibling and .value properties were applied to clicked button (referenced to as event.target).

const getValue = e => {
  if (e.target.classList.contains('btnSelected')) {
    console.log(e.target.previousElementSibling.value);
  }
};

document.body.onclick = getValue;
<form class="xForm">
  <label for='newName'>file</label>
  <input type='text' class='newName' placeholder='new name' />
  <input type='button' name='change' class='btnSelected' value='Modify' />
</form>
<form class="xForm">
  <label for='newName'>file</label>
  <input type='text' class='newName' placeholder='new name' />
  <input type='button' name='change' class='btnSelected' value='Modify' />
</form>
zer00ne
  • 41,936
  • 6
  • 41
  • 68