Reputation: 21
I have a page like this:
I want to add a set of numbers (not strings) when I press the button "set number list", but those numbers have to have spaces between them. I have all the HTML stuff I need, but I can't seem to figure out this JavaScript part. I know I can add numbers like this:
document.getElementById("listNumberButton").value = 1234;
and the result will show in the box when I click the button but I have done so much searching I can't seem to figure out how to add numbers with spaces between them like this:
1 2 3 4
Upvotes: 0
Views: 130
Reputation: 65
Run this snippet and check:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script>
function myFunction()
{
var number=document.getElementById("split").value;
number=number.replace(/[^\dA-Z]/g, '').replace(/(.{1})/g, '$1 ').trim();
document.getElementById("result").innerHTML=number;
}
</script>
</head>
<body>
<input type="text" id="split" onkeyup="myFunction()">
<h1 id="result"></h1>
</body>
</html>
Upvotes: 0
Reputation: 65
Try this code: works well
var number="1234";
number=number.replace(/[^\dA-Z]/g, '').replace(/(.{1})/g, '$1 ').trim();
answer will be 1 2 3 4
Upvotes: 0
Reputation: 1
Convert the number to string, split it on ''
, and join it with space - i.e.
var number = 1234;
var spacedNumber = number.toString().split('').join(' ');
or, in your case
document.getElementById("listNumberButton").value = 1234..toString().split('').join(' ');
note the ..
due to Numbers having a decimal point :p
Upvotes: 1