Form preventDefault not working - javascript

I have a button that submits a hidden form:
<a href = "javascript:;" onclick = "document.getElementById('work-for-form').submit();">
Form:
<form id="work-for-form" action="localhost/update" method="PUT" style="display: none;">
{{ csrf_field() }}
</form>
And my js:
$("#work-for-form").submit(function(event){
event.preventDefault();
console.log(event);
});
But the form still loads a new page.
What am i doing wrong?
Thanks

The onclick event on your a is too strong to prevent the submission of the form. I would suggest the following to fix this:
<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>
see also https://jsfiddle.net/9hta6f48/

You can use return false or you can use eventListeners
<form onsubmit="alert('stop submit'); return false;" >
Or
function mySubmit(){
alert('Will not submit');
return false;
}
</script>
<form onsubmit="return mySubmit();" >
Or event listeners
var myFuncRef = function(event) { event.preventDefault() }
element.attachEvent('onclick', myFuncRef);

Your code must be inside $(document).ready or must be after the form is rendered,
$(document).ready(function(){
$("#work-for-form").submit(function(event){
event.preventDefault();
console.log(event);
});
});

Related

JQuery two forms toggled, show correct form on submit

I have two forms being toggled as shown below. What I need to figure out, is how to show the correct form once it has been submitted and page refreshed. It will default to the lookup_form only currently. I have been browsing the internet for answers, but am not finding any good examples.
<div class="lookup_form">
<form method="POST" action="" id="lookup_form"></form>
</div>
<div class="nolookup_form">
<form method="POST" action="" id="nolookup_form"></form>
</div>
<a href="#" class="show"> //Firing off the script
<script>
jQuery(document).ready(function($) {
$(".nolookup_form").hide();
$(".show").click(function(){
$(".lookup_form, .nolookup_form").slideToggle("slow, linear");
});
});
</script>
Essentially I need to always show after refresh the actual form that was submitted.
I guess that you know what form you should show at the backend that produces your page, you can just pass that to javascript
<script>
var showForm2 = <?php echo $shouldShow2ndForm?'true':'false'; ?>;
if( showForm2 ){
//hide form1 and show form2
} else {
//hide form2 and show form1
}
</script>
You may use cookie or LocalStorage:
before submitting the form you can save the form id for example with:
localStorage.setItem("formId", "lookup_form");
and on dom ready you can test the value of this:
localStorage.getItem("formId")
An example:
jQuery(document).ready(function($) {
//
// on DOM Ready get formId from localstorage
//
var formId = localStorage.getItem("formId");
if (formId == null) { // never set: set the default value
formId = 'nolookup_form';
localStorage.setItem("formId", formId);
}
//
// Hide the other form
//
$("form:not(#" + formId + ")").hide();
//
// on form submit save in localstorage current form id
//
$('form').on('submit', function(e) {
e.preventDefault();
localStorage.setItem("formId", this.id);
});
$("#show").on('click', function(e) {
$("#lookup_form, #nolookup_form").slideToggle("slow, linear");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="POST" action="" id="lookup_form">
<p>First form</p>
<button type="submit">Submit lookup</button>
</form>
<form method="POST" action="" id="nolookup_form">
<p>Second form</p>
<button type="submit">Submit nolookup</button>
</form>
<button type="button" id="show">Show</button>

submit event not firing

I want to submit a form when changing a drop down menu and want to prevent the page from reloading.
<script src="jquery-1.9.1.min.js"></script>
$(document).ready( function(){
$('#adv_search').submit( function(e){
alert('form submitted');
e.preventDefault();
});
});
<form id="adv_search" name="adv_search" method="post">
<select name="state" id="state" onchange="document.adv_search.submit()">
------
</select>
</form>
The plain javascript's submit() will trigger the natural submit process of a form, you cannot bypass it with a jquery's submit. So it is better to use jQuery alone for doing this,
$(document).ready(function() {
$("#state").change(function() {
$('#adv_search').submit();
});
$('#adv_search').submit(function(e) {
alert('form submitted');
e.preventDefault();
});
});
DEMO

form buttom disable onsubmit but form is not submited in javasc

<script>
function disableButton() {
var button = document.getElementById('accept');
button.disabled = true;
return true;
}
</script>
<form class="form-horizontal" name ="reg" method="post" action="" onSubmit="return disableButton()"/>
<button class="btn btn-info" name="sub" type="submit" id="accept">
<i class="icon-ok bigger-150"></i>
Submit
</button
When I hit submit button button is disbled but form is not submitted
Kindly any one please do favour
Instead of trying to add functions to your forms, you can simply catch your form submit, disable the button and allow it continue afterwards:
HTML Part:
<form class="form-horizontal" id="reg" name="reg" method="post" action="" />
Javascript Part:
<script type="text/javascript">
var form = document.getElementById('reg');
if (form.attachEvent) {
form.attachEvent("submit", processForm);
} else {
form.addEventListener("submit", processForm);
}
function processForm(e) {
if (e.preventDefault) e.preventDefault();
var button = document.getElementById('accept');
button.disabled = true;
return true;
}
</script>
If you wish to test it out, change above to return false;. This will disable the form submit and only disable the button.
Try the following:
<?php echo "<pre>";var_dump($_POST); echo "</pre>";?>
<script>
function disableSubmit() {
var button = document.getElementById('accept');
button.disabled = true;
myNiceForm.submit();
}
</script>
<form class="form-horizontal" id="myNiceForm" name ="reg" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<input type="text" name="myTestText"/>
<input id="accept" type="submit" onclick="disableButton()"/>
</form>
Things to consider:
If you want your HTML form to be posted, it needs to have a proper
value for the action attribute.
The button with the id of accept doesn't cause the form to be
posted, you also don't have any client-side script to do so, and it's
not a good practice, so a submit button has been added to the form.
When you click the submit button, the disableSubmit() function
invokes, and disables the button, and finally submits the form
programmatically, however, it's not necessary.
Your function does not follow proper syntax. But other than that there's no real reason to return true or false...
var acceptor = document.getElementById("accept");
acceptor.addEventListener("click", toggleButton);
function toggleButton() {
acceptor.disabled = "disabled"
}
<button class="btn btn-info" name="sub" type="submit" id="accept">
<i class="icon-ok bigger-150"></i>
Submit
</button>
Also, your button tag is not closed <button> </button>...
You can simply define the attribute are defined as a boolean true or false, which means you can specify their value and leave everything else out. i.e. Instead of disabled="disabled".
You may want to consider a function buttonToggler... so you can later switch it back easily (although I'm not sure this will help you...
Also... have the script at the bottom of the body rather than the top in-case of a preloading issue (this is not a foolproof solution to the problem where the JS loads faster than the HTML).
<script type="text/javascript">
function toggleButton() {
var acceptor = document.getElementById('accept');
if acceptor.disabled === true{
acceptor.disabled=false;
} else {
acceptor.setAttribute('disabled', 'disabled');
}
</script>
Try that.

jQuery not hiding divs (mvc 4)

I have 2 divs:
<div class="lobsummary">
<input type="submit" name ="sbmtbtn">
<input type="submit" name ="sbmtbtn">
</div>
<div class="applicationsummary">
</div>
I want to show applicationsummary when sbmtbtn is submitted so I used the below script:
$('.lobsummary input:submit').submit(function (event) {
$('.applicationsummary').show();
$('.lobsummary').hide();
});
But its not working.
EDIT: The divs are enclosed in <% Html.BeginForm("Index", "Home"); %> which I am using to pass values to my controller from the view.
Use event.preventDefault() it stops the default action
$('.lobsummary input[type=submit]').click(function (event) {
event.preventDefault();
alert($(this).index() + 1);
$('.applicationsummary').show();
$('.lobsummary').hide();
});
#Rajaprabhu Aravindasamy is right,use submit() over a form:
$("form").submit( function () {
return false;
} );
HTML on the client side will be like:
<div class="lobsummary">
<form action="/"method="post">
<input type="submit" name ="sbmtbtn">
</form>
<form action="/"method="post">
<input type="submit" name ="sbmtbtn">
</form>
</div>
<div class="applicationsummary">
</div>
Just use click() to test your jquery selection:
$('.applicationsummary').hide();
$(".lobsummary form:eq(0)").click(function () {
alert(1)
$('.applicationsummary').show();
});
$(".lobsummary form:eq(1)").click(function () {
alert(2)
$('.applicationsummary').hide();
});
Then replace the click to submit.
When the form was submitted, it reloaded the whole page and that's why it was not hiding because it was going back to its default view. So I used if statements in my view to hide the forms.

How can I stop event propagation with jquery

I'm submitting a form with jquery and can't seem to stop the page from reloading after the form submits.
My current code looks like this:
HTML:
<form class="form-horizontal" method="post" action="#" name="basic_validate" id="basic_validate" />
<div class="control-group">
<label class="control-label">Image Path</label>
<div class="controls">
<input type="text" name="imagepath" id=imagepath />
</div>
</div>
<div class="form-actions">
<input type=button value="Send" id="sendemailbtn" class="btn btn-primary" />
</div>
</form>
jQuery:
$("#sendemailbtn").click(function(e) {
e.preventDefault();
$("#basic_validate").submit();
if ($("#basic_validate").children('.control-group').hasClass('error')) {
return false;
} else {
$.post('send_email.php', $("#basic_validate").serialize(), function(data) {
// I see output on the server side but never hit this area after the submission,
console.log(data);
}, "json");
}
});
$("#basic_validate").submit();
Is your culprit. That line submits the form and makes the page reload.
According to the submit doc,
[...] We can cancel the submit action by calling .preventDefault() on
the event object or by returning false from our handler.
As .preventDefault() doesn't seem to work for you, try :
$("#basic_validate").submit(function(){
if ($("#basic_validate").children('.control-group').hasClass('error')) {
return false;
}
else {
$.post('send_email.php', $("#basic_validate").serialize(), function(data) {
// I see output on the server side but never hit this area after the submission,
console.log(data);
}, "json");
}
return false; //This prevents reloading
});
That's because .submit() works that way. If you want to submit the form with AJAX then you want to make an AJAX request manually with $.post without .submit():
$("#sendemailbtn").click(function (e) {
e.preventDefault();
if (!$("#basic_validate").children('.control-group').hasClass('error')) {
$.post('send_email.php', $("#basic_validate").serialize(),
function(data) {
console.log(data);
}, "json");
}
});

Categories