Input Tag returning Empty String after inputting 1st character

Viewed 38

I am trying to get the values from an input box. When I first input a character and hit enter it returns an empty string in console and I only get the first value after inputting the 2nd value. For example: If I write 'a' in the input box and hit enter it returns an empty string and then if I write 'b' in the input box then it returns a and so on. Here's my code -

let opts = []; 
let optInputs = document.getElementsByName("option_values[]");

for(let j = 0; j < optInputs.length; j++){
     opts.push(optInputs[j].value);
}

If I only console.log optInputs then I am getting the Nodelist and inside it, I am getting the values immediately but whenever I want to access it in a loop I seem to get an empty string after I enter the first character. I have faced an issue like this. Can anyone please help me out here I have been scratching my head over this issue for 3 days now.

2 Answers

Try using a different selector like querySelector /getElementById / getElementByClassName

1.I need someway to call my code. here I am telling my form to execute the function every time the user submit the form. i am also using preventdefault(); inside my function because I don't want it to reload my page.

2.getting the value of the input withdocument.querySelector(".option_values").value; & storing it in optInputs.

3.pushing the value of optInputs into the array opts.

4.document.querySelector(".option_values").value = ""; to clear the input. everytime you hit enter it will go back to empty.otherwise user has to backspace and removing previous characters.

let opts = [];

function myFunction(event) {
  event.preventDefault();
  let optInputs = document.querySelector(".option_values").value;
  opts.push(optInputs)
  document.querySelector(".option_values").value = "";
  console.log(opts)
}
<form onsubmit="myFunction(event)">
  <input class="option_values" type="text" />
</form>

Related