Skip to content
Advertisement

How to get multiple values on(“input”) and store them in an array

I am creating an installation script, before executing the script I want to test entered credentials. I want to get these values directly before posting, then post through ajax to check if credentials works fine. I am stuck at storing them in array since these values changes everytime they get updated and array gets filled with trash data.

What would be the best method to store final or latest data in an array before posting them?

var host = '',
db = '',
user = '',
pass = '';

$("#host").on("input", function() {
   host = $(this).val();
   arr.push(host);
   
   $("#host_r").text($(this).val()); //just to debug
   console.log(arr);
});

$("#db").on("input", function() {
   db = $(this).val();
   arr.push(db);

   $("#db_r").text($(this).val()); //just to debug
   console.log(arr);

});

$("#user").on("input", function() {
   user = $(this).val();
   arr.push(user);

   $("#user_r").text($(this).val()); //just to debug
   console.log(arr);

});

$("#pass").on("input", function() {
   pass = $(this).val();
   arr.push(pass);
   
   $("#pass_r").text($(this).val()); //just to debug
   console.log(arr);
});

var arr = new Array;



console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input name="host" id="host" required>
<input name="db" id="db" required>
<input name="user" id="user" required>
<input name="pass" id="pass" required>

<br/>
Host
<div id="host_r"></div>
DB
<div id="db_r"></div>
User
<div id="user_r"></div>
Pass
<div id="pass_r"></div>
Array
<div id="array"></div>

Advertisement

Answer

To DRY this up you can put all the fields in a <form> element. You can then call serializeArray() on that form when it’s submit, which you can send in an AJAX request.

You can also turn the logic which puts the field’s values in to a related div by matching them by name to id in to a single line.

Try this:

$('form').on('submit', e => {
  e.preventDefault();
  let arr = $(e.target).serializeArray();
  console.log(arr);
  
  // send the array in an AJAX request here...
});


// for debugging, show values in the DOM
$('.field').on('input', e => $('#' + e.target.name).text(e.target.value));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<form>
  <input name="host" class="field" required />
  <input name="db" class="field" required />
  <input name="user" class="field" required />
  <input name="pass" class="field" required />
  <button type="submit">Submit</button>
</form>

<br/> 
Host <div id="host"></div>
DB <div id="db"></div>
User <div id="user"></div>
Pass <div id="pass"></div>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement