Make a checkbox and check if checked - javascript

I have a "terms of use" page, then I have the page where I have payment and such. On this page I would like the user to have to check a checkbox where it will say "if he accepts the terms of use", but I would also like a javascript, for the payment service Stripe, to check if the checkbox is checked and if not it will alert the user to check it and if it is just proceed like always.
I have commented in the script the different functions. I want it to function so if I were to click the checkbox and then click the submit button, it will then work as usual but if I don't check the checkbox, it will then make an alert box. I would like to do this using an "if" function.
The checkbox has to be in the form with the id "payment-form", where the rest of the inputs are.
The javascript is the whole function in the tags. It is the whole function that has to be disabled if the checkbox isn't checked.
My code so far:
<!DOCTYPE html>
<html>
<head>
<script src="https://checkout.stripe.com/checkout.js"></script>
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script type="text/javascript"> /* this is the javascript function that only has to "launch" if the checkbox is checked and if not it has to make an alert box to the user and not do any of the other functin in the javascript. */
$(document).ready(function() {
var handler = StripeCheckout.configure({
key: 'Removed for safety',
image: 'image2.png',
token: function(token) {
var $form = $('#payment-form');
$form.append($('<input type="hidden" name="stripeToken" />').val(token.id));
$form.get(0).submit();
}
});
$('#customButton').on('click', function(e) {
var amount = Math.round($("#amount").val()*100);
handler.open({
name: 'Payment',
description: 'describtion',
amount: amount
});
e.preventDefault();
});
$(window).on('popstate', function() {
handler.close();
});
});
</script>
</head>
<body>
<div id="header">
</div>
<div id="container">
<div id="content">
<div class="firstproductbidwrap" style="height:500px width:800px">
<form id="payment-form" action="chargeCard.php" method="POST" name="payment-form"> <!-- this is the form I would like to add the checkbox to -->
<input onkeypress="return isNumberKey(event)" type="text" name="amount" id="amount" value="" readonly/>
<input type="text" name="emailForPayment" id="emailForPayment" placeholder="Enter Email"/>
<input type="text" name="displayNameForPayment" id="displayNameForPayment" placeholder="Enter Display Name" maxlength="12"/>
<input type="image" src="button3.png" id="customButton" value="submit" alt="button"/>
</form>
<script type="text/javascript">
function toDec(code) {
return code - 48;
}
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57 || toDec(charCode) != currentVar + 1))
return false;
return true;
}
</script>
<script type="text/javascript">
var request = new XMLHttpRequest();
request.open('GET', 'textFileVariables.txt', false);
request.send();
var currentVar= parseInt(request.responseText)
var nextVar = currentVar + 1;
document.getElementById("currentVar").innerHTML = currentVar;
document.getElementById("nextVarDisplay").innerHTML = nextVar ;
document.getElementById("amount").value = nextVar ;
</script>
<div class="acceptrules">
When participating <!-- this is the text for accept terms with the link -->
<br>
you agree to the rules Terms of Use
</div>
</div>
</div>
</div>
</body>
</html>

What you could is this:
<!--Replace this thing -->
<input type="image" src="button3.png" id="customButton" value="submit" alt="button"/>
<!-- By This -->
<input id="myButton" type="submit" disabled="disabled" />
Then in CSS
<style>
#myButton{
background: url(path/to/your/image.png);
width: 100px; /*Your image size*/
height: 50px; /*Your image height*/
}
</style>
Then, you add this input before your submit
<label><input type="checkbox" id="terms" /> I accept terms and condition</label>
Then in your JS
$('#terms').on('change', function(){
if ($(this).is(':checked')){
$('#myButton').removeProp('disabled');
}
else{
$('#myButton').attr('disabled', 'disabled');
}
});

Put <input type="checkbox" id="agree" /> somewhere in your form and try this:
$('#customButton').on('click', function(e) {
if (!document.getElementById("agree").checked)
alert("You must agree to the TOS.");
else {
var amount = Math.round($("#amount").val()*100);
handler.open({
name: 'Payment',
description: 'describtion',
amount: amount
});
}
e.preventDefault();
});
https://jsfiddle.net/cj6f41aL/

Related

Inline error message still displayed after the user adds text to input fields

