Get HTML5 validation to work with onclick? - javascript

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).

Related

Calling JavaScript function on hitting enter key in input box

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">

Why does adding "return false;" to a submit event prevent the page from refreshing?

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&para2=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.

Yii and Javascript form submission

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.

Keeping a user from clicking 'submit', before the form is valid

I have a web form that uses a lot of JavaScript and ajax to determine if each field is valid. It gives warning messages on the fly to help the user know when there's a problem. I even use the "disable" feature on my submit button until everything is up to snuff. But here's the problem: All the event handling happens using the onblur feature. but when the last field is filled out, the validation doesn't happen till the user clicks away from that field. but why would they? there's nothing left to do on the page but click submit, which they can't do until they click somewhere else, anywhere else, first (to set off the validation event). I'm trying to find a way around this. There has to be a way where they don't have to make that extra click. it just doesn't seem professional. Is there a standard way around this? Can the validation event be triggered each time the user types an individual letter?
The form node has an onsubmit event that will fire when the user tries to submit the form. You can use this to validate all of the form fields and decide whether to let the user submit the form. The general implementation is this:
<form onsubmit="return validateForm()">
...
</form>
And in your JavaScript function, you have to return true if the user can continue submitting the form, or false to cancel the user's request before the form is submitted.
(In Psuedo-code):
function validateForm(){
if(formIsOkay){
return true;
}else{
return false;
}
}
You can validate each field using onkeyup, and withhold your user notification to the onblur method so it doesn't get annoying. If all fields are valid at the onkeyup, enable the submit button.
Given the limitations of {onChange, onKeyup, blur, etc} when it comes to handling copy/pasted or other edge cases I would probably add a timer to poll every 500ms or so and enable/disable the submit button:
window.setInterval(checkEnableSubmit, 500);
function checkEnableSubmit(){
if(validateForm()){
// enable submit button
}
}
function validateForm(){
if(formIsOkay){
return true;
}
return false;
}
I'd still call validateForm() on the button click to avoid users invalidating data and submitting before the timer is called. Server side validation is a given but I'd like to avoid the bad submit if possible.

Submit A Form Using Javascript

<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.

Categories