Printing Error/Stopping Form Submission For Digits JavaScript - javascript

Issue 1:
I'm trying to create a simple javascript function to check if all the characters entered into the field are numeric. The function is running, but not as I had hoped. I've located the isNaN function in javascript and it does not appear to be working. It enters the if statement every time, no matter if I type "asdf" or "1234" into the box.
Issue 2:
I want the form to stop submission obviously if the check for digits fails. However, I want it to continue to the submission page otherwise. I've been reading on ways to do this with pure JavaScript, and have the returns implemented as instructed. Is this a viable way to perform this? Alternatives?
Any help would be great on issue 1 or 2.
Here's my entire code:
<title>Bank System</title>
<script type="text/javascript">
function checkNumeric()
{
var pin = document.getElementById('pin');
if(isNaN(pin))
{
document.getElementById('message').innerHTML="Not A Valid Number";
return false;
}
else
{
return true;
}
}
</script>
<body style="background-color: gray;">
<h1>Welcome To Clayton's Credit Union</h1>
</br></br>
<form action="process.php" method="POST">
<label>Username: <input type="text" name="username"/></label>
</br>
<label>Pin Number<input type="text" maxlength="4" name="pin" id="pin"/></label>
</br></br>
<input type="submit" value="Submit" name="submit" onClick=" return checkNumeric()"/>
<p id="message"></p>
</br>
</form>
*Please note, I know this is not secure in anyway. I'm making this example specifically to show how vulnerable it is.

You are passing an element to isNaN rather than it's value. Try this:
var pin = document.getElementById('pin').value;
BTW
You should run this validation on the form submit rather than the button click:
<form action="process.php" method="POST" onsubmit="return checkNumeric()">
<input type="submit" value="Submit" name="submit" />
instead of:
<form action="process.php" method="POST">
<input type="submit" value="Submit" name="submit" onclick="return checkNumeric()" />

Related

I am trying to create form by putting form requirement and it's not working [duplicate]

This question already has answers here:
Difference between <input type='button' /> and <input type='submit' />
(4 answers)
Closed 2 years ago.
I have an in input required. As I am using input type="submit" it is working fine but I am using input type button. When I used input type button the input requirement doesn't work. Please help
When I used the code below with type submit the required is working
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
<form name="add_name" id="add_name">
Name: <input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>
But my form is as below. I am using input type button and the requirement is not working. How to solve it please.
<form name="add_name" id="add_name">
Name: <input type="text" name="fname" required>
<input type="button" value="Submit">
</form>
what`s up?
You just need add even listener on your button (not form), because form tag react onSubmit, but doesn`t react onClick buttons inside (like yours).
There is your right code:
<form name="myForm" action="/action_page.php" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit" onclick="return validateForm()">
</form>

How can I pass variable from the onclick of a button to the javascript code?

This code works:
<script type="text/javascript">
function submit_form()
{
if(confirm('My message here.'))
{
document.my_form_name.submit();
}
}
</script>
<form action="index.php" method="post" name="my_form_name">
<input type="button" value="Skip" onclick="submit_form()">
<input name="submit" type="submit" value="Save and continue">
</form>
HIGHLIGHTS:
function submit_form()
document.my_form_name.submit()
form action="index.php" method="post" name="my_form_name"
input type="button" value="Skip" onclick="submit_form()"
This does not work (but I want it to):
<script type="text/javascript">
function submit_form(variable)
{
if(confirm('My message here.'))
{
document.variable.submit();
}
}
</script>
<form action="index.php" method="post" name="my_form_name">
<input type="button" value="Skip" onclick="submit_form('my_form_name')">
<input name="submit" type="submit" value="Save and continue">
</form>
HIGHLIGHTS:
function submit_form(variable)
document.variable.submit()
form action="index.php" method="post" name="my_form_name"
input type="button" value="Skip" onclick="submit_form('my_form_name')"
I'm quite ok with PHP but lack decent JavaScript knowledge so if someone could point me in the right direction I'd be very happy!
And why do I need 2 buttons? Well, I want to display the skip-button to the left of the continue-button (first in HTML flow) but I do not want it to be default action if form is submitted by pressing enter key, therefore I let skip-button be "just" a button (controlled by JavaScript for submitting) and only the continue-button to be a "real" submit-button...
When you are using document.variable, it looks for something named variable. If you want it to look for the variable's value ('my_form_name'), use document[variable]:
if(confirm('My message here.'))
{
document[variable].submit();
}
#Blex has provided the right answer. Even though I am not a fan of inline JS, the following can save some typing and improve readability of your code:
HTML:
<input type="button" value="Skip" onclick="submit_form(this)">
<!-- use this instead of 'my_form_name' -->
JS:
variable.form.submit(); //instead of document[variable].submit();

