window.location.href still not working after cancelling form submission - javascript

I have an login form
<div id='login_form'>
<table>
<tr>
<td>Username:</td>
<td><input size=25 type='text' id='username'></td>
</tr>
<tr>
<td>Password:</td>
<td><input size=25 type='password' id='password'></td>
</tr>
<tr>
<td colspan='2' align='right'>
<input type='button' id='login' value='Login' onkeydown='normalobjKeyFunc(this)' onfocus='itemFocus(this)' onblur='itemBlur(this)'/>
</td>
</tr>
</table>
</div>
then I have javaScript
var input_username = document.getElementById("username").value;
var input_password = document.getElementById("password").value;
if(input_username === "123" && input_password === "456"){
alert("Correct username & password");
window.location.href="../../result.html";
return false;
}
But when I received the alert "Correct username & password", the page was not redirected to result.html. And I checked, "../../result.html" exists.
I found some people said the submission should be cancelled, so I deleted form and changed the " type = "submit" " to " type = "button" "for Login button, but it was not working.
And there is also another method, add "return false" after " window.location.href="../../result.html" ", but it was not working as well.
Any one has any idea????
Thanks in advance!

Username/password checking should be done on the backend (Java, PHP, Node, .NET)
Your form should be in a form tag though. The checking should be done in the onsubmit callback:
<script>
function authenticate(){
var input_username = document.getElementById("username").value;
var input_password = document.getElementById("password").value;
if(input_username==="123"&&input_password==="456"){
alert("Correct username & password");
window.location.href = "../../result.html";
}
else {
// Error
}
return false;
}
</script>
<form onsubmit="authenticate()">
<table>
<tr>
<td>Username:</td>
<td><input size="25" type="text" id="username"></td>
</tr>
<tr>
<td>Password:</td>
<td><input size="25" type="password" id="password"></td>
</tr>
<tr>
<td colspan="2" style="text-align: right">
<button onkeydown="normalobjKeyFunc(this)" onfocus="itemFocus(this)" onblur="itemBlur(this)">Login</button>
</td>
</tr>
</table>
</form>

Put an onclick in your button to call your javascript function..
<input type='button' id='login' onclick="authenticate()" value='Login' onkeydown='normalobjKeyFunc(this)' onfocus='itemFocus(this)' onblur='itemBlur(this)'/>

Related

Cannot set property 'innerHTML' of null with array

Could somebody tell what is wrong here? I have a form with validation of email address and what is supposed to do is when is correct to make a new array and to print below form and when it's not just one simple alert. This is HTML:
<form>
<table>
<tr>
<td>Your email address</td>
<td>
<input type="text" id="txtEmail">
</td>
</tr>
<tr>
<td>
<input type="button" value="Register me" onclick="check();">
</td>
</tr>
</table>
</form>
This is JS:
function check() {
var email = document.getElementById("txtEmail").value;
var reEmail = /^(\w)+(\d)*(\.\_)*#[a-z]{2,10}\.[a-z]{2,5}$/;
var correct = new Array();
if(email.match(reEmail)){
correct.push(email);
document.getElementById("prikaz").innerHTML = correct;
}
else {
alert("Not correct");
}
}
Your HTML should be like this:
<form>
<table>
<tr>
<td>Your email address</td>
<td>
<input type="text" id="txtEmail">
</td>
</tr>
<tr>
<td>
<input type="button" value="Register me" onclick="check();">
</td>
</tr>
<tr>
</table>
</form>
<div id="prikaz">
</div>
And your JS should be like this:
var correct =new Array();
function check() {
var email = document.getElementById("txtEmail").value;
var reEmail = /^(\w)+(\d)*(\.\_)*#[a-z]{2,10}\.[a-z]{2,5}$/;
if(email.match(reEmail)){
correct.push(email);
}
else {
alert("Not correct");
}
var correctEmails = "<table>";
for(var i=0; i< correct.length; i++){
correctEmails+=("<tr><td>"+correct[i]+"</td></tr>");
}
correctEmails+="</table>"
document.getElementById("prikaz").innerHTML = correctEmails;
}
You have no element with the id "prikaz" so getElementById is returning null.
And even if it did return something, I don't see the point of setting it's innerHTML to an array since that field is for text that will be parsed as HTML.

Javascript submit function returns Object is not a function error

