Check if checkbox is checked then send - javascript

I have this markup:
<form action="http://acumbamail.com/signup/13565/" method="POST">
<input type="checkbox" id="privacidad-btn" > Acepto polĂ­tica de privacidad<br>
<input type="button" value="Enviar" id="submit_acumba">
</form>
I want that if the user clicks on the button without checkbox checked there is an alert that he must agree to the terms (check the checkbox). Any ideas on the best approach to this?
I'm starting doing this way but don't know how which way to go:
if (jQuery("#privacidad-btn").is(":checked")) {
}

One approach that i like with html5 is the form validation
just put required on the checkbox and when the try to submit it they will be alerted with a popover dialog in there own language (its a good highlighter in the form of what is wrong with it)
<input required type="checkbox" id="privacidad-btn">
You could do it the way tymeJV suggest with button clicked event $("#submit_acumba").click(...)
That way you would support more browsers. but: It would just only validate on a click of a button
But there is the form submit event as well.
$("form").submit(function(e) {
if ( ! jQuery("#privacidad-btn").is(":checked")) {
// Not checked abort the default submit
e.preventDefault();
}
});
The difference is that it has to do all the native form validation before -> if it is invalid it won't trigger a submit or call the function
with button.onclick it would avoid the native validation since it would run before the submit event

You need a handler for the button as well:
$("#submit_acumba").click(function(e) {
e.preventDefault();
if (jQuery("#privacidad-btn").is(":checked")) {
//submit!
}
})

Using this straight and simple HTML implementation, you can do this without any special scripting (JavaScript/jQuery):
<form>
<p><input type="checkbox" required name="terms"> I accept the <u>Terms and Conditions</u></p>
<p><input type="submit"></p>
</form>
Here's a JSFiddle link where you can play with this implementation: http://jsfiddle.net/zs9b167b/

Related

Best way to form submission without using form action in JavaScript

I am building a PhoneGap application using JavaScript, HTML and jQuery Mobile.
All the HTML is in the same file, separated into <div data-role="page"> as pages.
Several pages have a form including one or more text/selection input and a submit button.
The submit is not a traditional form submit button but a button which using onClick runs a JavaScript function which can do many things.
I want the form to have this features:
When pressing the button and after running the function, clear the form.
In some cases the function should change the page.
The enter button on one of the inputs should submit the form (Activate the function).
Should I use the form HTML tag? If so what should I use for action? How to clear the form?
etc.
If you are trying to bind onClick to an input type="submit" then you're gonna have a bad time.
Unfortunately even if you return false or e.preventDefault when clicking that button, the form still sends the submit trigger so once your onClick code is finished then it will submit.
Example:
<form action="woot.php" method="POST">
<input type="submit" value="submit" onClick="alert('You clicked me! How could you?! It's cool the form will still go to woot.php. return FALSE wont help you either.'); return FALSE;">
</form>
What you probably want to do:
<form action="woot.php" method="POST">
<input type="submit" value="Submit" onSubmit="alert('You aint goin nowhere!'); return FALSE;">
</form>
What you should do:
<form action="woot.php" method="POST">
<input type="button" value="Button" onClick="alert('Away with you!'); window.location = 'http://www.google.com/';">
<input type="button" value="Button" onClick="someCoolFunction();">
</form>
I wouldn't use type="button", especially if you want to have the best chance of the form submitting when the user presses enter.
Use your regular form <input type="submit"> and then your JavaScript:
$('form').submit(function(e) {
// all your form handling here;
if (your_form_was_validated_and_handled) {
$('input[type!="submit"]').val('');
}
e.preventDefault();
});
Generic fiddle: http://jsfiddle.net/
You can still use the form tag, as it's useful for markup.
Just make sure that your buttons have attribute
type="button"
otherwise the button will submit the form by default.
To reset the form:
function resetForm() {
$('#form').each(function(){
this.reset();
});
}

browser back issue with javascript disable submit until checkbox

