I'm using the jquery.form.js from here: http://www.malsup.com/jquery/form/. I want to validate the text of the text input from the form before submitting. Validation goes to
'search_validate.php'. This part works fine. If validation passes, the form action's is changed. That works too.
Getting the form to submit normally after changing the action attribute doesn't work. The browser never goes to the '/videos/search/' page. It stays on the same page. I see the '/videos/search/' page loading in Firebug over and over though.
<form id="search" method="post" action="">
<input type="text" id="query" />
<input type="image" id="searchmag" src="blah.jpg" ?>
</form>
<script>
$(function(){
$('#searchmag').click(function(){
$('#search').attr('action','/search_validate.php');
$('#search').ajaxForm(function(data, textStatus){
if ((data.indexOf('letters & numbers only')>-1)) {
$('#query').css('color','#FF0000').val(data);
$("#query").unbind("click").click(function(){
$('#query').css('color','#848484').val('');
});
} else {
$('#search').attr('action','/videos/search/' + $('#query').val());
$('#search').submit();
}
});
});
});
</script>
This always works for me:
$("#myForm").on("submit", function(event) {
event.preventDefault();
// Validate form, returning on failure.
$(this).off("submit");
this.submit();
});
I hope this helps!
Related
I have a button (<input type="submit">). When it is clicked the page reloads. Since I have some jQuery hide() functions that are called on page load, this causes these elements to be hidden again. How do I make the button do nothing, so I can still add some action that occurs when the button is clicked but not reload the page.
There is no need to use JS or jQuery.
to stop the page to reload, just specify the button type as 'button'.
If you don't specify the button type, the browser will automatically set it to 'reset' or 'submit' which causes the page to reload.
<button type='button'>submit</button>
Use either the <button> element or use an <input type="button"/>.
In HTML:
<form onsubmit="return false">
</form>
in order to avoid refresh at all "buttons", even with onclick assigned.
You could add a click handler on the button with jQuery and do return false.
$("input[type='submit']").click(function() { return false; });
or
$("form").submit(function() { return false; });
In HTML:
<input type="submit" onclick="return false">
With jQuery, some similar variant, already mentioned.
You can use a form that includes a submit button. Then use jQuery to prevent the default behavior of a form:
$(document).ready(function($) {
$(document).on('submit', '#submit-form', function(event) {
event.preventDefault();
alert('page did not reload');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form id='submit-form'>
<button type='submit'>submit</button>
</form>
You could also use JavaScript for that:
let input = document.querySelector("input");
input.addEventListener("submit", (event) => {
event.preventDefault();
})
As stated in one of the comments (burried) above, this can be fixed by not placing the button tag inside the form tag. When the button is outside the form, the page does not refresh itself.
I can't comment yet, so I'm posting this as an answer.
Best way to avoid reload is how #user2868288 said: using the onsubmit on the form tag.
From all the other possibilities mentioned here, it's the only way which allows the new HTML5 browser data input validation to be triggered (<button> won't do it nor the jQuery/JS handlers) and allows your jQuery/AJAX dynamic info to be appended on the page.
For example:
<form id="frmData" onsubmit="return false">
<input type="email" id="txtEmail" name="input_email" required="" placeholder="Enter a valid e-mail" spellcheck="false"/>
<input type="tel" id="txtTel" name="input_tel" required="" placeholder="Enter your telephone number" spellcheck="false"/>
<input type="submit" id="btnSubmit" value="Send Info"/>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('#btnSubmit').click(function() {
var tel = $("#txtTel").val();
var email = $("#txtEmail").val();
$.post("scripts/contact.php", {
tel1: tel,
email1: email
})
.done(function(data) {
$('#lblEstatus').append(data); // Appends status
if (data == "Received") {
$("#btnSubmit").attr('disabled', 'disabled'); // Disable doubleclickers.
}
})
.fail(function(xhr, textStatus, errorThrown) {
$('#lblEstatus').append("Error. Try later.");
});
});
});
</script>
Use event.preventDefault() in the first line of your event function.
Buttons must be of the type button and contain type="submit" in the button html.
I need to disable the submit buttons of many forms on many different pages after they are clicked, in order for the form to be only submitted once.
I know the proper way to check for double submissions is better done server-side rather than just disabling a button, but I'm looking for a simple solution that should do for now.
Here is one of the buttons:
<input type="submit" value="Save" />
Here is the script I wrote
$(document).ready(function(){
$("input").each(function(index){
//find all submit buttons with value "Save"
if($(this).attr("value")=="Save"){
console.log(index);
$(this).click(function(){
//disable the button
$(this).attr("disabled","true");
console.log("save btn clicked");
//submit the form
var form = $(this).closest("form");
console.log(form.attr("action"));
form.submit();
});
}
});
});
Everything works fine until the part where I try to submit, the button disables just fine.The problem is that it's not submitting (it does without this script).
Why is it not submitting? Did I fail to find the form or .. ?
try...
$(form).submit();
instead of
form.submit();
$('form:has(input[value="Save"])').on('submit', function() {
alert('form submitted');
$('input[value="Save"]', this).attr('disabled', true);
});
input[disabled="disabled"] {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="#">
<input type="submit" value="Save" />
</form>
I am trying to submit my form named 'vform' by using javascript and ajax.Here
Button named 'show' is being used to show the 'div' containing form named vform and that form calls codevalidate function and there it submits the form using some ajax code..Where i am getting error is vform.submit().Here's the html and js code(I know error is in if condition but do not know where)
html:
<button id="show" onClick="javascript:codefield(); return false";>Apply for Discount</button>
<div id="apply" style="display:none">Voucher code<br>
<form id="vform" name="vform" action="" method="post" onsubmit="javascript:codevalidate(); return false;" >
<input type="text" name="code" id="code"><br>
<span id="error" style="color:red"></span><br>
<input type="submit" name="btn" value="apply" id="btn" ></form>
</div>
javascript:
function codevalidate()
{
if(document.getElementById('code').value!=="")
{
$.post("couponajax.php",{code:$("#code").val()},
function(data)
{
if(data=='1')
{
//alert("success");
vform.submit();
return true;
}
else
{
document.getElementById('error').innerHTML="You have entered a wrong code!";
return false;
}
});
}
else
{
document.getElementById('error').innerHTML="Code can't be empty!";
return false;
}
return false;
}
codefield function is just displaying the div on onclick event and ajax call is just checking whether the code exists in database or not..if exists returns 1 else 0.
The problem is alert message is being displayed but form is not being submitted. How can I fix this problem?
I think you are missing jquery selector.
Try to replace
vform.submit();
with
$("#vform").submit();
or you can call submit button click event like
$("#btn").click();
You are not selecting the form.
Try changing;
vform.submit();
To:
$("#vform").submit();
Please try this one, works for me.
document.getElementById("vform").submit();
Try this
document.forms["vform"].submit();
Hope this helps.
You don't have to submit form with code.
Just call validation function and control submit flow with preventDefault function.
var codevalidate = function(e) {
if (!validationCode) { // if validation code didn't pass
e.preventDefault(); // prevent form from submitting
}
}
// register callback that will be called when user submits form
document.getElementById("vform").addEventListener('onsubmit', codevalidate);
That way form will be submitted by user only if validation pass.
Also check if your data is actually returning '1' by calling console.log(data);
Form will be submitted to the current address if action is empty, is that ok?
The thing is that:
action attribute of your form element is empty. So it is being submitted but to the same page from which it is calling the .submit() method.
so you should specify action attribute first of all like:
<form id="vform" name="vform" action="vfrom_submit.php" method="post"
onsubmit="javascript:codevalidate(); return false;" >
.....
</form>
Also try changing
vform.submit();
to:
$("#vform").submit();
//OR
// document.getElementById("vform").submit();
// Although vform.submit() can also work.
Hope it helps, cheers :)!
You should use:
document.getElementById("vform").submit();
Update:
Try removing "return false;" from onsubmit attribute and remove "vform.submit();" from the if condition as well.
I have a form which has fields pre-filled with a default value, like this:
<input type=text name=first value="First Name" class="unfilled" />
When the textbox is clicked, the class unfilled is removed from the textbox, and the textbox is made blank so the user can type in his/her own info.
The problem is that when the form is submitted, its getting submitted with these default values, which is messing up the server side validation. How can I do it so that when the form is submitted, all the fields which have a default value are made blank, so the server side validation would throw the error: 'Please fill in this field'?
I'm trying the following code which isn't working:
$("#myForm").submit(function()
{
$(".unfilled").val('');
}
);
This does make the fields blank, but the server still receives them with their previous default values.
I think you simply have a syntax error. You're missing the closing parenthesis on your submit method.
I just whipped this up and it works fine
<!DOCTYPE html>
<html>
<body>
<?php
var_dump($_POST);
?>
<form action="test.php" method="post">
<input type="text" name="first" value="First Name" class="unfilled">
<input type="submit">
</form>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function($) {
$('form').submit(function() {
$('.unfilled').val('');
});
});
</script>
</body>
</html>
You need to stop the form execution first, change the values, and then manually submit the form.
$("#myForm").submit(function(e)
{
// Stop the form submit
e.preventDefault();
$(".unfilled").val('');
$(this).submit();
}
You have to return true; if you want the form to submit, or false, if you don't.
The problem with this approach is that the fields will 'blink' before posting the values, thus creating a bit of unprofessional feel.
It is better to use hidden values and set them in submit() event.
I think you need the .click() function of JQuery.
Example:
$(function () { // shorthand for document.ready
$('.unfilled').click(function () {
$(this)
.val('')
.removeClass('unfilled');
})
});
UPDATE
Sorry, i missunderstand you, thought you need a feature like a placeholder.
Of couse you can do it with return false;, but this cancel the submitting. Or like GreenWebDev says to use e.preventDefault();.
I am building a site which uses jQUery validation plugin and want things validated before submitting the form. My code looks like follows
<form>
<input type="button" value="Submit the Form" onclick="validateAndSubmit()" />
</form>
<script language="javascript">
function validateAndSubmit(){
//do some validation and then submit
}
</script>
In Firefox, this works perfectly. In Chrome, when I hit enter anywhere in the page, the form submit is triggered and validation doesn't work either. Is there something to avoid this ? Shouldn't the browser not submit a form when we hit an enter if there is no submit button?
use this syntax:
<form onsubmit="return validateAndSubmit()">
...
if you need to catch the return-key maybe you can handle it by binding an keydown event to the input and perform some action on keyCode #13
Try this method:
<form onsubmit="return validateAndSubmit(this);">
<input type="submit" value="Submit the Form"/>
</form>
<script language="javascript">
function validateAndSubmit(form_obj){
if(some_variable == 'correct_value') {
form_obj.submit();
return true;
} else {
alert('Wrong value');
return false;
}
//do some validation and then submit
}
</script>
I'm not sure if there's a standard regarding this or not.
Regardless, you can save yourself the trouble altogether by simply adopting a stronger strategy: implement the validation as an onsubmit action on the form, rather than an onclick action for the button. I almost never use buttons in forms; having to do so for yours would only throw me off, and that's not good for users.
So anyway. Form onsubmit is the way to go. And I'd appreciate it if you used unobtrusive Javascript instead of the HTML attributes :)