I have a system that can output 0 or more select boxes and I need to add some Javascript/JQuery validation. I am new to writing JQuery and I am stuck getting the content of the text label for the error message: Here is an example of my select boxes form:
<div id="prodOptions" class="sale">
<p class="elevenText floatLeft">Product options</p>
<div class="floatLeft"><label for="colour">Select Colour</label>
<select name="colour">
<option value="" selected="selected">---</option>
<option value="blue">Blue</option>
</select>
</div>
<div class="floatLeft">
<label for="size">Select Size</label>
<select name="size">
<option value="" selected="selected">---</option>
<option value="small">Small</option>
</select>
</div>
<div class="floatLeft">
<label for="flavour">Select Flavour</label>
<select name="flavour">
<option value="" selected="selected">---</option>
<option value="cherry">Cherry</option>
</select>
</div>
and here is my javascript function which is called on form submission (the alerts are for testing):
function validateOptions()
{
selectList = $('select').get();
message = "";
for(i=0; i<selectList.length; ++i)
{
//alert(selectList[i].name);
selector = "for[=\""+selectList[i].name+"\"]";
alert(selector);
alert($(selector.value));
message += ($(selectList[i]).prop('selected', true).val() == "") ? "Please enter a value for \r\n" : "";
}
alert(message);
}
Your attribute syntax is incorrect. Your selector should be
From there, you should fetch the label’s
.html(), rather than.val()Also, labels should reference element ID’s, rather than names. It is also not very clear how you want your message to be formatted. You should be able to do something like this:
You could also format your error message like so: