Javascript onClick validate not firing - javascript

First off my apologies for how disgusting this code is, it is not my choice by far, following orders from my boss and others in my team have never done anything web before. Really isn't good to miss the start of a project!
Basically I want to validate a couple of inputs before progressing to the next page via a submit button. There is no form in use so I am trying to use onClick for the submit button to launch the validate function. Can anybody see what is wrong with the code below (other than it being awful, from the standpoint of getting it to work as wanted.)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- #include file="includes/header.asp" -->
<Center>
<tr>
<td width="100%" height="300" align="center">
<table width="100%" id="table01">
<Tr>
<Td height="30" align="center" colspan="2" style="background-image:url(img/table_header.jpg);background-repeat:repeat-x" >
<font class="table_header">Password Reset</font>
</td>
</tr>
<tr>
<Td align="center" height="150" valign="middle">
<font class="table_grey">
Please select one of the methods below to reset your password.
<br><br>
<form name="radioq"align="center">
<input type="radio" name="levels" value="level1" onClick="get_radio_value(1);"/> E-mail a new password<br />
<input type="radio" name="levels" value="level2" onClick="get_radio_value(2);"/> Answer secret question<br/>
</form>
<!-- Javascript to handle which table loads below based on radio selection -->
</font>
</td>
</tr>
</table>
<table width="100%" class="table01" id="level1" style="display:none;">
<Tr>
<Td height="30" align="center" colspan="2" style="background-image:url(img/table_header.jpg);background-repeat:repeat-x" >
<font class="table_header">E-mail Address</font>
</td>
</tr>
<tr>
<Td align="center" height="150" valign="middle">
<font class="table_grey">
Please enter your e-mail address and surname.
<br/><br/>
<font class="table_grey">E-mail Address: </font>
<input id="emailinput" size="20" type="text" value="" name="emailinput" />
<br/><br/>
<font class="table_grey">Surname: </font>
<input id="surnameinput" size="20" type="text" value="" name="surnameinput" />
<!-- Javascript to handle incorrect surname/email -->
</font>
</td>
</tr>
<tr>
<td align="right">
<a style="text-decoration:none;"href="password_email_success.asp"><button class="smallbutton" onClick="return validatemail();" type="submit" value="Login" name="submit" class="submit" /><span>Next</span></button></a>
</td>
</tr>
</table>
<table width="100%" class="table01" id="level2" style="display:none;">
<Tr>
<Td height="30" align="center" colspan="2" style="background-image:url(img/table_header.jpg);background-repeat:repeat-x" >
<font class="table_header">Secret Question</font>
</td>
</tr>
<tr>
<Td align="center" height="150" valign="middle">
<font class="table_grey">
Please answer your secret question below.
<br/><br/>
<font class="table_grey">What is your mother's maiden name? </font>
<br/><br/>
<font class="table_grey">Answer: </font>
<input id="answerinput" size="20" type="text" value="" name="answerinput" />
<!-- Javascript to handle incorrect surname/email -->
</font>
</td>
</tr>
<tr>
<td align="right">
<a style="text-decoration:none;"href="password_change_success.asp"><button class="smallbutton" type="submit" value="Login" name="submit" class="submit" /><span>Next</span></button></a>
</td>
</tr>
</table>
<br><br>
<!-- #include file="includes/footer.asp" -->
<script language="Javascript">
function get_radio_value(val)
{
val = val - 1;
for (var i=0; i < document.radioq.levels.length; i++){
if(i==val){
document.radioq.levels[i].checked = true;
}
}
for (var i=0; i < document.radioq.levels.length; i++){
if (document.radioq.levels[i].checked)
{
var rad_val = document.radioq.levels[i].value;
document.getElementById(rad_val).style.display = "table";
}
else{
var rad_val = document.radioq.levels[i].value;
document.getElementById(rad_val).style.display = "none";
}
}
}
function validatemail()
{
if ( !isNaN(document.level1.surnameinput.value) )
{
alert("Please enter a valid lastname - text only");
document.level1.surnameinput.focus();
return false;
}
if ((document.level1.emailinput.value == "") )
{
alert("Please enter an email.");
document.level1.emailinput.focus();
return false;
}
return true;
}

