I have three textfields namely :
The value of StateCode and Country code is set by default.
If the Telephone Number textfield is entered, I want the other two fields to be made mandatory.
If the Telephone Number is empty then it is not required. How can I do this ?
I create this fiddle:
html
<label id="lblStateCode">State Code</label>
<input type="text" id="stateCode" value="585" />
<label id="lblCountryCode">Country Code</label>
<input type="text" id="countryCode" value="552" />
<label id="lblPhone">Phone</label>
<input type="text" id="phone" />
js
$("#phone, #stateCode, #countryCode").on("blur",function(){
if($("#phone").val() != ""){
if($("#stateCode").val() == ""){
$("#lblStateCode").addClass("errorClass");
}
else{
$("#lblStateCode").removeClass("errorClass");
}
if($("#countryCode").val() == ""){
$("#lblCountryCode").addClass("errorClass");
}
else{
$("#lblCountryCode").removeClass("errorClass");
}
}
else{
$("#lblStateCode").removeClass("errorClass");
$("#lblCountryCode").removeClass("errorClass");
}
});
$(function(){
if($("#phone").val() != ""){
if($("#stateCode").val() == ""){
$("#lblStateCode").addClass("errorClass");
}
else{
$("#lblStateCode").removeClass("errorClass");
}
if($("#countryCode").val() == ""){
$("#lblCountryCode").addClass("errorClass");
}
else{
$("#lblCountryCode").removeClass("errorClass");
}
}
else{
$("#lblStateCode").removeClass("errorClass");
$("#lblCountryCode").removeClass("errorClass");
}
});
css
.errorClass{
color:red;
}
u need to apply jquery validations:
$("#form").validate({
rules: {
State: { required: function () {
if ($('#Telephone').val() != '') return true;
else return false;
},
Country: { required: function () {
if ($('#Telephone').val() != '') return true;
else return false;
}
}
messages: {
State: { required: "error messge" },
Country: { required: "error messge" }
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.