javascript - How to get all form input values using blur event in `addEventListener`? - Stack Overflow

I am trying to get form values dynamically using addEventListener but I am just getting first input, no

I am trying to get form values dynamically using addEventListener but I am just getting first input, not getting other inputs.

This is my current code:

$(document).ready(
  function() {
    const user_input = document.querySelector('input[type="text"], input[type="password"]');

    user_input.addEventListener(
      'blur',
      function(event) {
        var target = event.target;

        if (target.name == "first_name") {
          console.log('first name : ' + target.value);
        }

        if (target.name == "mid_name") {
          console.log('mid name : ' + target.value);
        }

        if (target.name == "last_name") {
          console.log('last name : ' + target.value);
        }

        if (target.name == "password") {
          console.log('password : ' + target.value);
        }
      }
    );
  }
);
<script src=".3.1/jquery.min.js"></script>
<form>
  first_name : <input type="text" name="first_name" value=""> <br>
  mid_name : <input type="text" name="mid_name" value=""> <br>
  last_name : <input type="text" name="last_name" value=""> <br>
  password : <input type="password" name="password" value=""> <br>
</form>

I am trying to get form values dynamically using addEventListener but I am just getting first input, not getting other inputs.

This is my current code:

$(document).ready(
  function() {
    const user_input = document.querySelector('input[type="text"], input[type="password"]');

    user_input.addEventListener(
      'blur',
      function(event) {
        var target = event.target;

        if (target.name == "first_name") {
          console.log('first name : ' + target.value);
        }

        if (target.name == "mid_name") {
          console.log('mid name : ' + target.value);
        }

        if (target.name == "last_name") {
          console.log('last name : ' + target.value);
        }

        if (target.name == "password") {
          console.log('password : ' + target.value);
        }
      }
    );
  }
);
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  first_name : <input type="text" name="first_name" value=""> <br>
  mid_name : <input type="text" name="mid_name" value=""> <br>
  last_name : <input type="text" name="last_name" value=""> <br>
  password : <input type="password" name="password" value=""> <br>
</form>

Demo on JSFiddle

I can just get the fist name value; for the other inputs I am not getting anything. Any idea what I am doing wrong?

Share Improve this question edited Jun 3, 2020 at 8:03 Sebastian Simon 19.6k8 gold badges61 silver badges84 bronze badges asked Jun 3, 2020 at 7:38 user889030user889030 4,7644 gold badges58 silver badges54 bronze badges 6
  • 4 document.querySelector returns ONE node - the first that matches the given selector. – sdgluck Commented Jun 3, 2020 at 7:43
  • @sdgluck so do we have something which can work in entire block like giving form ID or name – user889030 Commented Jun 3, 2020 at 7:45
  • 1 @user889030 I don’t understand what you mean by your ment. But selecting multiple elements is done with querySelectorAll. May I also suggest event delegation instead of assigning multiple events? Something like this JSFiddle; this is just a single line of code inside the $(document).ready(function(){});. – Sebastian Simon Commented Jun 3, 2020 at 7:53
  • The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. You need to use another selector to get each element. – dale landry Commented Jun 3, 2020 at 8:02
  • @dalelandry The selector (which is the string) is fine. They need a different method, or a different approach. – Sebastian Simon Commented Jun 3, 2020 at 8:05
 |  Show 1 more ment

3 Answers 3

Reset to default 4

To achieve what you expect you have to change two parts in your code.

The first thing to change is to use the querySelectorAll instead of the querySelector. The difference is that the querySelector selects only one element at a time, while the querySelectorAll selects all the elements matching the selectors.

The second thing you have to change is to apply the addEventListener to any element in the array as they are different ponents and have different events to listen to.

Here is the running code: https://jsfiddle/9jo1snuq/1/

I hope this helps :)

$( document ).ready( function() {
    const user_input = document.querySelectorAll('input[type="text"], input[type="password"]');

    user_input.forEach(
        function(userInput) {
            userInput.addEventListener(
                'blur', 
                function ( event ) {
                    var target = event.target;

                    if( target.name == "first_name" ) {
                        console.log( 'first name : ' + target.value );
                    }

                    if ( target.name == "mid_name" ) {
                        console.log( 'mid name : ' + target.value );
                    }

                    if ( target.name == "last_name" ) {
                        console.log( 'last name : ' + target.value );
                    }

                    if ( target.name == "password" ) {
                        console.log( 'password : ' + target.value );
                    }

                }
            );  
        }
    );

});

Aside from the issue you are facing with querySelector() vs querySelectorAll() addressed by other answers, I suggest you use the native FormData() to get all your data from the form, here is a snippet:

https://developer.mozilla/en-US/docs/Web/API/FormData

document.getElementById('mybutton').addEventListener('click', function(e) {
  e.preventDefault();
  let myForm = document.getElementById('myForm');
  let formData = new FormData(myForm);
  for (let input of formData) {
    console.log(input);
  }
});
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>


    <form id="myForm">
      first_name : <input type="text" name="first_name" value=""> <br>
      mid_name  :  <input type="text" name="mid_name" value=""> <br>
      last_name  :  <input type="text" name="last_name" value=""> <br>
      password :  <input type="password" name="mid_name" value=""> <br>
      <button id="mybutton">
       get data
      </button>
    </form>


<script src="script.js"></script>
  </body>
</html>

Like this?

function updateResult() {
  $('#result').text(JSON.stringify($('#inputs').serializeArray().map(x=>x.name + ': '+x.value)))
}

$(document).ready(function() {
  $('input').on('change', function() {
    updateResult()
  })
})
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="inputs">
  first_name : <input type="text" name="first_name" value=""> <br>
  mid_name  :  <input type="text" name="mid_name" value=""> <br>
  last_name  :  <input type="text" name="last_name" value=""> <br>
  password :  <input type="password" name="password" value=""> <br>
</form>
<div id="result">

</div>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745314814a4622168.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信