Javascript form validation - PHP variable as VALUE - Invalid Input

I have an issue where I am validating form submission with javascript. The form is prefilled with results from the database as PHP values like this:
<form name="profiledit" action="profile_edited.php" method="POST" >
<h3>Name:</h3>
<input type="text" id="teamname" name="teamname"
value="<?php echo $result['teamname'];?>">
</form>
This is the javascript:
<script type="text/javascript">
function empty() {
tn = document.getElementById("teamname").value;
if (! /^[a-zA-Z0-9]+$/.test(tn)) {
alert("Please enter a valid Team Name");
return false;
}
}
</script>
The submit button is :
onClick="return empty();"
The problem is that is always tells me top "Please enter a valid Team Name" unless I retype the text in the box (that was supplied by the PHP value).
I cannot see any weird spaces or things in "view source".
What could the problem be?
Thanks.
EDIT1 : Sorry I forgot to paste closing brace. It was there in the code and this does work for BLANK forms OK. Just not when it has a prefilled value from PHP.
Try this
Check this link
Html
<form name="profiledit" action="" method="POST" id="profiledit">
<h3>Name:</h3>
<input type="text" id="teamname" name="teamname" value=""/>
<input type="button" id="submit" value="submit" name="submit" />
<input type="submit" id="submitform" value="submitform" name="submit" style="display:none;" />
</form>
Jquery
$('#submit').click(function(){
var pattern=/^[a-zA-Z0-9]*$/;
var tn = $("#teamname").val();
if(tn == "" && pattern.test(tn)){
alert('1');
}else {
//alert('2');
$('#submitform').trigger('click');
}
});
Hope its helps
Well, there was nothing wrong with the responses after all. My code was good and you guys code was good as well.
The problem?
Well I just happened to be testing with a teamname that had a SPACE in it!!!!!!!!!!
So having finally worked out that was the problem all along I would like to thank you all for your inputs.
I have used the regex instead : /^\w+( \w+)*$/
Allows words, numbers and a space.

How to get form onsubmit to check terms for Google Checkout button

I'm using Google Checkout and having a problem with the onsubmit function.
I have an "Agree to terms" checkbox that I've put in place so that users must accept the terms before continuing with the checkout. I'm calling a function on the HTML form element...
function preCheckout() {
if( !document.getElementById('terms').checked ) {
// Requirements not accepted.
$('.warning').animate({top: -$('.warning').outerHeight()}, 500);
return false;
}
}
which contains the google checkout button like so:
<form method="POST"
action="https://sandbox.google.com..."
accept-charset="utf-8" onsubmit="preCheckout();">
<div>
<input type="checkbox" id="terms" name="accept_terms" value="" />
<p>I agree to all the terms and requirements...</p>
</div>
<input type="hidden" name="item_name_1" value="Simple Notes Monthly Subscription"/>
<input type="hidden" name="item_description_1" value=""/>
<input type="hidden" name="item_quantity_1" value="1"/>
<input type="hidden" name="item_price_1" value=""/>
<input type="hidden" name="item_currency_1" value="USD"/>
<input type="hidden" name="shopping-cart.merchant-private-data" value="" />
<input type="hidden" name="tax_rate" value="0.065"/>
<input type="hidden" name="tax_us_state" value="UT"/>
<input type="hidden" name="_charset_"/>
<input type="hidden" name="continue-shopping-url" value="/thankyou.php" />
<input type="image" name="Google Checkout" id="google-btn" alt="Fast checkout through Google"
src="https://checkout.google.com/buttons/checkout.gif?merchant_id=id&w=180&h=46&style=trans&variant=text&loc=en_US"
height="46" width="180"/>
</div>
</form>
However the page continues on with or without the checkbox being checked.
What am I missing?
FYI Here's the question I really meant to ask
When you right into the onsubmit line it's self, you return the true or false respectively, right? Like so:
onsubmit="return false;"
Well let's breakdown what is actually going in your code. Because you are potentially returning false in your code, here's the two possibilities of what might happen on submit.
onsubmit="false" // form is a success and performs form action
onsubmit="" // form is a success and performs form action
but what you're really looking for is onsubmit="return false;" or onsubmit="return true;" so here's what you need to do:
function preCheckout() {
if( !document.getElementById('terms').checked ) {
// Requirements not accepted.
$('.warning').animate({top: -$('.warning').outerHeight()}, 500);
return false;
}
// return true if everything is fine
return true;
}
However, the most important part is this:
<!-- all I did was add a "return" to your onsubmit -->
<form method="POST" action="https://sandbox.google.com..." accept-charset="utf-8" onsubmit="return preCheckout();">