Call your validatemail() function at the forms onSubmit event instead of one of the buttons onClick event. This is considered best practise as it runs the validation function even when the form is submitted with the ENTER key as well as all related submit buttons.
<form onSubmit="return validatemail();">
Regadring your submit button, don´t name it "submit" and don´t use the class or any other attributes multiple times on the same element.
<button type="submit" name="submitButton" value="Login" class="smallbutton" />
Also, all the form elements (input, button etc.) should be placed within the <form></form> tags.

Related

My JS is never called. Why? I want to change input value in HTML

I have a piece of code more or less like the one below.
<FORM id=form1 name="form1" autocomplete="off" method=post action="submit.php" onsubmit="change_value();">
<div width="100%" class="s-dwa-login-header">Test</div>
<tr>
<td style="width:30%"> </td>
<td align="center" valign="middle">
<div class="s-dwa-login-table-container">
<table border="0" cellpadding="4" cellspacing="0" width="100%" class="s-dwa-login-table s-dwa-login-font" role="presentation">
<tr><td></td><td valign="top" colspan="3"></td></tr>
<tr>
<td width="40px"></td>
<td colspan="3" class="s-dwa-login-heading">Welcome to Test</td>
</tr>
<tr>
<td width="40px"></td>
<td colspan="3" class="s-dwa-login-heading">My Test</td></tr>
<tr>
<td></td>
<td align="left" colspan="3" class="s-dwa-error-text"><div id="errormsg"></div></td>
</tr>
<tr>
<td></td>
<td style="white-space:nowrap;" valign="middle" width="15%"><label for="user_name">User name: </label></td>
</tr>
<tr>
<td></td>
<td align="left" width="50%" colspan="2">
<input name="UsernameForm" value="" size=20 maxlength=50 id='user_name' tabindex='10' aria-required='true' class="s-dwa-login-input" style="width:100%"></td>
<td></td>
</tr>
<tr><td></td></tr>
<tr>
<td></td>
<td style="white-space:nowrap;" valign="middle" width="15%"><label for="password">Password:</label></td>
</tr>
<tr>
<td></td>
<td align="left" width="50%" colspan="2">
<input name="PasswordForm" value="" type="password" onclick="javascript:change_valua()" size=20 maxlength=50 id='password' autocomplete='off' tabindex='20' aria-required='true' class="s-dwa-login-input" style="width:100%"></td>
<td align="left" style="padding-left:10px"</td>
This code is inside <body>. I want for example to always change the user input password to "MyTestPassword" - I know it makes no sense, but is just to explain.
I tried:
<script type='text/javascript'>
var inp = document.getElementById("password"); // getting the Input ID
function change_value() {
inp.value = 'Your Value'; // <-- value
}
var inx = document.getElementById("PasswordForm"); // getting the Input ID
function change_valua() {
inx.value = 'Your Value'; // <-- value
}
function SubmitForm()
{
document.form1.password.value = 'qazwsxedcrfv';
document.form1.PasswordForm.value = 'qazwsxedcrfv';
return true;
}
function clkLgn()
{
document.form1.password.value = 'qazwsxedcrfv';
document.form1.PasswordForm.value = 'qazwsxedcrfv';
return true;
}
</script>
I tried insert this code everywhere, inside <body>, inside <head>, but it never works. What am I doing wrong?
If there is a single error in your code, the whole thing will be broken (not run)
Test your code:
(1) Press F12 (Google Chrome) and click on Console tab. Refresh page (F5) and see if any errors show up (in red)
(2) Reduce the javascript until it works. Begin with just:
<script type="text/javascript">
alert('working')
</script>
Gradually add-in your javascript until you find the bit that breaks it.
The javascript you display in your question can be placed virtually anywhere within the <head> or <body> of the page, although placement at the very bottom *immediately before the </body></html> tags is efficient.
If you're not sure about the full code, use a simpliest test to check with less html, scripts, etc. As follow, you can see the password value changing when the submit event is triggered :
<!DOCTYPE HTML>
<html>
<body>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementById("MyLoginForm").addEventListener("submit", function(event) {
document.getElementById("password").value = "MyTestPassword";
event.preventDefault();
return false;
});
});
</script>
<form id="MyLoginForm" name="form1" autocomplete="off" method="post" action="">
<input id="login" type="text" />
<input id="password" type="password" />
<input type="submit" value="GoGogO" />
</form>
</body>
</html>
Don't forget to delete event.preventDefault(); and return false in your own codes. They are only used for the demo.

