Javascript Question

Function to write all even numbers from form

I have html form of 16 fields. User enters number in each field
and function have to sort only even numbers and show them.


// JS function for even numbers and printing out in paragraph //


function evenNumbers() {
var numbers = document.getElementsByClassName("formInput");
var i;
for (i = 0; i <= numbers.length - 1; i++) {
if (numbers[i].value % 2 == 0) {
document.getElementById("even").innerHTML = "Even numbers are: " + numbers[i].value;
else {
continue;
}
}
}


After I fill in form, I do get text and value, but only last one.

Question: How can I get function to write me all even numbers in one
line?


Example: 2,4,6,8 etc...


What must I type in or change this function. Thank you all in advance

Answer

First of all your else is inside of if statement, which is wrong. Check that there is no need to add a continue; in your for loop as you are doing only one action.

Also check that all numbers that come from the form inputs are strings, than you have to get numbers with Unary plus (+) operator var num = +numbers[i].value;

Finally, i have created an array evenNumbers to collect all even numbers and based on that you can show up you message with a ternary operator - As the numbers are in an array, you can join them with Array.prototype.join() evenNumbers.join(', ')

Code:

function evenNumbers() {
  var numbers = document.getElementsByClassName('formInput'),
      evenNumbers = [];

  for (var i = 0, l = numbers.length - 1; i <= l; i++) {
    var num = +numbers[i].value;
    (num && num % 2 === 0) && evenNumbers.push(num);
  }

  document.getElementById('even').innerHTML = (evenNumbers.length) 
    ? 'Even numbers are: ' + evenNumbers.join(', ') 
    : 'There are no even numbers.';
}
input {
  display: block;
  margin: 2px;
}
<form>
  <input type="text" class="formInput">
  <input type="text" class="formInput">
  <input type="text" class="formInput">
  <input type="text" class="formInput">
  <input type="text" class="formInput">
  <input type="text" class="formInput">
  <input type="button" value="Show Even Numbers" onclick="evenNumbers()"/>
</form>

<hr>
<p>Result: <span id="even"></span></p>

Comments