HTML form with two submit buttons and two "target" attributes

I have one HTML <form>.
The form has only one action="" attribute.
However I wish to have two different target="" attributes, depending on which button you click to submit the form. This is probably some fancy JavaScript code, but I haven't an idea where to begin.
How could I create two buttons, each submitting the same form, but each button gives the form a different target?
I do this on the server-side.
That is, the form always submits to the same target, but I've got a server-side script who is responsible for redirecting to the appropriate location depending on what button was pressed.
If you have multiple buttons, such as
<form action="mypage" method="get">
<input type="submit" name="retry" value="Retry" />
<input type="submit" name="abort" value="Abort" />
</form>
Note: I used GET, but it works for POST too
Then you can easily determine which button was pressed - if the variable retry exists and has a value then retry was pressed, and if the variable abort exists and has a value then abort was pressed. This knowledge can then be used to redirect to the appropriate place.
This method needs no Javascript.
Note: This question and answer was from so many years ago when "wanting to avoid relying on Javascript" was more of a thing than it is today. Today I would not consider writing extra server-side functionality for something like this. Indeed, I think that in most instances where I would need to submit form data to more than one target, I'd probably be doing something that justified doing a lot of the logic client-side in Javascript and using XMLHttpRequest (or indeed, the Fetch API) instead.
It is more appropriate to approach this problem with the mentality that a form will have a default action tied to one submit button, and then an alternative action bound to a plain button. The difference here is that whichever one goes under the submit will be the one used when a user submits the form by pressing enter, while the other one will only be fired when a user explicitly clicks on the button.
Anyhow, with that in mind, this should do it:
<form id='myform' action='jquery.php' method='GET'>
<input type='submit' id='btn1' value='Normal Submit'>
<input type='button' id='btn2' value='New Window'>
</form>
With this javascript:
var form = document.getElementById('myform');
form.onsubmit = function() {
form.target = '_self';
};
document.getElementById('btn2').onclick = function() {
form.target = '_blank';
form.submit();
}
Approaches that bind code to the submit button's click event will not work on IE.
In case you are up to HTML5, you can just use the attribute formaction. This allows you to have a different form action for each button.
<!DOCTYPE html>
<html>
<body>
<form>
<input type="submit" formaction="firsttarget.php" value="Submit to first" />
<input type="submit" formaction="secondtarget.php" value="Submit to second" />
</form>
</body>
</html>
This works for me:
<input type='submit' name='self' value='This window' onclick='this.form.target="_self";' />
<input type='submit' name='blank' value='New window' onclick='this.form.target="_blank";' />
In this example, taken from
http://www.webdeveloper.com/forum/showthread.php?t=75170
You can see the way to change the target on the button OnClick event.
function subm(f,newtarget)
{
document.myform.target = newtarget ;
f.submit();
}
<FORM name="myform" method="post" action="" target="" >
<INPUT type="button" name="Submit" value="Submit" onclick="subm(this.form,'_self');">
<INPUT type="button" name="Submit" value="Submit" onclick="subm(this.form,'_blank');">
Simple and easy to understand, this will send the name of the button that has been clicked, then will branch off to do whatever you want. This can reduce the need for two targets. Less pages...!
<form action="twosubmits.php" medthod ="post">
<input type = "text" name="text1">
<input type="submit" name="scheduled" value="Schedule Emails">
<input type="submit" name="single" value="Email Now">
</form>
twosubmits.php
<?php
if (empty($_POST['scheduled'])) {
// do whatever or collect values needed
die("You pressed single");
}
if (empty($_POST['single'])) {
// do whatever or collect values needed
die("you pressed scheduled");
}
?>
Example:
<input
type="submit"
onclick="this.form.action='new_target.php?do=alternative_submit'"
value="Alternative Save"
/>
Voila.
Very "fancy", three word JavaScript!
Here's a quick example script that displays a form that changes the target type:
<script type="text/javascript">
function myTarget(form) {
for (i = 0; i < form.target_type.length; i++) {
if (form.target_type[i].checked)
val = form.target_type[i].value;
}
form.target = val;
return true;
}
</script>
<form action="" onSubmit="return myTarget(this);">
<input type="radio" name="target_type" value="_self" checked /> Self <br/>
<input type="radio" name="target_type" value="_blank" /> Blank <br/>
<input type="submit">
</form>
HTML:
<form method="get">
<input type="text" name="id" value="123"/>
<input type="submit" name="action" value="add"/>
<input type="submit" name="action" value="delete"/>
</form>
JS:
$('form').submit(function(ev){
ev.preventDefault();
console.log('clicked',ev.originalEvent,ev.originalEvent.explicitOriginalTarget)
})
http://jsfiddle.net/arzo/unhc3/
<form id='myForm'>
<input type="button" name="first_btn" id="first_btn">
<input type="button" name="second_btn" id="second_btn">
</form>
<script>
$('#first_btn').click(function(){
var form = document.getElementById("myForm")
form.action = "https://foo.com";
form.submit();
});
$('#second_btn').click(function(){
var form = document.getElementById("myForm")
form.action = "http://bar.com";
form.submit();
});
</script>
It is do-able on the server side.
<button type="submit" name="signin" value="email_signin" action="/signin">Sign In</button>
<button type="submit" name="signin" value="facebook_signin" action="/facebook_login">Facebook</button>
and in my node server side script
app.post('/', function(req, res) {
if(req.body.signin == "email_signin"){
function(email_login) {...}
}
if(req.body.signin == "fb_signin"){
function(fb_login) {...}
}
});
Have both buttons submit to the current page and then add this code at the top:
<?php
if(isset($_GET['firstButtonName'])
header("Location: first-target.php?var1={$_GET['var1']}&var2={$_GET['var2']}");
if(isset($_GET['secondButtonName'])
header("Location: second-target.php?var1={$_GET['var1']}&var2={$_GET['var2']}");
?>
It could also be done using $_SESSION if you don't want them to see the variables.
Alternate Solution. Don't get messed up with onclick,buttons,server side and all.Just create a new form with different action like this.
<form method=post name=main onsubmit="return validate()" action="scale_test.html">
<input type=checkbox value="AC Hi-Side Pressure">AC Hi-Side Pressure<br>
<input type=checkbox value="Engine_Speed">Engine Speed<br>
<input type=submit value="Linear Scale" />
</form>
<form method=post name=main1 onsubmit="return v()" action=scale_log.html>
<input type=submit name=log id=log value="Log Scale">
</form>
Now in Javascript you can get all the elements of main form in v() with the help of getElementsByTagName(). To know whether the checkbox is checked or not
function v(){
var check = document.getElementsByTagName("input");
for (var i=0; i < check.length; i++) {
if (check[i].type == 'checkbox') {
if (check[i].checked == true) {
x[i]=check[i].value
}
}
}
console.log(x);
}
This might help someone:
Use the formtarget attribute
<html>
<body>
<form>
<!--submit on a new window-->
<input type="submit" formatarget="_blank" value="Submit to first" />
<!--submit on the same window-->
<input type="submit" formaction="_self" value="Submit to second" />
</form>
</body>
</html>
On each of your buttons you could have the following;
<input type="button" name="newWin" onclick="frmSubmitSameWin();">
<input type="button" name="SameWin" onclick="frmSubmitNewWin();">
Then have a few small js functions;
<script type="text/javascript">
function frmSubmitSameWin() {
form.target = '';
form.submit();
}
function frmSubmitNewWin() {
form.target = '_blank';
form.submit();
}
</script>
That should do the trick.
e.submitEvent.originalEvent.submitter.value
if you use event of form

Categories