Reputation: 51
Need some help to validate an input and dropdown. Both can be empty or both must be filled. If the user forgets to fill the text input in column 5 and select a value from the dropdown in column 6 alert message should appear or if the user forgets to choose from the dropdown in column 6 and fill in the text box in column 5 alert message must also appear. The validation must operate on each created row.
Check jsfiddle here.
I'm thinking something like this:
$('input[name=QtePack]').each(function (obj) {
var $QtePack = $(this).val();
var tr = obj.closest('tr');
var $PackType = tr.find("[id^='Pack_Type_']").val();
if ($QtePack.length > 0 && $PackType == '') {
valid = false;
$PackType.addClass('error');
}
});
Thanks :-)
Upvotes: 0
Views: 83
Reputation: 6776
see this demo http://jsfiddle.net/BE5Lr/4093/
$('#SendButton').click(function (e) {
// Validate if empty
var valid = true;
$('.required').each(function () {
var $this = $(this);
if ($.trim($(this).val()) == '') {
valid = false;
$(this).addClass('error');
} else {
$(this).removeClass('error');
}
});
// changes starts
$("input[name='QtePack']").each(function(){
var ip = $(this);
var sel = $(this).closest("tr").find("select[name='PackType']");
if((ip.val().length==0 && sel.val().length!=0) || (ip.val().length!=0 && sel.val().length==0))
{
alert('enter both type and quant or leave both blank');
ip.addClass('error');
sel.addClass('error');
}
});
// changes ends
// Show validation alert
if (valid == false) {
e.preventDefault();
alert('Some field(s) is required.');
return false;
}
});
Upvotes: 1
Reputation: 695
update your code as follows :
$('input[name=QtePack]').each(function (obj) {
var $QtePack = $(this).val();
alert("QtePack = "+$QtePack);
var tr = $(this).closest('tr');
var reqelement=tr.find("[id^='Pack_Type_']");
var $PackType = tr.find("[id^='Pack_Type_']").val();
alert("PackType = "+$PackType);
if ($QtePack.length > 0 && $PackType == '') {
valid = false;
$(reqelement).addClass('error');
}
if($QtePack.length == "" && $PackType != '')
{
valid = false;
$(reqelement).removeClass('error');
$(this).addClass('error');
}
if($QtePack.length == "" && $PackType == '')
{
valid = true;
$(this).removeClass('error');
$(reqelement).removeClass('error');
}
});
Upvotes: 0