I want to capture comma separated numbers entered on the form of html as a javascript array.

Asked 2 years ago, Updated 2 years ago, 26 views

I'd like to import comma separated numbers that I entered on the form of html as a javascript array.
For example, send 1, 2, 3, 4, 5, 6, 7, 8, 9 on the form. where var x = [1, 2, 3, 4, 5, 6, 7, 8, 9]; and
var x = ["1, 2, 3, 4, 5, 6, 7, 8, 9"; or a string with var x = [1, 2, 3, 4, 5, 6, 7, 8, 9].

Please let me know if there is any way.

javascript

2022-09-29 21:35

1 Answers

Maybe you should split with ,, and then parseInt for each string.

Demo below

 var form = document.getElementById("form");
var input = document.getElementById("number");
var result= document.getElementById("result");

form.addEventListener("submit", function(e){
  e.preventDefault();
  var text = input.value;
  var numbers = text.split(", ").map(function(s){
    return parseInt(s, 10);
  });
  result.textContent=JSON.stringify(number);
});
<form id="form">
  <div>press Enter to submit</div>
  <input id="number" type="text"/>
</form>
<div>result:<span id="result"></span></div> 


2022-09-29 21:35

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.