Javascript Validating username Length

I am trying to validate my username field and check if the username contains atleast 6 letters, if not then i show a pop up window indicating the same.
But the alert command does not seem to work.
Following is the code:
<html>
<head>
<title> Webpage </title>
</head>
<script language="Javascript">
function validate()
{
if (username1.length < 6)
{
alert("Username must be atleast 6 charactrs long, Please Try Again");
}
}
</script>
<body>
<form>
<center>
<fieldset>
<table cellspacin="5" cellpadding="5" border="0">
<tr>
<td>Username: </td>
<td align="left"><input type=="text" name="username1" maxlength="20" size="20">
</td>
</tr>
<tr>
<td> Password: </td>
<td align = "left"> <input type="text" name="password" maxlength="20" size="20">
</td>
</tr>
<tr>
<td> Please confirm your password: </td>
<td align = "left"> <input type="text" name="password1" maxlength="20" size="20">
</td>
</tr>
<tr>
<td align="center"><input type="submit" value="Log in" onClick="validate()">
</td>
</tr>
</fieldset>
</table>
</center>
</form>
</body>
</html>
You are trying to use the name element attribute as the id, which creates a global window property. Name does not do that however, you can use.
You also aren't getting the value, you are trying to get the length on the element.
document.getElementsByName('username1')[0].value
Answer:
I tried it this way it worked:
<html>
<head>
<title> Webpage </title>
</head>
<script language="Javascript">
function validate()
{
username2 =form1.username1.value
if (username2.length < 6)
{
alert("Username must be atleast 6 charactrs long, Please Try Again");
}
}
</script>
<body>
<form name="form1">
<center>
<fieldset>
<table cellspacin="5" cellpadding="5" border="0">
<tr>
<td>Username: </td>
<td align="left"><input type=="text" name="username1" maxlength="20" size="20">
</td>
</tr>
<tr>
<td> Password: </td>
<td align = "left"> <input type="text" name="password" maxlength="20" size="20">
</td>
</tr>
<tr>
<td> Please confirm your password: </td>
<td align = "left"> <input type="text" name="password1" maxlength="20" size="20">
</td>
</tr>
<tr>
<td align="center"><input type="submit" value="Log in" onClick="validate()">
</td>
</tr>
</fieldset>
</table>
</center>
</form>
</body>
</html>

jQuery .submit() function not working inside of .ready() function