I've tried a few but similar ways of disabling a form submit button until a checkbox is checked.
<input type="checkbox" name="toc" value="accept" onclick="formsubmit.disabled = !this.checked" >I accept
<input class="FontSans" type="submit" name="formsubmit" id="formsubmit" value="submit" disabled="disabled" >
However if after submission you need to go back in the browser then the form shows the checkbox as checked but the submit is disabled. To enable the submit you need to uncheck
and check. Is there a way round this?
Not sure if you're using jQuery or not, but here's a jQuery-centric solution.
jQuery(function() {
if ($('.check').is(':checked')) {
$('form').removeAttr('disabled');
} else {
$('form').attr('disabled', true);
}
})
Let me know if you need vanilla JS.
This should prevent browser from restoring previous state
<input ... autocomplete="off" />

Input field with onchange fails to trigger when user click button in another form

I have a page with multiple small forms on it. Each form has one input field that has an onchange function which will submit it's form to a url that returns a no data status.
Things work fine, submitting form after form, until the user clicks on a small form that has ONLY a submit button in it. This click works, but abandons the change in the previous field resulting in its onchange not firing the click at the bottom of the changed function fails (still trying to understand the firebug trace).
What's going on? is there a fix for my structure?
UPDATE:
First I tried simply delaying the action of the submit, but no luck.
I have hidden the and added an <input button> to the chain of "events" so that the focus has a place to come to rest before the real submit tries to happen -- the code below has been updated. So the question now becomes:
Is this as simple as it can be?
Script:
$(function() {
$('input,select').change(changed);
});
function changed(){
...
$(this).parents('form').find(':submit').click();
}
function doSubmit(elt, id)
{
$(elt).focus();
setTimeout(function(){
$(id).click();
}, 400);
}
One of may small forms:
<form class="clean" method="POST" action="QuoteProApp.php">
<input type="submit" value="field" name="btn_update" style="display: none;">
<input type="hidden" value="000242" name="quote_id">
<input type="text" maxlength="15" size="3" value="" name="q[cost][4][1][unit]">
</form>
The offending click goes into this form:
<form class="clean" method="POST" action="QuoteProApp.php">
<input type="hidden" value="000242" name="quote_id">
<input type='button' name='btn_close' value='Close' onclick='doSubmit(this,"#CLOSE");'>
<input id='CLOSE' type='submit' name='btn_close' value='Close' style='display:none;'>
</form>
Might be totally irrelevant, but your selector for the change event includes your submit input too. Can you change it to:
$('input[type="text"],select').change(changed);
to see if anything changes?
The solution turned out to be to create a button tag, set the focus explicitly to a it, and then set a timeout to click the real, but hidden, submit input tag. This allows the change in focus to run the submit associated with it and then continue with the explicit submit of the page.
The question has been updated to show this solution.

Javascript login form doesn't submit when user hits Enter