When users click submit, I've coded an error message to appear under each input field that is missing a value using DOM selectors. I also disabled the email file that opens when submit is clicked, using preventDefault().
However, when the user types into the text area, the messages don't disappear. I tried using a 'keydown' event, but I couldn't get it to work.
HTML code:
<body>
<header class="header">
<form action="mailto:me#fakeemail.com">
<fieldset>
<legend>Personal details</legend>
<p>
<label>
Full name:
<input type="text" name="fullname" id="fullname">
</label>
</p>
<p class="errormsg" id="nameerrormsg">Please enter your name above</p>
<p>
<label>
Street Address:
<input type="text" name="streetaddr" id="streetaddr">
</label>
</p>
<p class="errormsg" id="addrerrormsg">Please enter your street address</p>
</fieldset>
<input type="submit" value="Submit it!" class="submitIt" onsubmit="return checkForm();">
</form>
<br>
<script src="inline-error.js" charset="utf-8"></script>
<div class="returnHome">
Return Home
</div>
</header>
</body>
Javascript code:
var submitIt = document.querySelector(".submitIt");
submitIt.addEventListener("click", function checkForm(event) {
var fNameInput = document.querySelector("#fullname")
var streetAddInput = document.querySelector("#streetaddr")
if (fNameInput.value == "") {
var nameErrorMsg = document.querySelector("#nameerrormsg").style.display = "block";
event.preventDefault();
}
if (streetAddInput.value == "") {
var addrErrorMsg = document.querySelector("#addrerrormsg").style.display = "block";
event.preventDefault();
}
})
To see an immediate result in the code in its current state, hide the error messages before checking the input values.
var submitIt = document.querySelector('.submitIt');
submitIt.addEventListener('click', function checkForm(event) {
var nameErrorMsg = document.querySelector('#nameerrormsg');
var addrErrorMsg = document.querySelector('#addrerrormsg');
nameErrorMsg.style.display = 'none';
addrErrorMsg.style.display = 'none';
var fNameInput = document.querySelector('#fullname');
var streetAddrInput = document.querySelector('#streetaddr');
if (fNameInput.value == '') {
nameErrorMsg.style.display = 'block';
event.preventDefault();
}
if (streetAddrInput.value == '') {
addrErrorMsg.style.display = 'block';
event.preventDefault();
}
});
Having said that, here are some additional suggestions:
Use CSS for styling elements (not JavaScript)
Discourage inline JavaScript
Store DOM elements outside the scope of the event listener so you don't have to query the DOM every time you click
Consider utilizing the required attribute on the inputs for a quick win on styling
So...
<!-- form.html -->
<head>
<link rel="stylesheet" href="form.css">
</head>
<body>
<header class="header">
<form>
<fieldset>
<legend>Personal details</legend>
<p>
<label for="fullname">Full name:
<input type="text" name="fullname" id="fullname" required>
</label>
</p>
<p class="errormsg" id="nameerrormsg">Please enter your name above</p>
<p>
<label for="streetaddr">Street Address:
<input type="text" name="streetaddr" id="streetaddr" required>
</label>
</p>
<p class="errormsg" id="addrerrormsg">Please enter your street address</p>
</fieldset>
<input type="submit" value="Submit it!" class="submitIt">
</form>
</header>
<button id="returnhome">Return Home</button>
<script src="inline-error.js"></script>
</body>
/* form.css */
input:valid {
border: none;
}
input:invalid:required {
border: 1px solid red;
}
.errormsg {
display: none;
}
.show {
display: block;
}
// inline-error.js
var submitIt = document.querySelector('.submitIt');
var nameInput = document.querySelector('#fullname');
var nameError = document.querySelector('#nameerrormsg');
var addrInput = document.querySelector('#streetaddr');
var addrError = document.querySelector('#addrerrormsg');
var returnHome = document.querySelector('#returnhome');
returnHome.addEventListener('click', e => {
e.preventDefault();
history.back();
});
submitIt.addEventListener('click', event => {
const nameValue = nameInput.value;
const addrValue = addrInput.value;
if (!nameValue || !addrValue) {
event.preventDefault();
}
if (!nameValue) {
nameError.classList.add('show');
} else {
nameError.classList.remove('show');
}
if (!addrValue) {
addrError.classList.add('show');
} else {
addrError.classList.remove('show');
}
});

Disabling jquery submit button until all the form inputs is filled

