2013-03-28 1 views
1

좋아, 그래서 나는 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 

}); // end click function

잘 작동합니다. 그러나 조건부 성명서를 작성하여 이메일 또는 전화 중 하나에 내용이 있는지 확인하고 싶습니다. 나는 사람들이 둘 다 떠날 것을 강요하고 싶지 않지만 적어도 하나는 남겨 두어야한다.

전화가 콘텐츠 (전화 번호가 아닌 숫자 만)가 있으면 전자 메일은 더 이상 필수 항목이 아니며 그 반대의 경우도 마찬가지입니다. 전자 메일에 내용이있는 경우 유효한 전자 메일인지 확인해야합니다.

어떻게 이렇게 가겠어요? phone가있는 경우 emai리터가 확인되지 않았거나 다른 경우 email이 ..phone 존재 있도록 내가 .. 여기 손실 :(

답변

0

그래서 이것이 전체 코드를 작성하는 것보다 할 ... jquery validation plugins에 모습을 쉽게하도록합니다 recommened 그러나

if(phone == "" || phone == " " || phone == "telefon" || phone.length < 5) { 
    $('input#telefon').val("telefon").css({ 'color': 'red' }); 
    error = true; // change the error state to true 
} else if (email == "" || email == " " || email == "epost") { // check if the field is empty 
//^^^ HERE 
    $('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; 
} 

을 선택하지 내가 결국 사용 했어.

$(function() { 
     var input = $('input[type=text], textarea'); 

     input.focus(function() { 

      var ibf = $(this); 

      if(ibf.val() == ibf.attr('title')) 
       ibf.val(''); 

      if(ibf.css({ 'color': 'red' })) 
       ibf.css({ 'color': '' }); 

     }).blur(function() { 
      var ibb = $(this); 

      if(ibb.val() == '') 
       ibb.val(ibb.attr('title')); 
     }); 

    }); 

    $("#telefon").keydown(function(e){ 
     var key = e.charCode || e.keyCode || 0; 
     // allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY 
     return ( 
      key == 8 || 
      key == 9 || 
      key == 46 || 
      (key >= 37 && key <= 40) || 
      (key >= 48 && key <= 57) || 
      (key >= 96 && key <= 105)); 
    }); 

    $('#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 input field 
     var phone = $('input#telefon').val(); // get the value of the input field 
     var email_compare = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i); // 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 
     } 

     var phone_valid = phone.length >= 6; 
     var email_valid = email_compare.test(email); 

     if(phone_valid && phone != 'telefon' || email_valid){ //one of two are populated 
      //make donut 

     }else{ 
      /*$('input#telefon').val("telefon").css({ 'color': 'red' }); 
      $('input#epost').val("epost").css({ 'color': 'red' }); 
      $('#err-form-contact').fadeIn('fast');*/     
      error = true; 

      if (!phone_valid && phone != 'telefon' && phone != ''){ 
       $('input#telefon').val("telefon").css({ 'color': 'red' }); 
      } 

      if (!email_valid && email != 'epost' && email != ''){ 
       $('input#epost').val("epost").css({ 'color': 'red' }); 
      } 
     } 

     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 
    }); // end click function 

이제 TWO 상자 중 하나 (이메일/전화)에 콘텐츠가 있는지 확인합니다.

1
if (! ((phone.length && phone != 'telefon') || email.length)) { 
    //none of the above has input 
} 
+0

추가를 시도했지만 작동하지 않습니다. 보내기를 누르면 아직 두 가지를 묻습니다. – axelra82

0

방금 ​​전화 및 이메일 if 조건 사이 else if를 추가 할 수의 비트에있어 내가 사용하고 사용자 정의 ... 오히려

+0

똑같은 문제는이 질문을 던지기는하지만 여전히 두 가지를 요구합니다. 나는 전화로 채우기를 시도했지만 여전히 이메일을 요구한다. (예, 포럼에서 유효성 검사 플러그인을 보았습니다. 좀 더 자세히 살펴 봐야 할 수도 있습니다.) – axelra82

+0

예 그건 .... – bipen

+0

jquery 유효성 검사 플러그인을 조금 봤는데 JS에 익숙하지 않다 .JVP가 멋지다. JS를 알고 있고 내가하는 일을 알고 있다면. 다른 한편으로 위의 contactform 유효성 검사를 함께 잘라내어 붙일 수있었습니다. 그래서 두 상자 (전화 및 전자 메일) 중 적어도 하나에 채워지는 확인을 할 수 있다면 정말 좋습니다 JVP보다 쉬운 방법은 없나요? 다른 해결책은 좋은 것처럼 보이지만 작동하지 않습니다. 전화가 입력되면 전자 메일을 요청하고 그 반대도 마찬가지입니다. – axelra82