Am using this function for the form submission just after one last check of 2 fields. But when submitting the form using javascript it returns the Object is not a function error. Didnt pasted the entire code of this page. pasted the required fields for this function. Any helps appreciated
<script type="text/javascript">
function validamt(strval){
var letters = /^[0-9]+(\.[0-9]{1,2})?$/;
if (letters.test(strval)) {
return true;
} else {
return false;
}
}
function validno(strval){
var letters = /^\d+$/;
if (letters.test(strval)) {
return true;
} else {
return false;
}
}
function finalcheck(){
var discount=$("#discount").val();
var stax=$("#stax").val();
var err=0;
if(discount!="In Rupees only" || stax!="(%)"){
if(!validno(stax)){err=1; alert('Invalid Service Tax');$("#stax").focus();}
if(!validamt(discount)){err=1;alert('Invalid Discount Amount');$("#discount").focus();}
}
alert(err);
if(err==0){
try{
document.getElementById('billsetupprocess').action="storebilling.php";
document.getElementById('billsetupprocess').submit();
}
catch(e){
alert(e);
}
}
}
</script>
<form name="billsetupprocess" id="billsetupprocess" method="post" action="storebilling.php" enctype="multipart/form-data" >
<table>
<tr>
<td>Discount</td>
<td><input name="discount" type="text" class="txtclass" id="discount" value="<?php if($discount!=""){echo $discount;} else {echo("In Rupees only");}?>" autocomplete="off" onfocus="Javascript:if(this.value=='In Rupees only'){this.style.color='rgb(193,193,193)';this.value='';}" onblur="Javascript:if(this.value==''){this.style.color='rgb(193,193,193)';this.value='In Rupees only';}" onkeyup="Javascript:if(this.value!=''){this.style.color='rgb(0,133,189)';}"/></td>
<td></td>
<td> </td>
</tr>
<tr>
<td>servicetax</td>
<td><input name="stax" type="text" class="txtclass" id="stax" value="<?php if($discount!=""){echo $servicetax;}else {echo("(%)");}?>" autocomplete="off" onfocus="Javascript:if(this.value=='(%)'){this.style.color='rgb(193,193,193)';this.value='';}" onblur="Javascript:if(this.value==''){this.style.color='rgb(193,193,193)';this.value='(%)';}" onkeyup="Javascript:if(this.value!=''){this.style.color='rgb(0,133,189)';}"/>
</td>
<td></td>
<td> </td>
</tr>
<tr>
<td> </td>
<td><input name="submit" id="submit" type="button" value="Save Setup" onclick="finalcheck()" class="btnclass" /></td>
<td> </td>
<td> </td>
</tr>
</table>

JavaScript checking & adding text to a table dynamically on submit button click

