0

I have multiple "input" from HTML.

<input type="text" id="m" />
<input type="text" id="m2" />
<input type="text" id="m3" />
<input type="text" id="m4" />

and I would like each of these to be checked if empty and then replaced with 0 in javascript I used the following

var m1 = document.getElementById('m1').value;
if (m1 === ""){
m1 = 0;
}

Is any simple way to check all the input text areas and then replace each empty with 0 value.

2
  • 2
    You could give each of the elements the same class and then grab them all at once and loop through them checking if they have empty value and replace with 0, for an example please see my answer below. Commented Feb 7, 2018 at 15:45
  • You should consider lib to do it for you if this is not just a simple test crap which you are going to throw away anyway. Commented Feb 7, 2018 at 15:51

2 Answers 2

3
<input type="text" id="m" class="txtEmptyReplace" />
<input type="text" id="m2" class="txtEmptyReplace" />
<input type="text" id="m3" class="txtEmptyReplace" />
<input type="text" id="m4" class="txtEmptyReplace" />

Now that they all have the same class in your js code do something like this:

let myTextElements = document.getElementsByClassName("txtEmptyReplace");
for(let x = 0; x < myTextElements.length; x++){
    if(myTextElements[x].value === ""){
       myTextElements[x].value = 0;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You could do:

let list = document.querySelectorAll('input')

list.forEach((input) => {
   let val = input.value;
   if (val === ""){
      val = 0;
   }
})

2 Comments

Isn't this supposed to cause some cross-browser issues, older version, IE etc? P.S (w/o the let nonsense, I mean the forEach).
Correct, NodeList is not supported in IE

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.