Disabling jquery submit button until all the form inputs is filled.
Am working with Jquery and I have been trying to implement disabling form submission button until the whole form inputs are filled. i have tried most solution found here but it does not solve the issue. Thanks
$('.postbtn_video').click(function() {
var element = $(this);
var ID = element.attr('id');
var msg = $('#status').val();
var title = $('#title').val();
var video = $('#video').val();
var stat = $('#stat').val();
if (title == "") {
alert('Please Enter video Post Title?');
} else if (msg == "") {
alert('Please Enter Video Post Description');
} else if (video == "") {
alert('Enter Youtube Video Link');
} else if (stat == "") {
alert('Select Status');
} else {
var postData = "post=" + msg + "&title=" + title + "&video=" + video + "&stat=" + stat;
$("#loader").show();
$("#loader").fadeIn(400).html('<img src="loader.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
$.ajax({
type: "POST",
url: "posts.php",
data: postData,
cache: false,
success: function(html) {
$("ul#updatepost").prepend(html);
$("ul#updatepost li:first").slideDown("slow");
$('#status').val('');
$('#loader').hide();
}
});
}
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" name="statusform">
<label>Video Post Title </label>
<input type="text" name="title" id="title" class="form-control" placeholder="Enter Post Title">
<p></p>
<label>Video Post Description</label>
<textarea style="width:100%" name="status" class="status form-control" id="status" placeholder="Share what you like " title="What's on your mind?">
</textarea>
<label>Youtube Video Link</label>
<input style="width:100%" name="video" class="form-control" id="video" placeholder="Youtube Video Link">
<label>status</label>
<select style="width:100%" name="stat" class="form-control" id="stat">
<option value="ok">ok</option>
</select>
<p></p>
<input name="post" type="submit" value="Share Video Updates" class="postbtn_video" style="background:black;color:white; height:30px;float:left" />
</form>
Firstly apply disabled="disabled" to the button:
<input name="post" type="submit" value="Share Video Updates" class="postbtn_video" disabled="disabled" />
Secondly, you need a function which will check each field is empty or not!
Check below code:
$(document).ready(function(){
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if(!empty){ // this will only check next inputs if empty is false, but once its set to true no further check will be made
if ($(this).val() == '') {
empty = true;
}
}
});
if (empty) {
$('.postbtn_video').attr('disabled', 'disabled');
} else {
$('.postbtn_video').removeAttr('disabled');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" name="statusform">
<label>Video Post Title </label>
<input type="text" name="title" id="title" class="form-control" placeholder="Enter Post Title">
<p></p>
<label>Video Post Description</label>
<textarea style="width:100%" name="status" class="status form-control" id="status" placeholder="Share what you like " title="What's on your mind?"></textarea>
<label>Youtube Video Link</label>
<input style="width:100%" name="video" class="form-control" id="video" placeholder="Youtube Video Link">
<label>status</label>
<select style="width:100%" name="stat" class="form-control" id="stat">
<option value="ok">ok</option>
</select>
<p></p>
<input name="post" type="submit" value="Share Video Updates" class="postbtn_video" disabled="disabled" />
</form>
Maybe this will help. you can manipulated the Form Disabled attribute:
var checkboxes = document.getElementsByTagName('input');
//check all check all input elements to see if they are check-boxes
for (var i = 0; i < checkboxes.length; i++) {
//If the input is a check-box run script else skip over
if (checkboxes[i].type == 'checkbox') {
//If it is a check-box ensure the box is unchecked
checkboxes[i].checked = false;
}
}
$(document).ready(function()
{
//define Element by ID and create variable
var $checked = $('#field_human');
//define default state for attribute before handler function trigger
$("#submit").attr("disabled", !$checked.checked)
//On element handler trigger define function to execute each time handler is triggered
$checked.click(function()
{
//State to define instance on method
if ($checked.prop('checked'))
{
//return true
//remove element attribute state 'disabled'
$('#submit').removeAttr('disabled');
}
if($('#contactForm input').val() != '')
{
$('#submit').removeAttr('disabled');
}
else {
//return false
//set element attribute state 'disabled'
$("#submit").attr("disabled", !$checked.checked);
}
//return to ready-state to wait for handler to trigger again
return;
});
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<form class="form-horizontal" role="form" method="post" action="" id="contactForm" name="contactForm">
<div class="form-group">
<label for="inputblk" class="col-sm-3 control-label">Input Block</label>
<div class="col-sm-9">
<input name="inputblk" class="form-control" />
</div>
</div>
<div class="form-group">
<label for="human" class="col-sm-3 control-label">Are You <strong><u>Human</u>?</strong></label>
<div class="col-sm-9">
<input id="field_human" class="field_human" type="checkbox" name="human" />
</div>
</div>
<div class="form-group">
<div class="col-sm-9 col-sm-offset-3">
<button id="submit" name="submit" type="submit" class="btn btn-dark btn-block btn-lg">Send</button>
</div>
</div>
</form>
1st:
inputs that you think are required, make it required! like below:
<input style="width:100%" name="video" class="form-control" id="video" placeholder="Youtube Video Link" required >
2nd:
Make your selection based on this attribute and check if values of these inputs are not empty. Disable the submit button if so.
3rd:
Make event listener to all inputs that have required attribute to listen user inputs.
something like this:
var l = $("[required='']");
function enableSubmit(l) {
if (l.length == 0) {
$("[name=post]").removeAttr('disabled');
} else {
for (var m = 0; m < l.length; m++) {
if (l[m].value.length == 0) {
$("[name=post]").attr("disabled", "disabled");
return;
}
}
$("[name=post]").removeAttr('disabled');
}
}
for (var m = 0; m < l.length; m++) {
l[m].addEventListener('input', function () {
enableSubmit(l);
});
}
First of all you need to add a disabled property to you input button by default like:
<input disabled name="post" type="submit" value="Share Video Updates" class="postbtn_video" style="background:black;color:white; height:30px;float:left" />
then in your jquery you need fire up a validate function that will check for all the inputs and if they are not empty you can simply remove the disabled property from your input button like:
$(document).on('keyup', "input:not([type='submit']", function () {
//set it to true by default
var valid = true;
//getting all the inputs except input submit
var inputTextboxes = $("input:not([type='submit'])");
inputTextboxes.each(function(e) {
//it enters this only if the valid is true for any one value, if valid is set to false at any point it won't check it for next inputs - works for first time
if (valid != false){
if ($(this).val()) {
valid = true;
}else{
valid = false;
}
}
else{
break; //breaks the loop
}
});
if (valid) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
Hope this helps

Show alert (Text Field is empty) on submit Html/JavaScript

How to get an Alert on Submit when I left a TextBox empty And It Should Turn To the Next page on submit.
Must Reply,
Thank You.
You can try this :
HTML :
<form action="" method="POST" id="myForm">
<input id="myInput" type="text" />
<input type="submit" />
</form>
(Replace the action attribute by the url of your destination page, the one you call the "next page").
JS (without jQuery):
var myForm = document.querySelector('#myForm');
var myInput = document.querySelector('#myInput');
myForm.addEventListener('submit', function(pEvent) {
if(myInput.value === '') {
pEvent.preventDefault(); //Prevents the form to be sent
alert('Ho! Stop!');
//Do whatever you want
}
});
JS (with jQuery) :
var myForm = $('#myForm');
var myInput = $('#myInput');
myForm.on('submit', function(pEvent) {
if(myInput.val() === '') {
pEvent.preventDefault(); //Prevents the form to be sent
alert('Ho! Stop!');
}
});
Demo : http://jsfiddle.net/af9qvkmp/9/
Here is the demo, based on jQuery!
HTML
<form action="" method="POST" id="form">
<input id="input1" type="text" />
<input id="input2" type="text" />
<input id="input3" type="text" />
<input id="input4" type="text" />
<input id="input5" type="text" />
<input type="submit" />
</form>
JS
$(function() {
$('#form').on('submit', function(event) {
var isError = false;
$(this).find('input[type="text"]').each(function() {
if($(this).val() == '') {
console.log($(this));
isError = true;
return false;
}
});
if(isError) {
event.preventDefault();
alert("Got Error");
} else {
// Submit the form
}
});
});
In form tag write
<form action="" method="post" enctype="multipart/form-data" onsubmit="return checkform(this);">
This is your input field
<input type="text" name="reviewValue" value="" id='starRate2' required>
Javascript Code:
<script language="JavaScript" type="text/javascript">
function checkform ( form ){
if (form.reviewValue.value == "") {
alert( "Please choice your Rating." );
form.reviewValue.focus();
return false ;
}
return true ;
}
</script>

how to not submit a form in js

I want to not submit the form if the inputs are empty, here is my code:
<html>
<head>
<title>
The X/O Game
</title>
<script type="text/javascript">
var check = function () {
var x = document.getElementById("x").value;
var o = document.getElementById("o").value;
var p = document.getElementById("p").value;
if(p==""||(x==""&&o=="")){
alert("fill the form!");
return false;
}
return true;
};
$('#formm').submit(function(e){
var shouldSubmit = check();
if (!shouldSubmit) {
e.preventDefault();
}
});
$('#emotion input:radio').addClass('input_hidden');
$('#emotion label').click(function(){
$(this).addClass('selected').siblings().removeClass('selected');
});
</script>
<link rel="stylesheet" type="text/css" href="style/style.css" />
<body>
<div>
Please enter your name & choose your character before start playing:
</div>
<div>
<form method=post action=game.php name="formm">
Name:<br>
<input type=text name=player id=p>
</div>
<div>
Character:<br>
<input
type="radio" name="emotion" value="xChar"
id="x" class="input-hidden" />
<label for="x">
<img src="images/x.png " />
</label>
<input
type="radio" name="emotion" value="oChar"
id="o" class="input-hidden" />
<label for="o">
<img src="images/o.png" />
</label>
</div>
<div>
<input type=submit value=Play>
</form>
</div>
</body>
</html>
$('#formm').submit(function(){
return f;
});
this function is called when the user clicks on the submit button.
the form is subbmited even though the inputs are empty, where is the wrong?
f is defined when you call check(), they will not magically update. Do the checks inside the submit function.
You'd better use HTML5 required attribute here:
<form>
<input type="text" name="x" required>
<input type="submit">
</form>
If you want more complex validation, you should have a look at html5rocks.com. The form validation should move from Javascript to HTML now (or in the near future).
But if you want to do it your way, do as epascarello suggests here:
$('#formm').submit(function(){
check();
return f;
});
Try this:
$('#yoursubmitbtnid').click(function(){
var x = document.getElementById("x").value;
var o = document.getElementById("o").value;
var p = document.getElementById("p").value;
if(p==""||(x=="" && o=="")){
alert("fill the form!");
return false;
}
});
You need to run the check function in the submit handler to determine whether or not the submit should be allowed.
var check = function () {
var x = document.getElementById("x").value;
var o = document.getElementById("o").value;
var p = document.getElementById("p").value;
if(p==""||(x==""&&o=="")){
alert("fill the form!");
return false;
}
return true;
};
$('#formm').submit(function(e){
var shouldSubmit = check();
if (!shouldSubmit) {
e.preventDefault();
}
});
You may want to look into using a validation plugin (such as this) if you plan on doing any extensive client side validation.
You need to call the check function when the form is being submitted
$('#formm').submit(function(){
return check();
});
If the check function returns false then the form should not submit.

Stopping action if requirements are not met

I want to check the validation of two text boxs if either one is empty. It showed show an error as an innerHTML and if they are both filled in. It will then continue to action. Here is my code:
function go()
{
var toCheck = document.getElementById('myAnchor');
if (toCheck != '') {
return true;
}
else
{
document.getElementById('myAnchor').innerHTML = 'Fred Flinstone';
}
}
this does set the innerHTML but still continues with the action. How can I stop it from continuing?
Thank you!
You should check the value of text box,
Change the code to
function go()
{
var toCheck = document.getElementById('myAnchor').value;
if (toCheck != '') {
return true;
}
else
{
document.getElementById('myAnchor').innerHTML = 'Fred Flinstone';
}
}
add the onsubmit on the form:
<form onsubmit="return true;">
...
</form>
if the return is false it will stop from submitting an opposite scenario if it's true. you could also call your functions on that attribute and do the same thing then if it doesn't fit the condition it will stop from submitting your form and do the other process you desire to happen.
Textfields use the value attribute.
document.getElementById('myAnchor').value = 'Fred Flinstone';
An empty textfield would have a value of "".
function go()
{
var toCheck = document.getElementById('myAnchor');
if (toCheck.value != "") {
return true;
}
else
{
toCheck.value = 'Fred Flinstone';
}
}
Here's a working example.
<!DOCTYPE html>
<html>
<body>
<form name="form" action="data.php">
<label style="float:left">
<font face="Comic Sans MS">* username &nbsp
</label></font>
<input type="text" id='textfield' name="name" size="40" style="float: left;">
<label id='myAnchor' style="display: inline; padding-left: 20px;"></label> <br/> <br/>
<label style="float:left"><font face="Comic Sans MS">* password &nbsp</label></font>
<input type="text" name="pwd" size="40" style="float: left;">
<label id="myAnchor2" style="display: inline; padding-left: 20px;">
</label> <br/> </p> <input type="button" value="LogIn" onClick="return go();"> </form>
</body>
<script>
function go()
{
var toCheck = document.getElementById('textfield');
if (toCheck.value != "") {
return true;
}
else
{
toCheck.value = 'Fred Flinstone';
}
}
</script>
</html>
In your question you said that
I want to check the validation of two text boxs
In that case you should be checking the value of textboxes, not the myAnchor.
I would change your html code like this:
<input type="text" name="name" id="name" size="40" style="float: left;">
<input type="text" name="pwd" id="pwd" size="40" style="float: left;">
<input type="submit" value="LogIn" onSubmit="go();">
adding id to the input boxes
then change the onClick event to onSubmit. that way you can perform javascript validation in the function, then submit the form if all goes well, otherwise display the error.
Then your script will be like...
function go() {
var name = document.getElementById('name').value,
pwd = document.getElementById('pwd').value;
if (name != '' && pwd != '') {
document.forms["form"].submit();
}
else {
document.getElementById('myAnchor').innerHTML = 'Fred Flinstone';
}
}

Categories

Resources