force form submit button click with jquery - javascript

Trying to trigger the submit functionality from JQuery. what am I doing wrong? In theory, this should work. I've tried about 4 different ways though.
I have tried
$('input#submit').trigger("click");
$( form:first ).submit();
$( form:first ).trigger("submit");
$('form#databaseActionForm').submit();
NOTHNG HAS WORKED (YET)?!
CODE:
<html lang="en">
<head>
<title>Database Management</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<script src="http://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
<style>
table td { border: 1px solid black; }
table td:first-child { text-align: left; }
</style>
<script>
<!--
$(document).ready(function() {
$('#erase').click(function() {
if (confirm("Are you sure that you want to ERASE ALL DATA from the database?"))
{
$('#buttonTypePressed').val("erase");
$('input#submit').trigger("click"); <!-- HERE -->
}
});
$('#update').click(function() {
var appID = $('#updateAppID').val();
var field = $('#fieldName').val();
var value = $('#newValue').val();
if (appID == null || appID == "") {
alert("You must enter the ID number of the entry you wish to modify.");
$('#updateAppID').focus();
}
else if (field == null || field == "") {
alert("You must choose which field you wish to modify.");
$('#fieldName').focus();
}
else if (value == null || value == "") {
alert("You must choose the new value you wish to appear in the database.");
$('#newValue').focus();
}
else {
$('#buttonTypePressed').val("update");
$('input#submit').trigger("click"); <!-- HERE -->
}
});
$('#delete').click(function() {
var appID = $('#deleteAppID').val();
if (appID == null || appID == "") {
alert("You must enter the ID number of the entry you wish to delete.");
$('#deleteAppID').focus();
}
else {
$('#buttonTypePressed').val("delete");
$('input#submit').trigger("click"); <!-- HERE -->
}
});
});
-->
</script>
</head>
<body>
<div id="container">
<from id="databaseActionForm" name="databaseActionForm" method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
<table border=0 style="margin: 50px auto; text-align: right;">
<tr style="text-align: center; font-weight: bold; font-size: 1.5em; text-decoration: underline;">
<th>Action</th>
<th>Additional Info</th>
<th>Button</th>
</tr>
<tr name="Clear">
<td>Erase Database</td>
<td style="text-align: center;">ARE YOU SURE?</td>
<td><input type="button" id="erase" name="erase" value="ERASE ALL?" /></td>
</tr>
<tr name="Update">
<td>Update Value</td>
<td>
Entry ID: <input type="text" id="updateAppID" name="updateAppID" placeholder="App entryID" /><br />
Field Name: <input type="text" id="fieldName" name="fieldName" placeholder="Field to change" /><br />
New Value: <input type="text" id="newValue" name="newValue" placeholder="New value" /><br />
</td>
<td><input type="button" id="update" name="update" value="Update Value" /></td>
</tr>
<tr name="Delete">
<td>Delete Payment</td>
<td>
Entry ID: <input type="text" id="deleteAppID" name="deleteAppID" placeholder="App entryID" />
</td>
<td><input type="button" id="delete" name="delete" value="Delete Entry" /></td>
</tr>
</table>
<input type="hidden" id="buttonTypePressed" name="buttonTypePressed" />
<input type="submit" id="submit" name="submit" value="submit" style="position: absolute; left: -9999px; width: 1px; height: 1px;" tabindex="-1"/>
</form>
</div>
</body>

There are 2 issues here, 1 is a typo in the element name form, you have it as from.
Another is the name/id of the submit button, it should not be submit as it will override the default submit property(the function) of the form element
<input type="submit" id="bsubmit" name="bsubmit" value="submit" style="position: absolute; left: -9999px; width: 1px; height: 1px;" tabindex="-1" />
Then just use the below snippet to submit the form
$('#databaseActionForm').submit();
Demo: Fiddle

I think the problem is you misspelled "form" as "from". Check the syntax highlighting. After that, any of these will work:
$('form#databaseActionForm').submit();
$('#databaseActionForm').submit(); // referencing the form's ID
document.databaseActionForm.submit(); // referencing the form's NAME