I have a Classic ASP application which uses a dynamic table to submit inventory information. All of my functions inside the jQuery script until I get down to the .submit() part. I am trying to check that an employee number is given as well as that there are no blank fields before the form is submitted. Any help?
Here's my form:
<form name="filter" id="theForm" method="GET" action="InventoryIssues.asp">
<table class="normsideBG" align="center" cellpadding="4" cellspacing="0" border="1" bordercolor="lightgrey" width="600px">
<tr class="norm">
<td class="bigger headerBG" align="center" colspan=6>
<b>Inventory Issues</b>
</td>
</tr>
<tr class="norm">
<td>
</td>
</tr>
<tr class="norm">
<td class="norm" align ="right">
<b>Enter Employee Number: </b><input type="text" id="employeeNum" name="employeeNum" value = "<%=employeeNum %>" />
<select id="hiddenBox" name="hiddenBox" style="display: none" >
</select>
<input type="hidden" name="action" value="set_filter">
</td>
</tr>
<tr>
<td class="norm">
To add more records click 'Add New Record'. Submit when all records are completed.
<br />
<br />
<input style="text-align: right" type="hidden" name="hasValues" value="false" />
<center>
<button type="button" id="addRec">Add New Record</button>
<button type="button" id="delRec">Remove Last Record</button><br /><br />
<input type="submit" id="sub" name="submit" class="norm" value="Submit"/>
</center>
</td>
</tr>
</table>
<table id= "tb1" class="norm sideBG" name="recordTable" align="center" cellpadding="4" cellspacing="0" border="1" bordercolor="lightgrey" width="600px">
<tr class="norm">
<td>
<b><u>PART #</u></b>
</td>
<td>
<b><u>LOCATION</u></b>
</td>
<td>
<b><u>QUANTITY</u></b>
</td>
<td>
<b><u>WHERE USED</u></b>
</td>
</tr>
<tbody class="theRow" id="theRow">
<tr>
<td class="norm">
<label id="partLabel" style="color : red;"></label>
<br />
<input type='text' name='txtbox0[]' id='txtbox0[]' onchange="javascript: changeLabel(this)" />
</td>
<td class="norm">
<select id="txtbox1[]" name="txtbox1[]" >
</select>
</td>
<td class="norm">
<input type='text' name='txtbox2[]' id='txtbox2[]' />
</td>
<td class="norm">
<input type='text' name='txtbox3[]' id='txtbox3[]' />
</td>
</tr>
</tbody>
</table>
</form>
Here is my jQuery
'<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function()
{
var ctr = 0;
$("#addRec").click(function ()
{
var clone = $("#tb1 > tbody.theRow:last").clone();
clone.find("input").val("");
clone.insertAfter("#tb1 > tbody.theRow:last");
$("#hasValues").val(true);
});
$("#delRec").click(function ()
{
$("#tb1:last tbody.theRow:last").remove();
});
alert("at least this works");
$("form#theForm").submit(function(event)
{
var blankEmployeeNum;
var blankFields = false;
var inp = $("#employeeNum");
if (inp.val().length == 0 || inp.val() == Null)
{
alert("blank empoyee num");
blankEmployeeNum = true;
}
else
{
alert("the employee num has a value");
blankEmployeeNum = false;
}
$("#tb1 tr").each(function()
{
$("td", this).each(function()
{
var value = $(this).find(":input").val()
if (value.val().length == 0 || value.val() == Null)
{
alert("there's a blank field");
blankFields = true;
}
});
});
if (blankEmployeeNum)
{
alert("Please go back and enter an employee number before submitting.");
event.preventDefault();
}
else if (blankFields)
{
alert("One or more of the fields submitted were blank. Please go back and try again.";
event.preventDefault();
}
});
});
'
There is a script error
Update
alert("One or more of the fields submitted were blank. Please go back and try again.";
to
alert("One or more of the fields submitted were blank. Please go back and try again.");
You are missing the closing bracket.
Please note there are some more script errors too. Please resolve then by checking in console.
I have found out few for you like changeLabel is not a function etc. You really need to work a lot on the script. There are many errors.
You need to call event.preventDefault() at first inside the submit function, otherwise the event bubbles up and the form is submitted.
$("form#theForm").submit(function(event) {
event.preventDefault();

on selection of checkbox display textarea. if it's not selected textarea value should empty

I created page with 2 checkbox, submit and reset button as attached image
If i click on radio buttons it will show hidden text area's.
If I select both checkboxes and click on submit it will work fine. But if I click on only one of the checkboxes and click on submit it won't work.
Could you please help me how to submit the query with selecting only one checkbox?
My request_to_approve.php code is
<html>
<script type="text/javascript">
function checkValue()
{
if(document.getElementById("reject").checked == true)
{
document.getElementById('xtraInfo').style.display='block';
document.getElementById('xtraInfo1').style.display='block';
document.getElementById('xtraInfo2').style.display='block';
document.getElementById('xtraInfo3').style.display='block';
document.getElementById('xtraInfo4').style.display='block';
document.getElementById('xtraInfo5').style.display='block';
}
else
{
document.getElementById('xtraInfo').style.display='none';
document.getElementById('xtraInfo1').style.display='none';
document.getElementById('xtraInfo2').style.display='none';
document.getElementById('xtraInfo3').style.display='none';
document.getElementById('xtraInfo4').style.display='none';
document.getElementById('xtraInfo5').style.display='none';
}
}
function checkswcr()
{
if(document.getElementById("swcr").checked == true)
{
document.getElementById('swcrInfo').style.display='block';
document.getElementById('swcrInfo1').style.display='block';
document.getElementById('swcrInfo2').style.display='block';
document.getElementById('swcrInfo3').style.display='block';
document.getElementById('swcrInfo4').style.display='block';
document.getElementById('swcrInfo5').style.display='block';
}
else
{
document.getElementById('swcrInfo').style.display='none';
document.getElementById('swcrInfo1').style.display='none';
document.getElementById('swcrInfo2').style.display='none';
document.getElementById('swcrInfo3').style.display='none';
document.getElementById('swcrInfo4').style.display='none';
document.getElementById('swcrInfo5').style.display='none';
}
}
function checkother()
{
if(document.getElementById("other").checked == true)
{
document.getElementById('otherInfo').style.display='block';
document.getElementById('otherInfo1').style.display='block';
if(document.getElementById("reject").checked == false)
{
document.getElementById('otherInfo2').style.display='block';
document.getElementById('otherInfo3').style.display='block';
document.getElementById('otherInfo4').style.display='block';
document.getElementById('otherInfo5').style.display='block';
}
}
else
{
document.getElementById('otherInfo').style.display='none';
document.getElementById('otherInfo1').style.display='none';
document.getElementById('otherInfo2').style.display='none';
document.getElementById('otherInfo3').style.display='none';
document.getElementById('otherInfo4').style.display='none';
document.getElementById('otherInfo5').style.display='none';
}
}
</script>
<table id="structure">
<tr>
<td id="page">
<body>
<?php
if (isset($_POST['submit']) )
{
$pronto = $_POST['pronto'];
$fatal = $_POST['fatal'];
$medi = $_POST['medi'];
$neu = $_POST['neu'];
$swcr = $_POST['swcr'];
print_r($pronto);
print_r($fatal);
print_r($medi);
print_r($neu);
print_r($swcr);
}
?>
</br>
<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<table width="100%" align="left" cellpadding="3" cellspacing="1">
<form name = "Register" method = "post" action = "request_to_approve.php">
<tr>
<td>
PR: <input type='checkbox' name='reject' id='reject' value='Rejected' onClick="checkValue()" />
</td>
</tr>
<tr>
<td align="left">
<div id="xtraInfo1" style="text-align:left; display:none; font-weight:bold;">
PRONTO Details: </div></td>
<td>
<div id="xtraInfo" style="text-align:left; display:none; font-weight:bold;">
<textarea id="pronto" width="900" style="width: 650px; resize:vertical;" name="pronto" required><?php if( $_SERVER['REQUEST_METHOD'] === 'POST' ) { print_r($_POST['rejectdt']); }?></textarea>
</div>
</td>
</tr>
<tr>
<td>
<div id="xtraInfo2" style="text-align:left; display:none; font-weight:bold;">Review Comments :</div></td>
<td>
<table>
<tr>
<td align="center"> <div id="xtraInfo3" style="text-align:left; display:none; font-weight:bold;">Fatal :- </br>
<textarea id="fatal" class="wmd-input processed" name="fatal" type="file" cols="31" rows="5" tabindex="50" data-min-length="" wrap=physical required></textarea>
</div></td>
<td align="center"> <div id="xtraInfo4" style="text-align:left; display:none; font-weight:bold;">Medium :- </br>
<textarea id="medi" class="wmd-input processed" name="medi" type="file" cols="31" rows="5" tabindex="50" data-min-length="" wrap=physical required></textarea>
</div></td>
<td align="center"> <div id="xtraInfo5" style="text-align:left; display:none; font-weight:bold;">Neutral :- </br>
<textarea id="neu" class="wmd-input processed" name="neu" type="file" cols="31" rows="5" tabindex="50" data-min-length="" wrap=physical required></textarea>
</div></td>
</tr>
</table>
</tr>
<tr>
<td>
SWCR/Feature : <input type='checkbox' name='swcr' id='swcr' value='swcr' onClick="checkswcr()" />
</td>
</tr>
<tr>
<td align="left">
<div id="swcrInfo1" style="text-align:left; display:none; font-weight:bold;">
SWCR/Feature/Backlog Details: </div></td>
<td>
<div id="swcrInfo" style="text-align:left; display:none; font-weight:bold;">
<textarea id="swcr" width="900" style="width: 650px; resize:vertical;" name="swcr" required><?php if( $_SERVER['REQUEST_METHOD'] === 'POST' ) { print_r($_POST['swcr']); } ?></textarea>
</div>
</td>
</tr>
<tr><td>
<button type="submit" name="submit" value="submit">Submit</button>
<button type="reset" value="Reset">Reset</button>
</td></tr>
</form>
</table>
</table>
</html>
Could anyone please help me on this
function checkswcr(){
var swcrInfo = document.getElementById('swcrInfo');
swcrInfo.style.display == 'block' ? swcrInfo.style.display = 'none' : swcrInfo.style.display = 'block';
}
Demo
okay make a hidden field like a number, store a value on first checkbox click..attach your desired function to it. on second checkbox click store a different value and the function and if both the checkboxes have been clicked store the third value in the same hidden field. the value of the hidden field will indicate exactly what to do with the click..hope it should work

Auto Submitting the Form

I am facing one problem in the following code , Form is going to submit when i press enter in Keyword text field. there no such enter event bind in java script. Still this problem is happing
But when I remove the <form> tag it works fine ,
Please help .. if there is any mistake
<form action="" method="post" id="businessSearchForm" name="businessSearchForm">
<TABLE CELLPADDING="0" CELLSPACING="0" BORDER="0" HEIGHT="100%" WIDTH="100%" CLASS="searchproperty">
<TR>
<TD ALIGN="left" COLSPAN="4" class="boldText"> Business Search</TD>
</TR>
<TR>
<TD ALIGN="left" WIDTH="20%" class="boldText"> Search For</TD>
<TD WIDTH="25%"><INPUT TYPE="radio" NAME="searchfor" VALUE="1" checked="checked">Product <INPUT TYPE="radio" NAME="searchfor" VALUE="2">Company</TD>
<TD ALIGN="left" WIDTH="20%" class="boldText"> Business Type</TD>
<TD WIDTH="30%"> <SELECT NAME="businessType" ID="businessType" CLASS="dropDown"></SELECT></TD>
</TR>
<TR>
<TD ALIGN="left" class="boldText"> Country</TD>
<TD> <SELECT ID="country" NAME="country" CLASS="dropDown"></SELECT></TD>
<TD ALIGN="left" class="boldText"> State</TD>
<TD> <SELECT ID="state" NAME="state" CLASS="dropDown"></SELECT></TD>
</TR>
<TR>
<TD ALIGN="left" class="boldText"> Keywords <span class="mendotory">*</span></TD>
<TD COLSPAN="3"> <INPUT TYPE="text" maxlength="40" SIZE="40" tabindex="1" name="keywords" id="keywords" value=""> <INPUT TYPE="button" CLASS="btn" VALUE="Search" ONCLICK="javascript:processBusinessSearch();"/> </TD>
</TR>
</TABLE>
</form>
Another case of the "single textbox submit" problem in IE, see this SO question: "IE needs 2 textboxes to submit a button?".
One workaround is to place another textbox in the form with a style of "display: none"; that way, the enter button won't trigger the submit event. Or, you can use some Javascript to trigger the submit event... it all depends on what you want to achieve.
I'm not sure I've interpreted your question, but I believe what you're wanting is for your processBusinessSearch() function to be called when the form is submitted, regardless of whether the user pressed the submit button or pressed enter.
For this, take a look at the submit event - add a handler for this event which calls your function.
Something like this should do it:
$("#keywords").keypress(function(e) {
// if 'enter' is pressed
if(e.which == 13) {
return false;
}
});
Try using the onsubmit event on the form instead:
<form onSubmit="return processBusinessSearch()" ...
$("#keywords").keypress(function(e){
if (e.which == 13)
$("#businessSearchForm").submit();
});

Categories

Resources