dafont
dafont

Reputation: 1

JavaScript - Form validation loop through specific fields

I'm wondering, what would be a short/good way of performing form validation in JavaScript by looping through all input-text as well as <select>, however, the condition on the select is that out of the 2 selects, ONLY one needs to be selected.

<form id="daform">
<input type="text" value="" name="name" id="name" />
<input type="text" value="" name="last" id="last" />

<select id="choice1" name="choice1">
 <option>Bye</option>
 <option>Hello</option>
</select>

<select id="choice2" name="choice2">
 <option>Bye</option>
 <option>Hello</option>
</select>

<input type="submit" />
</form>

Upvotes: 0

Views: 1108

Answers (3)

RSK
RSK

Reputation: 17516

Have you tried the jQuery validation plugin?
You can see a demo here.

Upvotes: 0

sioked
sioked

Reputation: 226

You really should use some javascript toolkit for help with this, but if not this might help:

validateSelectChoices = function(){
  return document.getElementById('choice1').selectedIndex || document.getElementById('choice2').selectedIndex;
}

This will check to see if one of the select boxes has the 'hello' value selected (keep in mind that dropdowns will always default to the first option in the list, in your case 'bye'.

Upvotes: 0

Sahil Muthoo
Sahil Muthoo

Reputation: 12496

Look into,document.getElementsByTagName().

Upvotes: 1

Related Questions