Link to home
Create AccountLog in
Avatar of Robert Granlund
Robert GranlundFlag for United States of America

asked on

Print Javascript Array on page

If I have form validation like this:
function validateForm() {
  var errors = [];
  var street_address=document.forms["myForm"]["street_address"].value;
  if (street_address==null || street_address=="") {
    errors.push("A street address must be filled out");
  }

  var city=document.forms["myForm"]["city"].value;
  if (city==null || city=="") {
    errors.push("A city name must be filled out");
  }

  if(errors.length > 0) {
    alert(errors.join("\n"));
    return false;
  }
}

Open in new window


How can I get the error messages to print in a div beside the form input where thee error is, instead of in an alert box?
Avatar of Sudaraka Wijesinghe
Sudaraka Wijesinghe
Flag of Sri Lanka image

If you want to display each error in it's own DIV tag, replace each push command with something like this.
document.getElementById('id_of_div_here').innerHTML = 'error message here';

Open in new window

Or, if you want to display them all in one DIV tag.
document.getElementById('id_of_div_here').innerHTML = errors.join('<br />');

Open in new window

Avatar of Robert Granlund

ASKER

Like This:

function validateForm()
{
	var errors = [];
  var od_position=document.forms["myForm"]["item_options[0][od_position]"].value;
if (od_position==null || od_position=="")
  {
  errors.document.getElementById('od_position').innerHTML = 'A position must be filled out';
  } 


Then: 

<tr>
		<td colspan="2"><div id="od_position"></div></td>
	</tr>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Sudaraka Wijesinghe
Sudaraka Wijesinghe
Flag of Sri Lanka image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer