I have a search that operates by AJAX. It works perfectly well when the user presses the search button, the problem is... if the user presses enter... it submit the form rather than executing the AJAX javascript function. How can I make the Enter button call my AJAX function as opposed to submitting the form?
Use the form's onsubmit event to execute your ajax call and make the button into a submit button if it isn't already.
Example HTML
<form action="/search.php" onsubmit="submitAjaxQuery(event)">
<input type="text" name="keywords" />
<button type="submit">Go!</button>
</form>
Example JS
function submitAjaxQuery(event)
{
if (event.preventDefault)
event.preventDefault();
else
event.cancel = true;
// run ajax calling function here.
}
Here is a simple DOM way to handle this:
<form action="javascript:void(0)">
<input type="text" />
<input type="submit" onclick="doSomething(this.form)">
</form>
<script>
function doSomething(form){
alert('form submitted');
}
</script>
Place the cursor in the input field, and either if you click the button or type enter, the form is submitted by javascript (not the page)
Trap it in the onSubmit method of the form and return false.
With jQuery:
jQuery("#myform").submit(function() {
callAJAXFunction();
return false;
});
The correct way is to let the non-javascript users use the form submit with page refresh but a javascript call for those with javascript:
<form action="yourscript.php" method="post" onsubmit="doSomething(this.form); return false;">
<input type="text" />
<input type="submit" />
</form>
<script>
function doSomething(form){
alert('form submitted');
}
</script>
Related
I'm creating a login form and in that if any input is wrong then i want to stay on the same page and notify the client to enter the correct input
I want to stay on this page http://localhost:8080/loginpage/ but after every click i'm redirected to http://localhost:8080/loginpage/?UserName=UserName&pword=&ConfirmPassword=&Email=Email&FirstName=First+Name&LastName=Last+Name&cars=male&Signup=Signup .
I have written a code for this but it does not seem to work.
if(t!==0)
{
var er="Email-id already exists";
window.location.reload(false);
document.getElementById("nemail").value=er;
document.getElementById("username").value=username;
document.getElementById("pword").value="";
document.getElementById("confpwd").value="";
document.getElementById("fname").value=fname;
document.getElementById("lname").value=lname;
document.getElementById("gender").value=gender;
}
I have tried to use several other methods like
window.location.replace('/loginpage/');
window.location.href="/loginpage/index.html";
But none of them works.
Please help!
There are two ways to prevent a form to submit.
Set form onsubmit="return false".
Register a submit event on a from. In the callback call event.preventDefault();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>1 way to prevent form to submit via onclick attribute</h2>
<form action="#submit-from-1-way" onsubmit="return validate(this)"><!--set onsubmit="return false"-->
<input name="value"/>
<button type="submit">Submit</button>
</form>
<h2>2 way to prevent form to submit via submit event</h2>
<form id="form" action="#submit-from-2-way"><!--set onsubmit="return false"-->
<input name="value"/>
<button type="submit">Submit</button>
</form>
<script>
console.log(location.href+'#'+location.hash+'?'+location.search);
function validate(form) {
return $(form).find('input').val();
}
$('#form').submit(function (e) {
if (!validate(this)) e.preventDefault();
});
</script>
You can use preventDefault() on the click event for a given html object. This will prevent the browser from taking the default action on a specific HTML object.
For example to prevent actoin on a link:
<body>
Click Me
<script>
function dontGo(event) {
event.preventDefault();
}
document.getElementById("clickMe").addEventListener("click",dontGo);
</script>
</body>
I have to make a little form with some fields like name, age or email. For example:
<input id="name" type="text" required/>
I have a problem with the validation because i want to use the automatic validation of html to check that all fields with the required tag aren't empty and, after that, validate some fields (like the email) with javascript. I have a submit input element like this:
<input type="submit" value="Submit" onclick="form.validate()" />
The problem is that the onclick method (validate()) is always called before the auto validation, and what i want to do is call that method afther the auto validation ends (and it's everything right). The javascript i'm using to test looks like this:
"use strict";
class Form {
constructor(){}
validate(){
alert("validate");
}
}
var form = new Form();
The alert is always shown, but the auto validation it's not. If i don't put the onclick tag with its method on the submit button, the auto validation works. Any idea about my problem?
You need to use the directive ng-submit in your form:
<form ng-submit="form.validate()" ng-controller="YourController">
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" />
</form>
https://docs.angularjs.org/api/ng/directive/ngSubmit
https://docs.angularjs.org/api/ng/directive/form#submitting-a-form-and-preventing-the-default-action
Keep Rocking!
This method uses jQuery. First you need to prevent the default action on form submit, then you can do your validation, then finally submit the form. Example below.
Your form:
<form id="form">
<input type="text" required>
<input type="submit" value="Submit!">
</form>
Javascript(with jQuery):
$('#form').submit(function(ev) {
ev.preventDefault(); // to stop the form from submitting
/* Validations go here */
form.validate();
alert('here');
this.submit(); // If all the validations succeeded
});
JavaScript(vanilla):
document.getElementById('form').addEventListener('submit', function(ev) {
ev.preventDefault(); // to stop the form from submitting
/* Validations go here */
alert('here');
this.submit(); // If all the validations succeeded
});
In PHP program, I have JS function which validates submit <form ...onsubmit='return isOK();'>. It works OK. The problem is I want it to work only for particular submits, not for all. Is there any way inside the JS function to find out which submit was pressed, or some PHP trick
instead of onsubmit u can use onClick.
<input type="submit" onclick="return pressSubmit1()" value="submit1" />
<input type="submit" onclick="return pressSubmit2()" value="submit2" />
<form action="action.php" method="post">
...
<input name="submit" type="button" value="check me" onclick="submitform('check')" />
<input name="submit" type="button" value="do not check me" onclick="submitform('not check')"/>
</form>
in javascript:
function submitform(check)
{
if(check=='check') checkfrom();
}
in PHP
if($_POST['submit']=="check me")
checkform();
<form class="allowed" onsubmit='return isOK();'>
----
function isOK() {
if($(this).hasClass('allowed')) {
// Do stuff
}
}
your question is not clear, are you using a single submit button or different ones. If you're using different submit buttons then ofcourse you can make checks based on the id of the submit button. On the other hand if is a single submit button then it depends on what the conditions are for submitting or not submitting
It's better you write some HTML and Java Script code which you are using. So, it's easy to correct mistake is you have made somewhere in code snippet.
We can check which submit button is clicked, using PHP.
In the PHP page corresponding to the form submit, write
if(extract($_POST) && isset($submitbtn1)) {
// some validation for first submit button
}
elseif(extract($_POST) && isset($submitbtn2)) {
// some validation for second submit button
}
Note: we can use $ followed by submit button name inside the extract function. ie. $submitbtn1 is same as $_POST['submitbtn1']
Yes different onclick looks fine as mentioned in the accepted answer. But in the event handler you should have the
code as below. Note the preventDefault.
Also since submit is A button that submits the form. You can use button type instead of submit type and then there is no need for preventDefault. Here is the link of the code http://jsbin.com/wikose/4/
function testlogin(){
event.preventDefault();
var test = 'not validated';
if(test === "validated")
alert("not valid login");
else
$('form').submit();
return false;
}
I have a form, which has a jquery form validation.. what i need is the submit button should get disabled when i submit the form once the validation is done..
<form action="#" method="post" id="myform" name="myform">
Location: <input name="location" type="text" />
Site: <input name="site" type="text" />
Age: <input name="age" type="text" />
Gender <input name="gender" type="text" />
<input name="button" type="submit" class="myButton" id="button" value="Submit" />
</form>
here is my form JsFiddle
Not sure why you want to disable the submit button but using jQuery you could do
$('input[type="submit"]').prop('disabled',true);
Typically you either wouldnt have a submit button, or else submit the form and the page will reload!
UPDATE
To stop people from reposting the values by refreshing the page as you wrote in comments, redirect the user to the page without the values posted!
header('/same_page.php');
you want to do the action on form.submit. Not sure if you need to add form.valid() there as a check, but I always do it like that. Afterwards you can return true or false.
True: The browser proceeds with the link and action specified in the form
False: The browser stops (when you have validation errors)
Here the code:
$('#myform').submit(function() {
if (!$('#myform').valid()) return false;
$('#myform input[type=submit]').attr("disabled", "disabled");
return true;
});
I've also updated your fiddle with that code, so you can try it out
after you validate the form, use:
$( "#button" ).click(function(event) {
if($('#myform').valid()) {
$(event.target).attr("disabled", "disabled");
}
});
If you want to disable once the form which you want to validate is valid, then you can disable the submit button like this
$("#myForm").validate({
submitHandler: function(form) {
// do other stuff for a valid form
$('#myform input[type=submit]').attr("disabled", "disabled");
form.submit();
}
});
I want an HTML form to do nothing after it has been submitted.
action=""
is no good because it causes the page to reload.
Basically, I want an Ajax function to be called whenever a button is pressed or someone hits Enter after typing the data. Yes, I could drop the form tag and add just call the function from the button's onclick event, but I also want the "hitting enter" functionality without getting all hackish.
By using return false; in the JavaScript code that you call from the submit button, you can stop the form from submitting.
Basically, you need the following HTML:
<form onsubmit="myFunction(); return false;">
<input type="submit" value="Submit">
</form>
Then the supporting JavaScript code:
<script language="javascript"><!--
function myFunction() {
// Do stuff
}
//--></script>
If you desire, you can also have certain conditions allow the script to submit the form:
<form onSubmit="return myFunction();">
<input type="submit" value="Submit">
</form>
Paired with:
<script language="JavaScript"><!--
function myFunction() {
// Do stuff
if (condition)
return true;
return false;
}
//--></script>
<form id="my_form" onsubmit="return false;">
is enough ...
It also works:
<form id='my_form' action="javascript:myFunction(); return false;">
<form onsubmit="return false;">
How about
<form id="my_form" onsubmit="the_ajax_call_function(); return false;">
......
</form>
You can use the following HTML
<form onSubmit="myFunction(); return false;">
<input type="submit" value="Submit">
</form>
Use jQuery. Maybe put a div around your elements from the form. Then use preventDefault() and then make your Ajax calls.
Use:
<form action='javascript:functionWithAjax("search");'>
<input class="keyword" id="keyword" name="keyword" placeholder="input your keywords" type="search">
<i class="iconfont icon-icon" onclick="functionWithAjax("search");"></i>
</form>
<script type="text/javascript">
function functionWithAjax(type) {
// Ajax action
return false;
}
</script>
In cases where 'return false' doesn't do a thing,
try just passing the event to the form's onsubmit (not action!)
and simply add event.preventDefault() in that function.
Leave the 'action' from the html. Additional info: action="javascript:etc(event)" didn't work in my tests.
As part of the button's onclick event, return false, which will stop the form from submitting.
I.e.:
function doFormStuff() {
// Ajax function body here
return false;
}
And just call that function on submit button click. There are many different ways.
You can use preventDefault to prevent the form's default submit behaviour from firing
form.addEventListener('submit', myHandler);
function myHandler(event) {
event.preventDefault();
}
Just replace 'action=""' withonsubmit='return false'. That's it.