Related

JavaScript - How to place asterisk in the right side of the text box?

I want to place asterisk in the right side of the each text box individually when I am submitting the empty form/field. The code is working but asterisk is displaying in the end of the form.
This is my code:
[<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
<title></title>
<style type="text/css">
body { font-family:arial, helvetica, sans-serif; font-weight:bold; font-size:13px; color:#000; text-align:left; margin:3px 0px; }
input { text-align:center; border:2px solid #CCC; }
#wrap { width:400px; height:200px; margin:20px; padding:10px; }
#une { margin-top:10px; }
#reg {margin-top:10px; }
.a13B { color:#F00; }
.cntr { text-align:center; }
</style>
</head>
<body>
<div id="wrap">
<form id="regform" name="registerationform" method="POST">
<table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse" width="300">
<tr>
<td>First Name: </td>
<td class="cntr">
<input type="text" name="fnametxt" size="20"></td>
</tr>
<tr>
<td>Second Name: </td>
<td class="cntr">
<input type="text" name="snametxt" size="20"> </td>
</tr>
<tr>
<td>User Name:</td>
<td class="cntr">
<input type="text" name="unametxt" size="20"> </td>
</tr>
<tr>
<td>Email Address: </td>
<td class="cntr">
<input type="text" name="emailtxt" size="20"> </td>
</tr>
<tr>
<td>Password : </td>
<td class="cntr"><input type="password" name="pwdtxt" size="20"> </td>
</tr>
<tr>
<td>Confirm : </td>
<td class="cntr"><input type="password" name="cpwdtxt" size="20"> </td>
</tr>
</table>
<input id="reg" name="reg" type="button" onclick="regvalidate(this.form)" value="Register Now">
</form>
<div id="une" class="a13B">
</div>
</div>
<!-- end wrap -->
<script type="text/javascript">
var uneObj=document.getElementById("une"); // object ref to msg line
var currentBrdObj;
//
function regvalidate(formObj)
{ uneObj.innerHTML=""; // clear msg line before resubmitting
// gather object ref to input boxes
var allInputs=document.getElementById("regform").getElementsByTagName("input");
// check if value of box is ""
for(var i=0;i<allInputs.length;i++)
{ if(allInputs\[i\].name !="reg") // ignore submit button
{ if(allInputs\[i\].value=="")
{ uneObj.innerHTML=msg\[i\];
if(currentBrdObj){currentBrdObj.style.border="2px solid #CCC"; }
allInputs\[i\].style.border="2px solid #F00";
currentBrdObj=allInputs\[i\];
allInputs\[i\].onclick=function(){ this.style.border="2px solid #CCC"; }
return;
} } }
// check if password and confirm are the same
if((formObj.pwdtxt.value) != (formObj.cpwdtxt.value))
{ uneObj.innerHTML = msg\[msg.length-1\]; // last msg in array
formObj.pwdtxt.value = ""; formObj.pwdtxt.style.border="";
formObj.cpwdtxt.value = ""; formObj.cpwdtxt.style.border="";
return;
}
// all ok so submit form
uneObj.innerHTML = "All ok so submitting form";
formObj.submit();
}
// -----
var msg =\["*","*",
"*","*",
"*","*"\];
msg\[msg.length\]="Passwords must be equal.<br>Please type a password";
//
</script>
</body>
</html>][1]
#PawanKumar
Here is your code:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#submitBtn').on('click', function(e) {
debugger;
e.preventDefault();
var fields = document.getElementsByTagName('input');
for (var i = 0; i < fields.length; i++) {
if (fields[i].hasAttribute('required')) {
if (fields[i].value == "") {
fields[i].classList.add('redBorder');
$(fields[i]).after('*');
} else {
fields[i].classList.remove('redBorder');
}
}
}
});
});
</script>
<style>
.redBorder {
border: 2px solid red;
border-radius: 2px;
}
</style>
</head>
<form novalidate>
<input type="text" placeholder="first name" required/><br/><br/>
<input type="text" placeholder="last name" /><br/><br/>
<button id="submitBtn" value="Submit">Submit</button>
</form>
</html>
Use span element to display asterisk at the end of text box. Try this :
<input type="text" id="name"/> <span style="color:red"> * </span>
Hope this solves your requirement.
Why bother with all that mess?
<input type="text" name="fnametxt" required />*
<input type="email" name="emailtxt" required />*
<input type="submit" value="Register" />
JavaScript required: none at all
With the help of jquery after() method, you can achieve this.
$(fields[i]).after("<span class='redColor'>*</span>");
I have also added code to show red border for required input field.
Note: If you use <form> tag, then HTML5 will automatically does the validation and your script will not execute, so to prevent that use novalidate attribute in the form tag or just remove the form tag.
$(document).ready(function() {
$('#submitBtn').on('click', function(e) {
e.preventDefault();
var fields = document.getElementsByTagName('input');
for (var i = 0; i < fields.length; i++) {
if (fields[i].hasAttribute('required')) {
if (fields[i].value == "") {
fields[i].classList.add('redBorder');
$(fields[i]).after("<span class='redColor'>*</span>");
} else {
fields[i].classList.remove('redBorder');
}
}
}
});
});
.redBorder {
border: 2px solid red;
border-radius: 2px;
}
.redColor{
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form novalidate>
<input type="text" placeholder="first name" required/><br/><br/>
<input type="text" placeholder="last name" /><br/><br/>
<button id="submitBtn" value="Submit">Submit</button>
</form>

JavaScript uncaught reference error using onclick attribute in input form tag

JavaScript Function
function submitToServer(formObject)
{
if(validateUserName(formObject["userName"]) && validatePassword(formObject["password"]))
{
formObject.submit();
}
}
HTML FORM FIELD
<form method="POST" action="SignIntoPortal">
<table>
<tr>
<td> User Name : </td>
<td>
<input type="text" id="userName" name="userName" onblur="validateUserName(this)">
<span id="userName_help" />
</td>
</tr>
<tr>
<td> Password : </td>
<td>
<input type="password" id="password" name="password" onblur="validatePassword(this)">
<span id="password_help" />
</td>
</tr>
<br>
</table>
<input type="button" name="submitButton" id="submitButton" value="Submit" onclick="submitToServer(this.form);">
</input>
</form>
The above is my code, which validates data and submits the form. but i keep getting
Uncaught ReferenceError: submitToServer is not defined
error, which I am unable to resolve. what could be the reason?
But, when I tried it with different form it worked with different names and fields.
EDIT
the difference between the code that worked and this is that, the former code does not use table it works smooth. Does scope change with table ?
You can find the code here CODE FIDDLE
You can get .html file here
SignIn.html
<html>
<head>
<title>Sign into Shopping Zone</title>
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-8">
<style>
body
{
font: 14px verdana;
}
h1
{
font: arial-black;
color: blue;
}
</style>
<script type="javascript" language="text/javascript">
function submitToServer(formObject)
{
if(validateUserName(formObject["userName"]) && validatePassword(formObject["password"]))
{
formObject.submit();
}
}
function validateUserName(inputField)
{
if(inputField.value.length == 0)
{
document.getElementById("userName_help").innerHTML = "Please enter value";
return false;
}
else
{
document.getElementById("userName_help").innerHTML = "";
return true;
}
}
function validatePassword(inputField)
{
if(inputField.value.length == 0)
{
document.getElementById("password_help").innerHTML = "Please enter value";
return false;
}
else
{
document.getElementById("password_help").innerHTML = "";
return true;
}
}
</script>
</head>
<body>
<h1><b><i>Shopping Zone</i></b></h1>
<p> Kindly Provide Login info
</p>
<!-- SignIn Form Data for Passing to SignIntoPortal-->
<form method="POST" action="SignIntoPortal">
<table>
<tr>
<td> User Name : </td> <td><input type="text" id="userName" name="userName" onblur="validateUserName(this)"><span id="userName_help" /></td>
</tr>
<tr>
<td> Password : </td> <td><input type="password" id="password" name="password" onblur="validatePassword(this)"><span id="password_help" /></td>
</tr>
<br>
</table>
<input type="button" name="submitButton" id="submitButton" value="Submit" onclick="submitToServer(this.form)"></input>
</form>
</body>
</html>
in the script header, your 'type' and 'language' attributes are mixed up. type should be 'text/javascript' and language should be 'javascript' although the language attribute is not required
<script type="text/javascript" language="javascript">

JS Registration Form

I am creating a registration form with a name a email and a phone number. I have a name id a phone id and a email id also I have txtNameError, txtPhoneError, and txtEmailError and I am using a bnt button id.
Here is the HTML for the program.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Week 12: Registration Form</title>
</head>
<body>
<div class="page">
<table>
<tr>
<td><input type="text" name="txtName" id="txtName" placeholder="Name" /></td>
<td><p class="error" id="txtNameError">Name must be at least 6 characters long.</p>
</td>
</tr>
<tr>
<td><input type="text" name="txtPhone" id="txtPhone" placeholder="Phone: ###-###-
####" /></td>
<td><p class="error" id="txtPhoneError">Phone must be in the format ###-###-####.</p>
</td>
</tr>
<tr>
<td><input type="text" name="txtEmail" id="txtEmail" placeholder="Email Address" />
</td>
<td><p class="error" id="txtEmailError">Must be a valid email address.</p></td>
</tr>
<tr>
<td colspan="2" style="text-align:center;"><button id="btnRegister"
name="btnRegister">Register</button></td>
</tr>
</table>
</div>
<link type="text/css" rel="stylesheet" href="week12.css" />
<script type="text/javascript" src="week12.js"></script>
</body>
</html>
and my JavaScript:
var txtEmail = document.getElementById('txtEmail');
var txtPhone = document.getElementById('txtPhone');
var txtName = document.getElementById('txtName');
var txtEmailError = document.getElementById('txtEmailError');
var txtPhoneError = document.getElementById('txtPhoneError');
var txtNameError = document.getElementById('txtNameError');
function register(){
if (/^[A-Z \.\-']{6,20}$/i.test(txtName.value)) {
p.error {display:none;}
} else {
p.error {display:txtNameError;}
}
if (/\d{3}[ \-\.]?\d{3}[ \-\.]?\d{4}/.test(txtPhone.value)) {
p.error {display:none;}
} else {
p.error {display:txtPhoneError;}
}
if (/^[\w.-]+#[\w.-]+\.[A-Za-z]{2,99}$/.test(txtEmail.value)) {
p.error {display:none;}
} else {
p.error {display:txtEmailError;}
}
}
{
var btnRegister = document.getElementById('btnRegister');
btnRegister.onclick = register;
}
I'm using Modern javascript develop and design which was written by larry ullman.
I'm not sure though on how I am suppose to get the txterrors to work before I had a style.visibility in the html which I could set the if and else statement and if it was true I could make it hid or vis or if false hid or vis. I'm not sure on how to do this though I did read about addErrorMessage() and removeErrorMessage() functions which I would add the id and the error message but I am not sure what that means though since in the html file I was provided the Error msg are in the html file. Thanks For any tips.
CSS
body {
margin: 0;
}
.page {
margin: 10px auto;
height: 500px;
width: 500px;
background: #CCC;
}
.page table {
width: 500px;
height: 500px;
}
.error {
color: #FF0000;
font-weight: bold;
font-style: italic;
visibility: hidden;
}
You use in one place
var txtPhone = U.$('phone');
and in other
var txtNameError = document.getElementById('txtNameError');
I think this is copy and paste and you don't understand how it work.
And in your html not exists fields with name or id "phone".
In first you should use one method for access to HTML elements.
var txtPhone = document.getElementById('txtPhone');
This code is very strange too:
if (/^[A-Z .-']{2,20}$/i.test(txtName.value.length > 6))
For check length you should make check it separate or change regexp.
if (/^[A-Z \.\-']{7,20}$/i.test(txtName.value))
For hidden errors text you can use CSS. For example,
p.error {display:none;}
For show error you should make error message visible
if (/^[A-Z .-']{7,20}$/i.test(txtName.value)) {
//value is correct. make some if need
} else {
//value is wrong
//show element txtNameError
}

Stuck trying to assign JS vars to hidden fields

I've been fighting with this for a couple of days now...need some guidance please.
I have pared down a much bigger form to a "sample" size to demonstrate what I am after.
The area in question is blocked off in a very recognizable area in the calcFees function.
I also tried to get fancy and have the vars self post to the form so they could be seen, but that does not work.
UPDATE: Here is a bit more info as to what I am running into.
//At this point the var regularfee is = 26.5
// (confirmed by console.log(regularfee);)
// I want to assign it to the hidden field with the id="regularfee"
// I have tried both of the following lines:
document.getElementById('regularfee').value=regularfee.value;
// console.log(document.getElementById('regularfee.value')); shows "null"
document.getElementById('regularfee').value=regularfee;
// console.log(document.getElementById('regularfee')); shows "[object HTMLDivElement]"
What am I doing wrong?
END OF UPDATE *****************************
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="multiForm" action="post.php" method="POST" id="app" name="app">
<div id="page1" class="page" style="visibility:visible;">
Name: <input type="text" size="40" name="name1" >
<br><br>
<table border="1" cellpadding="5" width="50%">
<tbody>
<tr>
<td align="center" colspan="3"><strong>Membership Classification</strong></td>
</tr>
<tr><td width="1000">
<input name="paymethod" type="radio" class="pay" id="paypal" value="paypal" />I would like to use PayPal   
<input name="paymethod" type="radio" class="pay" id="check" value="check" />I would like to pay by check
</td>
<td style="width:150px" align="right">Fee
</td>
<td style="width:150px">
</td></tr>
<tr>
<td><input name="memberclass" type="radio" class="membership" id="regular" value="regular"/> Regular Membership</td>
<td align="right"><div id=regularfee></td>
<td><div align="right" id=regselectedfee></td>
</tr>
<tr><td colspan="2" align="right">Total </td>
<td><div align="right" id=total>
</td></tr></tbody>
</table>
<input type="hidden" name="regularfee" id="regularfee" value="">
<input type="hidden" name="regselectedfee" id="regselectedfee" value="">
<input type="hidden" name="total" id="total" value="">
</form>
<br>
<input type="button" id="C1" value="Continue" onClick="showLayer('page2')">
</td></tr>
</table>
</div>
<div id="page2" class="page">
<b>Page 2
<br><br>
<input type="button" id="B1" value="Go Back" onClick="showLayer('page1')">
<input type="submit" name="submit" value="Click to see Vars" />
</div>
</form>
</body>
</html>
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script language="JavaScript">
var paypalselected
var checkselected
var regularfee
var memberfee1
var total
$(function () {
function clearForm()
{
paypalselected = "0";
checkselected = "0";
regularfee = 0.0;
memberfee1 = 0.0;
total = 0.0;
$("#regselectedfee").text(memberfee1.toFixed(2));
$("#total").text(total.toFixed(2));
// clear all radio buttons
$("#regular").prop("checked", false );
}
function calcFees()
{
total = (memberfee1);
$("#total").text(total.toFixed(2));
// **********************************************************************************
// Here is where I want to plug in the 3 JS vars to the hidden fields
// regularfee, regselectedfee, total
// Here is what I've tried:
// vars are not getting plugged in
// If possible, I would like the vars to be plugged in dynamically
// just as the form is updateddynamically when user selects buttons
document.getElementById('regularfee').value=regularfee;
document.getElementById('regselectedfee').value=regselectedfee;
document.getElementById('total').value=total;
// **********************************************************************************
}
function selectPayment()
{
$(".pay").change(function () {
clearForm();
if ($("#paypal").prop("checked")) {
regularfee = 26.50;
$("#regularfee").text(regularfee.toFixed(2));
paypalselected = "1";
checkselected = "0";
}
if ($("#check").prop("checked")) {
regularfee = 25.0;
$("#regularfee").text(regularfee.toFixed(2));
checkselected = "1";
paypalselected = "0";
}
});
}
clearForm();
selectPayment();
//start of membership button selection
$(".membership").change(function () {
if (paypalselected == "1"){
if ($("#regular").prop("checked")) {
memberfee1 = 26.5;
$("#regselectedfee").text(memberfee1.toFixed(2));
calcFees();
}
} //end of paypalselected test
if (checkselected == "1"){
if ($("#regular").prop("checked")) {
memberfee1 = 25.0;
$("#regselectedfee").text(memberfee1.toFixed(2));
calcFees();
}
} //end of checkselected test
}); //end of $(".membership").change(function () {
});
//end of main function
var currentLayer = 'page1';
function showLayer(lyr){
hideLayer(currentLayer);
document.getElementById(lyr).style.visibility = 'visible';
currentLayer = lyr;
window.scrollTo(0,0);
}
function hideLayer(lyr){
document.getElementById(lyr).style.visibility = 'hidden';
}
</script>
<style>
body{
font: 10pt sans-serif;
}
.page{
position: absolute;
top: 10;
left: 100;
visibility: hidden;
}
p.small
{
line-height: 5px;
}
p.smalltext12
{
font-size:12px
}
</style>
You have 2 elements #total. Only the first is given a value:
document.getElementById('total').value = total;
Same for the others.
IDs must be unique to be useful.

Javascript tabindex focus sets focus to next element

In the below sample, I am trying to have the navigation within the div. Used a JS function to get the current element and check and set the focus. But it sets the focus to next element always. Can somebody check?
function loadOverlay(event) {
var oly = document.getElementById('overlay');
oly.style.display = "block";
document.getElementById('userName').focus();
}
// restore page to normal
function restore() {
// document.body.removeChild(document.getElementById("overlay"));
//document.getElementById('overlay').focus();
}
// restore page to normal
function sayHi() {
alert("Hi");
}
function navigate(event, maxtab) {
//alert(event);
if (window.event) {
caller = window.event.srcElement; //Get the event caller in IE.
key = window.event.keyCode; //Get the keycode in IE.
} else {
caller = event.target; //Get the event caller in Firefox.
key = event.which; //Get the keycode in Firefox.
}
var currtab = document.activeElement.tabIndex;
// alert(key);
if (key == 9) {
if (currtab == 6) {
document.getElementById("userName").focus();
}
}
}
#outer {
width: 100%;
height: 100%;
}
.overlay {
background-color: grey;
opacity: .7;
filter: alpha(opacity=70);
position: fixed;
top: 100px;
left: 100px;
width: 500px;
height: 300px;
z-index: 10;
border: 1px solid black;
display: none;
}
<div id="outer">
<p>Check overlay</p>
<input type=button onclick="loadOverlay(event)" value="Open overlay">
</div>
<div id="overlay" class="overlay" onkeydown="navigate(event, 5)">
<h1>Enter your Name and Pasword </h1><br>
<table border=1>
<tr>
<td>Enter Your Name :</td>
<td>
<input tabindex="2" type="text" id="userName" value=""></td>
</tr>
<tr>
<td>Enter Your PassWord :</td>
<td><input tabindex="3" type="password" id="userPassWord" value=""></td>
</tr>
<tr>
<td>Confirm Your PassWord :</td>
<td><input tabindex="4" type="password" id="userRePassWord" value=""></td>
</tr>
<tr>
<td align=center><input tabindex="5" type="submit" id="formsub" name="Submit" value="Submit"></td>
<td align=center><input tabindex="6" type="reset" id="formref" name="reset" value="Refresh"></td>
</tr>
</table>
</div>

Categories

Resources