I have a table which contains two textboxes (textbox1 ,textbox2). Both of the textboxes are mandatory. If I don't enter value in textbox1 and enter value textbox2, or vice versa , I should get a error message. How can we achive this with jQuery?
$("[id^=textboxid]").each(function(){
if ($(this).val().length > 0) {
// do something alert ...
}
}
);
this run over all textbox that the id start with textboxid , like textboxid1, textboxid2 ...
Assuming that you actually have a form, and would like this validation to occur on the submission of the form, first of all, add in your warning message:
<p class="warning">Both textboxes need to be filled</p>
Then, add in the following Javascript
$('form').submit(function(){
var inputValid = true;
$('form textarea').each(function(){
if(!this.value){
$('.warning').show();
return false;
}
});
});
This will, on the submission of the form, loop through all textearea
s, and display the error message, as well as cancel the form submission if any of the textarea
s in the form are not filled.
The easiest way I found to do this is to add a class to your textbox such as 'requiredField'.
<input type="text" class="requiredField" />
You can then get all required fields in the table using the 'find' function.
textboxes = $('#tableid').find('.requiredField');
and then iterate over them using the 'each' function
textboxes.each(function() {
if(this.value.length==0){
//do something here
}
}
With something like this I usually color the border of the textbox red, and add an alert to tell the user they must complete all the required fields.
Here is the final code.
requiredFields = $('#tableid').find('.requiredField');
var allFieldsComplete = true;
requiredFields.each(function(index) {
if (this.value.length == 0) {
$(this).addClass('requiredIncomplete');
allFieldsComplete = false;
} else {
$(this).removeClass('requiredIncomplete');
}
});
if(!allFieldsComplete){
alert('Please complete all required fields');
}
return allFieldsComplete;
You will also need to specify a 'requiredIncomplete' style in your CSS. What this will do is check all textboxes in the table to see if they contain data. If a textbox doesnt contain data it adds the 'requiredIncomplete' class to it (which contains some styling to set it apart from the other textboxes), otherwise it removes the class. It will then return true if all fields contain data or false if one of them is missing data.
// create a custom jQuery expression filter, called :hasValue
jQuery.expr[':'].hasValue = function(elem, index, match) {
return jQuery(elem).val() !== '';
};
// textbox logic
if($('table textbox:hasValue').length !== 2) {
alert('error message');
}