I'm working on a simple javascript login for a site, and have come up with this:
<form id="loginwindow">
<strong>Login to view!</strong>
<p><strong>User ID:</strong>
<input type="text" name="text2">
</p>
<p><strong>Password:</strong>
<input type="password" name="text1"><br>
<input type="button" value="Check In" name="Submit" onclick=javascript:validate(text2.value,"username",text1.value,"password") />
</p>
</form>
<script language = "javascript">
function validate(text1,text2,text3,text4)
{
if (text1==text2 && text3==text4)
load('album.html');
else
{
load('failure.html');
}
}
function load(url)
{
location.href=url;
}
</script>
...which works except for one thing: hitting enter to submit the form doesn't do anything. I have a feeling it's cause I've used "onclick" but I'm not sure what to use instead. Thoughts?
Okay yeah so I'm well aware of how flimsy this is security-wise. It's not for anything particularly top secret, so it's not a huge issue, but if you guys could elaborate on your thoughts with code, I'd love to see your ideas. the code i listed is literally all I'm working with at this point, so I can start from scratch if need be.
There are several topics being discussed at once here. Let's try to clarify.
1. Your Immediate Concern:
(Why won't the input button work when ENTER is pressed?)
Use the submit button type.
<input type="submit".../>
..instead of
<input type="button".../>
Your problem doesn't really have anything to do with having used an onclick attribute. Instead, you're not getting the behavior you want because you've used the button input type, which simply doesn't behave the same way that submit buttons do.
In HTML and XHTML, there are default behaviors for certain elements. Input buttons on forms are often of type "submit". In most browsers, "submit" buttons fire by default when ENTER is pressed from a focused element in the same form element. The "button" input type does not. If you'd like to take advantage of that default behavior, you can change your input type to "submit".
For example:
<form action="/post.php" method="post">
<!--
...
-->
<input type="submit" value="go"/>
</form>
2. Security concerns:
#Ady mentioned a security concern. There are a whole bucket of security concerns associated with doing a login in javascript. These are probably outside of the domain of this question, especially since you've indicated that you aren't particularly worried about it, and the fact that your login method was actually just setting the location.href to a new html page (indicating that you probably don't have any real security mechanism in place).
Instead of drudging that up, here are links to related topics on SO, if anyone is interested in those questions directly.
Is there some way I can do a user validation client-side?
Encrypting Ajax calls for authentication in jQuery
3. Other Issues:
Here's a quick cleanup of your code, which just follows some best practices. It doesn't address the security concern that folks have mentioned. Instead, I'm including it simply to illustrate some healthy habits. If you have specific questions about why I've written something a certain way, feel free to ask. Also, browse the stack for related topics (as your question may have already been discussed here).
The main thing to notice is the removal of the event attributes (onclick="", onsubmit="", or onkeypress="") from the HTML. Those belong in javascript, and it's considered a best practice to keep the javascript events out of the markup.
<form action="#" method="post" id="loginwindow">
<h3>Login to view!</h3>
<label>User ID: <input type="text" id="userid"></label>
<label>Password: <input type="password" id="pass"></label>
<input type="submit" value="Check In" />
</form>
<script type="text/javascript">
window.onload = function () {
var loginForm = document.getElementById('loginwindow');
if ( loginwindow ) {
loginwindow.onsubmit = function () {
var userid = document.getElementById('userid');
var pass = document.getElementById('pass');
// Make sure javascript found the nodes:
if (!userid || !pass ) {
return false;
}
// Actually check values, however you'd like this to be done:
if (pass.value !== "secret") {
location.href = 'failure.html';
}
location.href = 'album.html';
return false;
};
}
};
</script>
Put the script directly in your html document. Change the onclick value with the function you want to use. The script in the html will tell the form to submit when the user hits enter or press the submit button.
<form id="Form-v2" action="#">
<input type="text" name="search_field" placeholder="Enter a movie" value=""
id="search_field" title="Enter a movie here" class="blink search-field" />
<input type="submit" onclick="" value="GO!" class="search-button" />
</form>
<script>
//submit the form
$( "#Form-v2" ).submit(function( event ) {
event.preventDefault();
});
</script>
Instead of <input type="button">, use <input type="submit">. You can put your validation code in your form onsubmit handler:
<form id="loginwindow" onsubmit="validate(...)">
it's because it's not a form submitting, so there's no event to be triggered when the user presses enter. An alternative to the above form submit options would be to add an event listener for the input form to detect if the user pressed enter.
<input type="password" name="text1" onkeypress="detectKey(event)">
Maybe you can try this:
<form id="loginwindow" onsubmit='validate(text2.value,"username",text1.value,"password")'>
<strong>Login to view!</strong>
<p><strong>User ID:</strong>
<input type="text" name="text2">
</p>
<p><strong>Password:</strong>
<input type="password" name="text1"><br>
<input type="submit" value="Check In"/>
</p>
</form>
As others have pointed out, there are other problems with your solution. But this should answer your question.
Surely this is too unsecure as everyone can crack it in a second ...
-- only pseudo-secure way to do js-logins are the like:
<form action="http://www.mySite.com/" method="post" onsubmit="this.action+=this.theName.value+this.thePassword.value;">
Name: <input type="text" name="theName"><br>
Password: <input type="password" name="thePassword"><br>
<input type="submit" value="Login now">
</form>
My Thought = Massive security hole. Anyone can view the username and password.
More relevant to your question: - You have two events happening.
User clicks button.
User presses enter.
The enter key submits the form, but does not click the button.
By placing your code in the onsubmit method of the form the code will run when the form is submitted. By changing the input type of the button to submit, the button will submit the form in the same way that the enter button does.
Your code will then run for both events.

How to submit a form when the return key is pressed?

Can someone please tell me how to submit an HTML form when the return key is pressed and if there are no buttons in the form?
The submit button is not there. I am using a custom div instead of that.
To submit the form when the enter key is pressed create a javascript function along these lines.
function checkSubmit(e) {
if(e && e.keyCode == 13) {
document.forms[0].submit();
}
}
Then add the event to whatever scope you need eg on the div tag:
<div onKeyPress="return checkSubmit(event)"/>
This is also the default behaviour of Internet Explorer 7 anyway though (probably earlier versions as well).
IMO, this is the cleanest answer:
<form action="" method="get">
Name: <input type="text" name="name"/><br/>
Pwd: <input type="password" name="password"/><br/>
<div class="yourCustomDiv"/>
<input type="submit" style="display:none"/>
</form>
Better yet, if you are using javascript to submit the form using the custom div, you should also use javascript to create it, and to set the display:none style on the button. This way users with javascript disabled will still see the submit button and can click on it.
It has been noted that display:none will cause IE to ignore the input. I created a new JSFiddle example that starts as a standard form, and uses progressive enhancement to hide the submit and create the new div. I did use the CSS styling from StriplingWarrior.
I tried various javascript/jQuery-based strategies, but I kept having issues. The latest issue to arise involved accidental submission when the user uses the enter key to select from the browser's built-in auto-complete list. I finally switched to this strategy, which seems to work on all the browsers my company supports:
<div class="hidden-submit"><input type="submit" tabindex="-1"/></div>
.hidden-submit {
border: 0 none;
height: 0;
width: 0;
padding: 0;
margin: 0;
overflow: hidden;
}
This is similar to the currently-accepted answer by Chris Marasti-Georg, but by avoiding display: none, it appears to work correctly on all browsers.
Update
I edited the code above to include a negative tabindex so it doesn't capture the tab key. While this technically won't validate in HTML 4, the HTML5 spec includes language to make it work the way most browsers were already implementing it anyway.
Use the <button> tag. From the W3C standard:
Buttons created with the BUTTON element function just like buttons created with the INPUT element, but they offer richer rendering possibilities: the BUTTON element may have content. For example, a BUTTON element that contains an image functions like and may resemble an INPUT element whose type is set to "image", but the BUTTON element type allows content.
Basically there is another tag, <button>, which requires no javascript, that also can submit a form. It can be styled much in the way of a <div> tag (including <img /> inside the button tag). The buttons from the <input /> tag are not nearly as flexible.
<button type="submit">
<img src="my-icon.png" />
Clicking will submit the form
</button>
There are three types to set on the <button>; they map to the <input> button types.
<button type="submit">Will submit the form</button>
<button type="reset">Will reset the form</button>
<button type="button">Will do nothing; add javascript onclick hooks</button>
Standards
W3C wiki about <button>
HTML5 <button>
HTML4 <button>
I use <button> tags with css-sprites and a bit of css styling to get colorful and functional form buttons. Note that it's possible to write css for, for example, <a class="button"> links share to styling with the <button> element.
Here is how I do it with jQuery
j(".textBoxClass").keypress(function(e)
{
// if the key pressed is the enter key
if (e.which == 13)
{
// do work
}
});
Other javascript wouldnt be too different. the catch is checking for keypress argument of "13", which is the enter key
I believe this is what you want.
//<![CDATA[
//Send form if they hit enter.
document.onkeypress = enter;
function enter(e) {
if (e.which == 13) { sendform(); }
}
//Form to send
function sendform() {
document.forms[0].submit();
}
//]]>
Every time a key is pressed, function enter() will be called. If the key pressed matches the enter key (13), then sendform() will be called and the first encountered form will be sent. This is only for Firefox and other standards compliant browsers.
If you find this code useful, please be sure to vote me up!
Use the following script.
<SCRIPT TYPE="text/javascript">
<!--
function submitenter(myfield,e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;
if (keycode == 13)
{
myfield.form.submit();
return false;
}
else
return true;
}
//-->
</SCRIPT>
For each field that should submit the form when the user hits enter, call the submitenter function as follows.
<FORM ACTION="../cgi-bin/formaction.pl">
name: <INPUT NAME=realname SIZE=15><BR>
password: <INPUT NAME=password TYPE=PASSWORD SIZE=10
onKeyPress="return submitenter(this,event)"><BR>
<INPUT TYPE=SUBMIT VALUE="Submit">
</FORM>
I use this method:
<form name='test' method=post action='sendme.php'>
<input type=text name='test1'>
<input type=button value='send' onClick='document.test.submit()'>
<input type=image src='spacer.gif'> <!-- <<<< this is the secret! -->
</form>
Basically, I just add an invisible input of type image (where "spacer.gif" is a 1x1 transparent gif).
In this way, I can submit this form either with the 'send' button or simply by pressing enter on the keyboard.
This is the trick!
Why don't you just apply the div submit styles to a submit button? I'm sure there's a javascript for this but that would be easier.
If you are using asp.net you can use the defaultButton attribute on the form.
I think you should actually have a submit button or a submit image... Do you have a specific reason for using a "submit div"? If you just want custom styles I recommend <input type="image".... http://webdesign.about.com/cs/forms/a/aaformsubmit_2.htm
Extending on the answers, this is what worked for me, maybe someone will find it useful.
Html
<form method="post" action="/url" id="editMeta">
<textarea class="form-control" onkeypress="submitOnEnter(event)"></textarea>
</form>
Js
function submitOnEnter(e) {
if (e.which == 13) {
document.getElementById("editMeta").submit()
}
}
Similar to Chris Marasti-Georg's example, instead using inline javascript.
Essentially add onkeypress to the fields you want the enter key to work with. This example acts on the password field.
<html>
<head><title>title</title></head>
<body>
<form action="" method="get">
Name: <input type="text" name="name"/><br/>
Pwd: <input type="password" name="password" onkeypress="if(event.keyCode==13) {javascript:form.submit();}" /><br/>
<input type="submit" onClick="javascript:form.submit();"/>
</form>
</body>
</html>
Since display: none buttons and inputs won't work in Safari and IE, I found that the easiest way, requiring no extra javascript hacks, is to simply add an absolutely positioned <button /> to the form and place it far off screen.
<form action="" method="get">
<input type="text" name="name" />
<input type="password" name="password" />
<div class="yourCustomDiv"/>
<button style="position:absolute;left:-10000px;right:9990px"/>
</form>
This works in the current version of all major browsers as of September 2016.
Obviously its reccomended (and more semantically correct) to just style the <button/> as desired.
Using the "autofocus" attribute works to give input focus to the button by default. In fact clicking on any control within the form also gives focus to the form, a requirement for the form to react to the RETURN. So, the "autofocus" does that for you in case the user never clicked on any other control within the form.
So, the "autofocus" makes the crucial difference if the user never clicked on any of the form controls before hitting RETURN.
But even then, there are still 2 conditions to be met for this to work without JS:
a) you have to specify a page to go to (if left empty it wont work). In my example it is hello.php
b) the control has to be visible. You could conceivably move it off the page to hide, but you cannot use display:none or visibility:hidden.
What I did, was to use inline style to just move it off the page to the left by 200px. I made the height 0px so that it does not take up space. Because otherwise it can still disrupt other controls above and below. Or you could float the element too.
<form action="hello.php" method="get">
Name: <input type="text" name="name"/><br/>
Pwd: <input type="password" name="password"/><br/>
<div class="yourCustomDiv"/>
<input autofocus type="submit" style="position:relative; left:-200px; height:0px;" />
</form>

Categories

Resources