2016-04-10 17 views
0

入力フィールドが空の の場合、次のページにアクセスしないようにします。フィールドが空でボタンをクリックするとアラートが表示されますが、[OK]をクリックすると次のページに移動します。inputFieldが入力されていない場合、次のページへのナビゲートを無効にする

<script type="text/javascript"> 
    window.onload = function(){ 

     function checkFilled(inputField) { 

      if(inputField.value.length > 1) { 
       return true; 
       } 
      else { 
        alert('field1 is not filled in'); 
        $("#button1").click(function(e){ 
        e.preventDefault();  
        });         
        return false; 
       } 
      }; 

      document.getElementById('button1').onclick = function() { 

      var field1 = document.getElementById('field1'); 
      checkFilled(field1);  
      }; 
     }; 

</script> 






<input type="text" name="field1" id="field1"/> 

    <a href="nextpage.html"> 

     <div id="button1"></div> 

    </a> 
+0

どのように警告することができますが全く表示されていますか? 'checkFilled()'は実際には呼び出されません。あなたのコードは質問と異なっていますか? – MrCode

答えて

1

あなたはhref属性が設定され、inputFieldは空ですが、次のページにすぐにあなたを取得されa tagを使用。これは、あなたが欲しいものを行う必要があります。

window.onload = function(){ 
 
    function checkFilled(inputField) { 
 
    if(inputField.value.length > 1) { 
 
     return true; 
 
    } 
 
    else { 
 
     alert('field1 is not filled in'); 
 
     return false; 
 
    } 
 
    }; 
 
    document.getElementById('button1').onclick = function() { 
 
    var field1 = document.getElementById('field1'); 
 
    return checkFilled(field1); 
 
    }; 
 
};
<input type="text" name="field1" id="field1"/> 
 
<form action="nextpage.html"> 
 
    <input id="button1" type="submit" value="next"> 
 
</form>

それとも、代わりにボタンのaタグを使用することを好む場合:

function checkFilled() { 
 
    if(document.getElementById("field1").value.length > 1) { 
 
    window.location.href="nextpage.html"; 
 
    } 
 
    else { 
 
    alert('field1 is not filled in'); 
 
    return false; 
 
    } 
 
}
<input type="text" name="field1" id="field1"/> 
 
<a href="#" onclick="checkFilled();">next</a>

関連する問題