2017-09-03 4 views
0

を働いていない私は、隠しフォームサブミットボタンいますフォームのpreventDefault

<a href = "javascript:;" onclick = "document.getElementById('work-for-form').submit();"> 

フォーム:

<form id="work-for-form" action="localhost/update" method="PUT" style="display: none;"> 
{{ csrf_field() }} 
</form> 

そして、私のJS:

$("#work-for-form").submit(function(event){ 
    event.preventDefault(); 
    console.log(event); 
}); 

は、しかし、フォームがまだロード新しいページ。

私は間違っていますか? ありがとう

+0

それはここで、 – user3844579

+0

ちょうどタイプミス/アップデートですが、あなたはfalseを返す代わりに試してみました。 preventDefault – Manav

+0

あなたのコードが実行されないようにするJSエラーがあるように思えます - コンソールをチェックしましたか? – Utkanos

答えて

1

あなたのaのonclickイベントは、フォームの送信を妨げるほど強すぎます。私はこの問題を解決するために以下のことをお勧めします:

<a href="javascript:;" >form submit</a> 

<form id="work-for-form" action="/update" method="PUT" style="display: none;">{{ csrf_field() }}</form> 

<script> 
$("a").on("click",function(){ 
    $("#work-for-form").submit(); 
}) 
$("#work-for-form").submit(function(event){ 
    alert('intercept'); 
    event.preventDefault(); 
    console.log(event); 
}); 
</script> 

はあなたがreturn falseを使用するかはeventListeners

<form onsubmit="alert('stop submit'); return false;" > 

それとも

function mySubmit(){ 
     alert('Will not submit'); 
     return false; 
    } 
</script> 

<form onsubmit="return mySubmit();" > 

やイベントを使用することができますもhttps://jsfiddle.net/9hta6f48/

0

を見ますリスナー

var myFuncRef = function() { event.preventDefault() } 

element.attachEvent('onclick', myFuncRef); 
0

あなたのコードは.ready $(ドキュメント)内でなければならないか、フォームがレンダリングされた後でなければならない、

$(document).ready(function(){ 
    $("#work-for-form").submit(function(event){ 
    event.preventDefault(); 
    console.log(event); 
    }); 
}); 
関連する問題