I want to create a dynamic alert from a specific input value within each form. I have many forms on a page. Each alert needs to be slighly different. I am using two of the forms input values to produce the custom message. <input type="hidden" name="on0" value="Size"> & <input type="hidden" name="on1" value="Color">. I have the alert working for the first form on the page, but after the second form, my alert does not match the selected input value of that form. How can I target a specific instance of these input values within the form a user interacts with?
Here is a simplified version of my code showing only two forms:
example on – jsfiddle
<form method="post" class="list1">
<input type="hidden" name="on0" value="Size">
<select name="os0">
<option value="">-- Choose a Size --</option>
<option value="Short">Short</option>
<option value=" Medium">Medium</option>
<option value=" Long">Long</option>
</select>
<input type="hidden" name="on1" value="Color">
<select name="os1">
<option value="">
-- Choose a Color --
</option>
<option value="ivory">ivory</option> <option value=" black"> black</option>
</select>
<input type="button" value="Add to Cart" class="catalog">
</form>
<!-- seconed form start -->
<hr />
<form method="post" class="list2">
<input type="hidden" name="on0" value="Option">
<select name="os0">
<option value="">-- Choose a Option --</option>
<option value="Option 1">Option 1</option>
<option value="Option 2">Option 2</option>
<option value="Option 3">Option 3</option>
</select>
<input type="hidden" name="on1" value="Accent Color">
<select name="os1">
<option value="">
-- Choose a Choose a Accent Color --
</option>
<option value="red">Red</option>
<option value="yellow">yellow</option>
<option value="orange">orange</option>
</select>
<input type="button" value="Add to Cart" class="catalog">
</form>
And my js
$(document).ready(function(){
var size_x = $("input[name='on0']").val();
var color_x = $("input[name='on1']").val();
function popWarning() {
if ($("select[name='os0']").val() === "") {
alert('Please choose a ' + size_x);
return false;
}
if ($("select[name='os1']").val() === "") {
alert('Please choose a ' + color_x);
return false;
}
}
$("input.catalog").click(function() {
popWarning();
});
});
How do you expect the script to know which form (and therefore elements with the same
nameattribute) you’re talking about without specifying it? Try something like this:Working example:
http://jsfiddle.net/7YJ63/6/
This way,
popWarningis able to grab the parent form from theinput.catalogthat triggered it by click, viaobj(thispassed in). Then, all elements/values are found withfindbecause you know that the elements you’re looking for are a descendent of the form.