I'm a JS learner. I want to display input values in each line (and it's done) but I want to prevent displaying empty values as empty space and replace them with "0". Also I want to force only numbers in the input. Can anyone help me?
<input type="text" id="user-input" onfocus = "this.value =''">
<button id="submit" onclick="addTo()">Submit</button>
<p class="demo"></p>
const myArr = [];
function addTo() {
myArr.push(document.getElementById("user-input").value);
if(myArr.value = "") {
myArr.value = 0;
}
document.querySelector(".demo").innerHTML = myArr.join("<br />")
}
Like you wrote you on the comments, you should change the input to type="number
. Then you must check if the input value in empty before adding it to the array.
Take a look at the example i create for you. There are other ways to do this, but i wanted to stay true to your original idea. i hope it helps you...
let myArr = []; function addTo() { const enteredValue = document.getElementById("user-input").value; const readyValue = enteredValue === ''? 0: enteredValue; myArr.push(readyValue); document.querySelector(".demo").innerHTML = myArr.join("<br />") }
<input type="number" id="user-input" onfocus="this.value =''"> <button id="submit" onclick="addTo()">Submit</button> <p class="demo"></p>
No need for any javascript you can solve both by
<input type="number" placeholder="0">
Granted the placeholder will only show "0" on screen but will return blank as value
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.