0

I have three user inputs which take any number. If a user leaves an input empty then clicks the submit button I would like that input to return 0.

What would be the best way to handle this?

I have created an if statement that individually looks for if input 1 or input 2 or input 3 is empty, but what if input 1 and 2 are empty or if input 3 and 1 are empty, this will lead to quite a long if statement

I wanted to know what would be the best way to go about solving this?

*.js

If( hours === 0  ){
hours = 0
}else if ( minutes === 0 ){
minutes = 0
}else if ( seconds === 0 ){
seconds = 0
}
// more if statement with different combination of minutes seconds and hours being 0
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71

2 Answers2

1

Create a function that does that work and then pass the input value to the function. Call the function for each input.

function checkInput(input){
  if(!input.value){
    input.value = 0;
  }
}

// Find all the <input> elements and loop thorugh them
document.querySelectorAll("input").forEach(function(element){
  checkInput(element); // Call the checkInput function and pass the current input
});
<input>
<input>
<input>

You can also avoid the JavaScript completely by using more precise HTML:

<input type="number" required value="0">
<input type="number" required value="0">
<input type="number" required value="0">
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

First off, You can make sure the user enters a value in the input using the required attribute.

<input type="text" required>

Also If it's inserting into the database, you just need to change the column data type which the value is inserting, to a data type of INT. That way the default is always going to be zero.

But if you still need to check...

if(#inputid.value === ""){
#inputid.value = 0;}

Also remember to get all the inputid using querySelectorAll("#inputid") Then make it an array using var id = Array.from(); Then loop through id using foreach to check the if statement.

  • 1
    Who said anything about a database? – Scott Marcus Jun 26 '21 at 15:26
  • It was just a suggestion. Others who may have similar problems may have a case scenario like that. –  Jun 26 '21 at 15:28
  • `id`s should really be avoided when possible as they make for brittle code. Also, you do not need to make the node list returned from `querySelectorAll()` into an array in order to loop over it with `forEach()`. See my answer above. – Scott Marcus Jun 26 '21 at 15:31