Although I am able to call Javascript function on hitting the enter key. I am calling a function shortIt() when user hits the enter key, shortIt() takes the text from input box and makes a request to Google URL Shortener API which returns a short URL, but the generated response is visible for only some seconds.
I am showing the response in a div.
Seems to be very weird problem, code is here https://s3-ap-southeast-1.amazonaws.com/s3freebucket/URLShortner/url-shortner.html
But when I click on shortIt button to short the url. It works fine and the response text stays in the div.
This is because on pressing the enter key, the form gets submitted. When this happens you will notice the page reloading. This is a default behaviour and is the consequence of using <form>. On form submission, the page in the forms action attribute is loaded. In this case the action attribute of the <form> is not set and so the page you are on is just reloaded, thus the script stops running and the page reloads.
Two straight forward options for fixing this:
(Simplest) Remove the form tag - it is not used to submit anything so removing it should leave things still working
Prevent the default action when the form submit event is fired.
With JQuery:
$('#myForm').on('submit', function (evt) {
evt.preventDefault(); // prevents form submission
});
Where myForm is the ID of your form tag. You will need add an id attribute to your existing html form tag: <form id="myForm" class="form-horizontal">
Related
I'm doing a tutorial on making a chat server with Node.js and socket.io. Here's what I had in the html:
<form id='chat_form'>
<input id='chat_input' />
<button>Send</button>
</form>
<script type='text/javascript'>
var socket = io();
$('#chat_form').submit(function(){
var message = $('#chat_input').val();
socket.emit('messages', message);
$('#chat_input').val('');
});
</script>
I won't bother putting what I had on the back-end, because that part all worked fine. But in the browser, every time I submitted, the page refreshed, and a /? was added to the end of the URL bar.
Looked around for a bit, and found another tutorial (the one on the socket.io website), that had basically the same code, but they had added return false; to the end of their submit event. Tried that out and it worked fine. I'd like to understand why that worked though. Can anyone explain? Also, can you explain why the /? was added to the URL?
first about /?:
default method of form submit is GET, but you can change it with <form method="POST"> (while default is <form method="GET"> if method is not provided).
With POST form data is passed in request body, with GET - in request url params.
If you have
<form action="/submit.php" method="GET">
<input name="foo" value="1" />
<input name="bar" value="2" />
</form>
And you submit that form, you'll get URL something like /submit.php?foo=1&bar=2.
In your case you have no inputs with name attribute, so your GET params are "empty" (/?<params should go there>).
You can read more in:
http://www.w3schools.com/tags/att_form_method.asp
About return false;
Submitting form forces page reload (with either POST or GET request). If you submit form with javascript you need to prevent this default action. You can do this by
$('#chat_form').submit(function(event){
//....
event.preventDefault();
});
Or with return false;.
A simple and easy answer to this is
"Return false prevents navigation"
Return false is always used in those case where user or browser action needs to be stooped.
In every programming language, the code after return is not executed, which means further action wont take place, which can be
stopping form submit
stopping navigation and hyperlink jumps
other than return false you can also use
event.preventDefault();
event.stopPropagation();
Now about form submit
A form is submitted using GET and POST which can be decided by the author using method="POST" attribute in form tag,
when nothing given by default form submits using GET
which passes values in url - ex - something.html?para1=value1¶2=value2
which is fast and less secure, every time you submit a form with get all the form elements will be passed in the url
From the jQuery submit() docs:
Now when the form is submitted, the message is alerted. This happens prior to the actual submission, so we can cancel the submit action by calling .preventDefault() on the event object or by returning false from our handler.
So what's happening is, the default event behavior triggered when the submit event occurs is being prevented.
The default method of submission for the jQuery submit function is an HTML GET, which supplies the form paramaters as a URL query, in the form of /?queryParam=value. Hence, the /? appears in the URL, with no query parameters after the /? (as none are being supplied in the form).
Hope this helps!
Return false prevents all of the default functions of html element events from firing.
An example is an html form, once you hit the submit button it's default is to navigate to another page. You don't want that to happen if you are using Ajax functions to send data to a server without leaving the page.
Another way to do it is pass an event object parameter to the event function.
Then at the beginning of the function type event.preventDefault ();.
The following link offers a good explanation of why the trailing slash is present. https://webmasters.stackexchange.com/questions/35643/is-trailing-slash-automagically-added-on-click-of-home-page-url-in-browser
your form element has no method, so default method get is set. If you click send all the input elements are added after current page+?
return false prevents the submit action to perform.
I have a form for name, company, email, and phone number, and using required it makes sure that the form has something filled in for each input. What I am trying to do is have it download a file to the computer of the visitors who fill out the form, and have this code handling the download:
HTML:
<input type="submit" id="submitbutton" onclick="download()">
JS:
function download(){
window.open('the_file.zip');
}
However, adding the onclick is causing the form to bypass validation and it will submit and download with nothing needing to be filled out. What can I do here to make sure the HTML5 validation works?
I would listen for the submit rather than the click event.
Using jQuery:
$('form').submit(function(event){
alert('form was submitted!');
// window.open('the_file.zip');
// event.preventDefault();
// ... do something else ...
// $(this).submit();
});
Then you could also prevent the default action of submit event.preventDefault(); before if you wanted to do something before you actually submitted the form.
What you should really do is, instead of an onclick event, set the form action attribute to a server page that validates the form, then, if the form is valid, redirects the user to the_file.zip.
Even by doing something like event.preventDefault(), I'm pretty sure you're also going to prevent the form values from being processed by anything (they'll just sit their in their respective input fields and a new window will open with the file to download).
I'm using Yii as a PHP framework for my site. Additionally, my site uses some js/jquery like, say, a jQuery UI Dialog widget (except for those dialogs, the rest of the code is pure normal html form components and jQuery code for the event handlers).
In the Yii side, I use CForms to build my forms from specifications file.
When I test if the form was submitted, I must do it for a certain button. This is not only forced, but I also take advantage of it.
if ($myCFormInstance->submitted('approve')) {
//process approval code
} else if ($myCFormInstance->submitted('reject')) {
//process rejection code
}
The actual problem I have is a bit conceptual one, since -fortunately- I know what's going on with my code and -again, fortunately- know the problem root:
Somewhere in My code I intercept the submit button's click event:
$(function(){
$(".critical-action").click(function(e){
var form = $(this).closest("form");
e.preventDefault();
e.stopImmediatePropagation();
confirmDialog("¿Continuar?", "#critical-action-dialog", function(){
form.submit();
});
});
});
Say the .critical-action classed elements are always a submit button in a form.
The intention of the code: cancel the form submission, and perform it only if the user -in the dialog- clicks the "Yes, Continue" (i.e. confirming the action) button.
This code works as expected, and have no problems at a javascript level BUT -and here goes my issue- when doing form.submit(), the button is not sent as part of the form. This is obvious: I'm sending the form without specifying any button. In the case of Approve and Reject, which have two buttons, the example explains itself: if the form.submit() call could send their buttons ¿which of them should send?.
Question: So, since form.submit() doesn't send any button, but I actually need buttons ¿how can I send the form "with the corresponding button" -i.e. a button I choose to specify, which should correspond to this in the click handler function context- automatically via javascript? The button NEEDS to be identified by Yii in order to process the form (specially with the Approve and Reject case).
If you added a hidden input to the form, you can modify the input value with jQuery before you submit the form, like this:
$("#inputID").val('approve');
If you want to set the value to the value of the clicked button via $(this).val(), be aware of the issue that could result in an IE browser, explain here. The second answer (by postpostmodern) has a solution to this issue.
about click and submit
example below:
<form action="url" method="post">
<input type="text" id="input1"/>
<input type="submit" value="submit" onclick="testFun()"/>
</form>
if it is possible that function testFun run after the form's submit when we click the button to submit
if the answser is no.
why? how does the browser work when click the submit button?? the order is click function-> submit ? is right??
No you cannot execute a function after the form has been submitted - the order of which things are executed is as follows :
User clicks the submit button
The onclick function is executed
The browser submits the page to the url specified in the action of the form
You can prevent the browser submitting the page by returning false from the onclick handler :
function myfunc() {
// do some stuff
return false;
}
the submit button should then be modified like this :
<input type="submit" onclick="return myfunc()"/>
If you do wish to execute a function after the form has been submitted you need to submit the form using AJAX - this doesnt cause the browser to navigate away from the page and a JavaScript function can be executed after the form has been submitted
This is not possible because the form's action would redirect the browser to that URL.
1 option would be to run testFun() on your action url page, but this might not be possible depending on what the function does.
If you are to post more information about what you are actually trying to do here, then it might help.
No, but testFun might (in turn) call another, asynchronous, function that wouldn't run until the form had submitted (at which point it wouldn't run at all since the browser would have left the page).
No it is not possible, after submit you are out of the scope from the current page. But if you are using an iframe for your form submit and call the function on the parent page, then I thought it will work.
The anwswer is "It is not possible"
Why
Because once the browser triggers the submit event all user interaction with page is stopped. After the submit event is triggered the communication is between your browser and the webserver. This is how broswers are designed.
In your case Form submission happens because you have a form in your page and in that form you have an input of type=button. If you dont want to submit the page you can change the type of the input to button.
Check this fiddle http://jsfiddle.net/kiranvj/MBxNs/1/
<form action="/?wpmlmethod=offsite&list=2&wpmlformid=" method="post">
...
</form>
I tried:
<script type="text/javascript">document.forms[0].submit();</script>
But it didn't work.
You should submit it on some click event, etc, for example:
elem = document.getElementById('button_id');
elem.onclick = function(){
document.forms[0].submit();
};
Update:
As you said form is already filled, you want to submit it straight away, you can try this instead:
window.onload = function(){
document.forms[0].submit();
};
Note that forms[0] represents the first form on your page, if there are more than one forms on your page, you will need to specify the correct index for it eg forms[1], forms[2], etc
Make sure you call the submit method after the form exists (either by placing the script after the form or using an onload or onready event)
Make sure you do not have a form control (e.g. an input) with the name or id of submit as this will clobber the submit method with a reference to that HTMLElementNode.
That said, you probably shouldn't be loading a page just to instantly submit a form with JS in the first place. You should have already had all the information needed on the server when you built the form. It smells of bad design and can break the back button.