好吧,所以我一直在四處尋找條件語句在JQuery中,但我無法找到一個解決方案如何檢查,以確保至少有一個兩個輸入框有內容。聯繫表單,填寫兩個輸入字段之一檢查
這是我迄今爲止
$('#send').click(function(){ // when the button is clicked the code executes
$('.error').fadeOut('fast'); // reset the error messages (hides them)
var error = false; // we will set this true if the form isn't valid
var name = $('input#namn').val(); // get the value of the input field
var message = $('textarea#meddelande').val(); // get the value of the textarea
var phone = $('input#telefon').val(); // get the value of the input field
var email_compare = /^([a-z0-9_.-]+)@([da-z.-]+).([a-z.]{2,6})$/; // Syntax to compare against input
var email = $('input#epost').val(); // get the value of the input field
if(name == "" || name == " " || name == "namn" || name.length < 2) {
$('input#namn').val("namn").css({ 'color': 'red' });
error = true; // change the error state to true
}
if(phone == "" || phone == " " || phone == "telefon" || phone.length < 5) {
$('input#telefon').val("telefon").css({ 'color': 'red' });
error = true; // change the error state to true
}
if (email == "" || email == " " || email == "epost") { // check if the field is empty
$('input#epost').val("epost").css({ 'color': 'red' });
error = true;
}else if (!email_compare.test(email)) { // if it's not empty check the format against our email_compare variable
$('input#epost').val("kontrollera epost").css({ 'color': 'red' });
error = true;
}
if(message == "" || message == " " || message == "meddelande" || message.length < 10) {
$('textarea#meddelande').val("meddelande").css({ 'color': 'red' });
error = true; // change the error state to true
}
if(error == true) {
$('#err-form').fadeIn('fast');
return false;
}
var data_string = $('#ajax-contactform').serialize(); // Collect data from form
$.ajax({
type: "POST",
url: $('#ajax-contactform').attr('action'),
data: data_string,
timeout: 6000,
error: function(request,error) {
if (error == "timeout") {
$('#err-timedout').fadeIn('fast');
}
else {
$('#err-state').fadeIn('fast');
$("#err-state").html('Ett fel uppstod: ' + error + '');
}
},
success: function() {
$('#ajax-contactform').fadeOut('fast');
$('#success-msg').fadeIn('slow');
}
});
return false; // stops user browser being directed to the php file
}); //結束點擊功能
而且其工作的罰款。但是,我想提出一個條件聲明來檢查並確保電子郵件或電話有內容。我不想迫使人們不得不離開這兩個,但至少有一個。
因此,如果手機有內容(只有數字,沒有單詞「電話」),則電子郵件不再是強制性的,反之亦然。如果電子郵件有內容,則仍需檢查以確保其有效的電子郵件。
我該怎麼做呢?我在一個有點丟在這裏:(
我試着添加這個,但它不起作用。當發送它仍然要求兩個。 – axelra82 2013-03-28 10:19:09