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/

5

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.