0

jQuery Validation プラグインを使用して、2 つの時間フィールドを検証しようとしています。end time1つのフィールドで「すべて」が選択されている場合、それが他のフィールドにも当てはまり、より大きいことを確認したいstart time

HTMLは次のとおりです。

 <form id="schedule">
 <select name='start_hour' id='start_hour'>
    <option value='All00'>All</option>
    <option value='0000'>00</option>
    <option value='0100'>01</option>
    <option value='0200'>02</option>
    <option value='0300'>03</option>...
</select>
 and 
<select name='end_hour' id='end_hour'>
    <option value='All00'>All</option>
    <option value='0000'>00</option>
    <option value='0100'>01</option>
    <option value='0200'>02</option>
    <option value='0300'>03</option>...
</select>
 </form> 

カスタムルールは次のとおりです。

 jQuery.validator.addMethod(  "schedule", function(value, element) { 

    var start_hour = document.getElementsByName("start_hour");
    var end_hour = document.getElementsByName("end_hour");

    alert(start_hour.value);
    alert(end_hour.value);
    if (start_hour.value == "All00" && end_hour.value !="All00") 
    { 
        alert('end hour all error')
        return false;
          }
        else if (end_hour.value == "All00" && start_hour.value !="All00") 
    { 
        alert('start hour all error')
        return false;
          }
          else if (end_hour.value <= start_hour.value ){
              alert('end hour must be larger error')
        return false;
          }

    else return true; 
  },  "Error with schedule");

何らかの理由でalert(start_hour.value);「未定義」を返します私も使用しようとしましたがgetElementbyID、それも失敗しました。私はJavascriptに本当に慣れていないので、おそらく単純なものだと思います。

ここにJsFiddle

4

4 に答える 4

2

jQuery で getElementsByName を使用する必要はありません。代わりにこれを試してください。jQuery Attribute Selector

$('select[name="start_hour"]')

または、名前と同じIDを持っているように見えるので、代わりにこのセレクターを使用できます

$('select#start_hour')

Validator メソッドは次のように構築する必要があります

 jQuery.validator.addMethod(  "schedule", function(value, element) { 
    var start_hour = $('select#start_hour');
    var end_hour = $('select#end_hour');

    alert(start_hour.val());
    alert(end_hour.val());

    if (start_hour.val() == "All00" && end_hour.val() !="All00") { 
        alert('end hour all error')
        return false;
    }
    else if (end_hour.val() == "All00" && start_hour.val() !="All00") { 
        alert('start hour all error')
        return false;
    }
    else if (end_hour.val() <= start_hour.val() ) {
        alert('end hour must be larger error')
        return false;
    }
    else return true; 
  },  "Error with schedule");
于 2011-05-17T21:41:53.937 に答える