Arsengael Arsengael - 1 month ago 9
HTML Question

Displaying new input value (adding spaces)

This seems embarrassing to ask even for a newbie like me, but I have a huge headache with displaying new value in the html input field after adding spaces between numbers in html input.
Basically, what I want to achieve is to add spaces between numbers in the input field after the user "unclicks" the input. For example, 123456789123456789 would change to 12 3456 7891 2345 6789. I get the value of users input and add spaces where I want, but I just can't make it appear in the input field. My code looks like this:



'use strict';
$(document).ready(function (){var $inputTwo = $('#separateNumbers');
$inputTwo.change(function() {
var inputNumber = $inputTwo.val();
var separatedNumbers = [];
var part1 = inputNumber.substring(0, 2);
separatedNumbers.push(part1);
for (var i = 2; i < inputNumber.length; i += 4){
separatedNumbers.push(inputNumber.substring(i, i + 4))
}
var displayNumber = separatedNumbers.join(' ');
$inputTwo.val(displayNumber);
})
});

<body>
<div class="wrapper">
<div id="Task1_2">
<h1>Task 1.2</h1>
<label for="separateNumbers">Write more than 10 digits:</label><br/>
<input type="number" id="separateNumbers" placeholder=" i.e. 12345678901234567">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>





I don't understand why this doesn't work. I tried to replace last code line with

document.getElementById('separateNumbers').value = displayNumber;

but then I got this in console:

The specified value "87 6178 1" is not a valid number. The value must match to the following regular expression: -?(\d+|\d+.\d+|.\d+)([eE][-+]?\d+)?.

This appears no matter what combination of numbers I put. Unfortunately I don't understand Regex yet, so I don't even know what would be a valid value...

Please help me, I'm out of ideas what to do...

M B M B
Answer

a number does not have spaces in it. change your input to a type = text and it should work