Basically my HTML looks like this:
<form method="post" name="htmlform" onsubmit = "checkFields()">
<table style="width: 479px;" border="30" cellspacing="3" cellpadding="10">
<tbody>
<tr>
<td valign="top"><span id="firstNameSpan" >First Name *</span></td>
<td valign="top"><input type="text" name="first_name" id="first_name"
size="30" maxlength="50" /></td>
</tr>
<tr>
<td valign="top"><span id = "lastNameSpan" >Last Name *</span></td>
<td valign="top"><input type="text" name="last_name" size="30" maxlength="50"/>
/td>
</tr>
<tr>
<td style="text-align: center;" colspan="2"><input type="radio" name="sex"
value="male" /> Male <input type="radio" name="sex"
value="female" /> Female</td>
</tr>
<tr>
<td style="text-align: center;" colspan="2"><input type="submit" value="submit"
/></td>
</tr>
</tbody>
</table>
</form>
When the form is submitted, the onsubmit() event checks if first_name textfield is blank, if it is then the label or span to its left is appended to output "first name*" + " you must enter a first name" and similarly for last name and sex.
The problem is that the text in the table does not update with appendchild. When I enclosed the statement in an alert for debugging the message is appended then disappears.
The JavaScript code is below for the onsubmit = "checkFields()".
function checkFields() {
var firstName = document.getElementById("first_name").value;
var lastName = document.getElementById("last_name").value;
if (firstName == "") {
//<span style='color:red'> Please enter a first name </span>
var nameHint = " Please enter a first name";
var node = document.getElementById("firstNameSpan");
//alert(node.appendChild(document.createTextNode(nameHint)) );
//not working
node.appendChild(document.createTextNode(nameHint));
} if (lastName == "") {
//additional code
}
}
Thanks in advance, your help is much appreciated. Also are there any JavaScript debuggers?
Regards
David D
I believe your sample code is not working due to incorrect html. document.getElementById("last_name") will return undefined.
http://jsfiddle.net/5E6my/1/
Thanks all, Im getting the ropes of JFiddle the split screen is very useful although the error messages are not useful for debugging. Here is the completed code (1) HTML (2) JavaScript.
<form method="post" name="htmlform" onsubmit="return checkFields();">
<table style="width: 479px;" border="30" cellspacing="3" cellpadding="10">
<tbody>
<tr>
<td valign="top"><span id="firstNameSpan" >First Name *</span></td>
<td valign="top"><input type="text" name="first_name" id="first_name"
size="30" maxlength="50" /></td>
</tr>
<tr>
<td valign="top"><span id = "lastNameSpan" >Last Name *</span></td>
<td valign="top"><input type="text" name="last_name" id="last_name" size="30"
maxlength="50" /></td>
</tr>
<tr>
<td style="text-align: center;" colspan="2" id = "sexMessage">
Please select Male or Female*</td>
</tr>
<tr>
<td style="text-align: center;" colspan="2"><input type="radio"
name="sex" value="male" /> Male <input type="radio" name="sex"
value="female" /> Female</td>
</tr>
<tr>
<td style="text-align: center;" colspan="2"><input type="submit" value="submit"
/></td>
</tr>
</tbody>
</table>
</form>
The JavaScript code to react to the onsubmit button's unfilled fields in the form are: (any ways to make this code simpler??)
window.checkFields = function()
{
var firstName = document.getElementById("first_name");
var lastName = document.getElementById("last_name");
if(firstName.value == "")
{
//<span style='color:red'> Please enter a first name </span>
var nameHint = " *Please enter a first name ";
var fnNode = document.getElementById("firstNameSpan");
while(fnNode.firstChild)
{
fnNode.removeChild(fnNode.firstChild)
}
fnNode.appendChild(document.createTextNode(nameHint));
fnNode.style.color="red";
} else{
var nameHint = " First Name *";
var fnNode = document.getElementById("firstNameSpan");
while(fnNode.firstChild)
{
fnNode.removeChild(fnNode.firstChild)
}
fnNode.appendChild(document.createTextNode(nameHint));
fnNode.style.color="black";
}
if (lastName.value == "")
{
//additional code
var nameHint = " *Please enter a last name";
var lnNode = document.getElementById("lastNameSpan");
while(lnNode.firstChild)
{
lnNode.removeChild(lnNode.firstChild)
}
lnNode.appendChild(document.createTextNode(nameHint));
lnNode.style.color="red";
} else{
var nameHint = " Last Name *";
var lnNode = document.getElementById("lastNameSpan");
while(lnNode.firstChild)
{
lnNode.removeChild(lnNode.firstChild)
}
lnNode.appendChild(document.createTextNode(nameHint));
lnNode.style.color="black";
}
var radios = document.getElementsByName("sex");
var radioValue = ""
for(var i=0; i<radios.length; i++)
{
if(radios[i].checked)
{
radioValue = radios[i].value;
}
}
if(radioValue === "")
{
var sexNode = document.getElementById("sexMessage");
var nameHint = "*You did not choose a sex";
while(sexNode.firstChild)
{
sexNode.removeChild(sexNode.firstChild);
}
sexNode.appendChild(document.createTextNode(nameHint));
sexNode.style.color="red";
} else {
var sexNode = document.getElementById("sexMessage");
var nameHint = "Please select Male or Female*";
while(sexNode.firstChild)
{
sexNode.removeChild(sexNode.firstChild);
}
sexNode.appendChild(document.createTextNode(nameHint));
sexNode.style.color="black";
}
return false;
}
The trick is to use as Yury suggested was the onsubmit="return checkfields()" and then in the code block to use window.checkFields = function() { etc.
One question that I have... is JQuery a lot simpler to use, im learning JavaScript before JQuery... should I skip to JQUery instead. Also does JQuery support the AJAX framework?
Much appreciated
David

Form "submit" working in IE but not Firefox and Chrome

I have a sign up form on my site which works OK in IE but does not work in Firefox or Chrome. I have tried looking through other forum posts here with similar problems but still can't get my head round this silly problem. (I am not a code writer).
Here is the code
<script type="text/JavaScript">
function validate_form(){
{validation_text}
else{
return true;
}
}
var str_vars = '';
function all_fields(){
str_vars = '';
el = document.form1;
for (var i = 0; i < el.elements.length; i++) {
if (el.elements[i].value != '')
str_vars += el.elements[i].name+'='+el.elements[i].value+'&';
}
str_vars = str_vars.substr(0,str_vars.length-15);;
}
</script>
<div id="div_form" name="div_form">
<form id="form1" name="formx" method="{send_method}" action="{form_switch}">
<p> </p>
<table border="0" width="100%" style="border-collapse: collapse" bordercolor="#111111" cellpadding="0" cellspacing="0">
{error}
{signup_list}
<tr>
<td align="right">{description_country} </td>
<td>{shiping_country_list}{required_country}</td>
</tr>
<tr><td align="right"> {promo}</td></tr>
{code_signup}
<tr>
<td colspan="2"><div align="center">
<input name="terms" id="terms" value="1" type="checkbox">
<label for="terms">I accept the terms & conditions</label>
</div></td>
</tr>
<tr>
<td colspan="2"><div align="center">
{captcha}</td>
</tr>
{arp_fields}
<tr>
<td><div align="right">*</div><br></td>
<td width="332">Denotes required</td>
</tr>
<tr>
<td>
<div align="right">
<input name="Submit" value="Submit" type="button" onclick="{request}{request_email}{form2items}">
</div></td>
<td> <br></td>
</tr>
</table>
</form>
</div>
</div>
Any help would be appreciated.
Maybe instead of
el = document.form1;
try
el = document.getElementById('form1');
I can't see all the JS so it is hard to guess, but one other thing to try is to change the name of the submit button from name="Submit" to something else like name="submitForm". If form.submit() is getting called somewhere in the script this can cause problems.
Your validate function should look something like this:
function validate_form(){
var form = document.getElementById('form1');
err = 'The following fields are not correct filled:\n';
if (form.first_name.value == ''){
err += 'No First Name.\n';
}
if (emailCheck(form.email.value) == false){
err += 'No Valid email.\n';
}
if (form.terms.checked != true){
err += 'You did not agree with the terms.\n';
}
if (err != 'The following fields are not correct filled:\n'){
alert (err);
return false;
}
else{
return true;
}
}
Lastly, change your submit button to this:
<input name="Submit" value="Submit" type="button" onclick="if (validate_form()) document.getElementById('form1').submit();">

Duplicate Forms with Jquery

i found on the Internet a plugin and add some new lines to form this:
(function($){
$countForms = 1;
$countFormsA = 1;
$.fn.addForms = function(idform){
var myform = "<table>"+
" <tr>"+
" <td>Field A ("+$countForms+"):</td>"+
" <td><input type='text' name='fielda["+$countForms+"]'></td>"+
" <td>Field B ("+$countForms+"):</td>"+
" <td><textarea name='fieldb["+$countForms+"]'></textarea></td>"+
" <td><button>remove</button></td>"+
" </tr>"+
"</table>";
var myform2 = "<table>"+
" <tr>"+
" <td>Field C</td>"+
" <td><input type='text' name='fieldc["+$countFormsA+"]'></td>"+
" <td>Field D ("+$countFormsA+"):</td>"+
" <td><textarea name='fieldd["+$countFormsA+"]'></textarea></td>"+
" <td><button>remove</button></td>"+
" </tr>"+
"</table>";
if(idform=='mybutton'){
alert(idform);
myform = $("<div>"+myform+"</div>");
$("button", $(myform)).click(function(){ $(this).parent().parent().remove(); });
$(this).append(myform);
$countForms++;
}
else{
if(idform=='mybutton1'){
alert(idform);
myform2 = $("<div>"+myform2+"</div>");
$("button", $(myform2)).click(function(){ $(this).parent().parent().remove(); });
$(this).append(myform2);
$countFormsA++;
}
}
};
})(jQuery);
$(function(){
$("#mybutton1").bind("click", function(){
var idform=this.id;
if($countFormsA<3){
$("#container1").addForms(idform);
}
});
});
$(function(){
$("#mybutton").bind("click", function(){
var idform=this.id;
if($countForms<3){
$("#container").addForms(idform);
}
});
});
However i'm having a problem. If i click "add form" everything works, but when i click "add form 1" the new form is added but after 1 second it disappears. Any hint how can i solve this? Thank you!
The html code:
<button id="mybutton">add form</button>
<div id="container"><div>
<form method="post" name="b" >
<table>
<tr>
<td>Field A</td>
<td><input type='text' name='dadoA'></td>
<td>Field B</td>
<td><textarea name="dadoB"></textarea></td>
<td><button>remove</button></td>
</tr>
</table></div></div>
<div align="center">
<p><input type="submit" value="Registar" name="registar"></p>
</div>
<!-- -->
<button id="mybutton1">add form1</button>
<div id="container1"><div>
<form method="post" name="a" >
<table>
<tr>
<td>Field A</td>
<td><input type='text' name='dadoA'></td>
<td>Field B</td>
<td><textarea name="dadoB"></textarea></td>
<td><button>remove</button></td>
</tr>
</table></div></div>
<div align="center">
<p><input type="submit" value="Registar1" name="registar1"></p>
</div>
The form will disappear because the page is being refreshed by that button's default behaviour.
You will need to prevent that behaviour in your click binding. I would suggest passing the event object through and using preventDefault() ie:
$("#mybutton1").bind("click", function(e){
e.preventDefault();
var idform=this.id;
if($countFormsA<3){
$("#container1").addForms(idform);
}
});

Categories

Resources