开发者

JavaScript - Form validation loop through specific fields

开发者 https://www.devze.com 2023-01-30 18:20 出处:网络
I\'m wondering, what would be a short/good way of performing form validation in JavaScript b开发者_JAVA技巧y looping through all input-text as well as <select>, however, the condition on the sel

I'm wondering, what would be a short/good way of performing form validation in JavaScript b开发者_JAVA技巧y 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>


Look into,document.getElementsByTagName().


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'.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消