I need to do a very basic form validation, and my method of choice is jQuery. However, for some reason, the validation function seems not to get fired at all.
After looking at this for several hours I can't find out what the problem is.
HTML:
<form id="form1" name="form1" method="post" action="process.php">
<table width="100%" border="0" cellspacing="5" cellpadding="0">
<tr>
<td width="160">Meno:</td>
<td><input type="text" name="meno" id="meno" /></td>
<td width="160">Priezvisko:</td>
<td><input type="text" name="priezvisko" id="priezvisko" /></td>
</tr>
<tr>
<td width="160">Názov spolocnosti: <br />
<span class="register_comment">(nevyplnajte ak nie ste podnikatel)</span></td>
<td><input type="text" name="spolocnost" id="spolocnost" /></td>
<td width="160">Krajina:</td>
<td><select name="krajina" id="krajina">
<option value="" selected="selected"> </option>
<option value="cz">Ceská republika</option>
<option value="sk">Slovenská republika</option>
</select></td>
</tr>
<tr>
<td width="160">Adresa:</td>
<td><input type="text" name="adresa" id="adresa" /></td>
<td width="160">Mesto:</td>
<td><input type="text" name="mesto" id="mesto" /></td>
</tr>
<tr>
<td width="160">Email:<br />
<span class="register_comment">(na tento email Vám príde potvrdenie)</span></td>
<td><input type="text" name="email" id="email" /></td>
<td width="160">Telefonický kontakt:<br />
<span class="register_comment">(uvádzajte kontakt na mobilný telefón na ktorom budete zastihnutelní najmä 10.10.!)</span></td>
<td><input type="text" name="telefon" id="telefon" /></td>
</tr>
<tr>
<td width="160">Miesto nástupu: </td>
<td colspan="3"><select name="nastup" id="nastup">
<option value="" selected="selected"> </option>
<option value="nr">Nitra</option>
<option value="ba">Bratislava</option>
<option value="br">Brno - Avion Shopping Park, Škandinávská 128/2</option>
<option value="ph">Praha - Avion Shopping Park, Škandinávská 15/A</option>
<option value="pl">Plzen - OC Olympia, Písecká 972/1</option>
</select></td>
</tr>
<tr>
<td colspan="4"><p>
<label>
<input type="checkbox" name="suhlas" value="checkbox" id="suhlas" />
Oboznámil som sa s podmienkami úcasti a Súhlasím s podmienkami úcasti </label>
FLEX Polishing Camp<br />
</p></td>
</tr>
<tr>
<td colspan="4" align="center"><input type="submit" id="button" value="Odoslat záväznú prihlášku na FLEX Polishing Camp" style="width:500px;" /></td>
</tr>
<tr>
<td colspan="4" class="register_comment">xxxx</td>
</tr>
</table>
</form>
jQuery:
<script>
$("#form1").submit(function() {
var errors = new array();
if ($('input[name=meno]').val() == "") {
errors.push('Meno je povinná položka.');
}
if ($('input[name=priezvisko]').val() == "") {
errors.push('Priezvisko je povinná položka.');
}
if ($('input[name=krajina]').val() == "") {
errors.push('Je nutné vybrať si krajinu - ČR alebo SR.');
}
if ($('input[name=adresa]').val() == "") {
errors.push('Adresa je povinná položka.');
}
if ($('input[name=mesto]').val() == "") {
errors.push('Mesto je povinná položka.');
}
if ($('input[name=email]').val() == "") {
errors.push('Email je povinná položka.');
}
if ($('input[name=telefon]').val() == "") {
errors.push('Telefonický kontakt je povinná položka.');
}
if ($('input[name=nastup]').val() == "") {
errors.push('Telefonický kontakt je povinná položka.');
}
if (!$('#suhlas').attr('checked')) {
errors.push('Je potrebné vysloviť súhlas s podmienkami zaškrtnutím tlačítka "Oboznámil som sa s podmienkami účasti a Súhlasím s podmienkami účasti FLEX Polishing Camp".');
}
if ( errors.lenght > 0 )
{
var text;
for (var i = 0; i < errors.length; i++) {
text = text + errors[i] + '\n';
};
alert(text);
return false;
}
return true;
});
</script>
$("form1") should be $("#form1")
As other mention you have missed the # for your ID selector, you can also use map method and minify your code.
$("#form1").submit(function() {
var errors = [];
errors = $('input[type=text]', this).filter(function(){
return $.trim(this.value) == "";
}).map(function() {
return this.name + ' je povinná položka.';
}).get();
if (errors.length) {
var text = errors.join('\n');
alert(text);
return false;
}
});
http://jsfiddle.net/bwVWQ/
First $("form1") should be $("#form1")
//Secondly
text = text + arr[i] + '\n';
//Should be
text = text + errors[i] + '\n'; OR text += errors[i] + '\n';
Looks like the Updated code has again a typo in it..
This might be preventing it
if ( errors.lenght > 0 ) // Supposed to be errors.length
You are missing the # sign on your selector, #form1
$("#form1").submit(function() {
Related
I have read this post but still have some questions. I am getting the error:
Uncaught TypeError: Cannot read property 'value' of null
On this line:
fullname = document.getElementById('namefull').value;
I am 100% sure that the field 'namefull' is on the form and I also have a value typed in the form. I actually have a check to make sure it's not null and that passes. Here is form:
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td align="center" colspan="5" bgcolor="#CCFFFF"><b><font face = "Calibri">All Fields Required so we can contact you</b></td>
</tr>
<tr>
<td align="right" colspan="2" bgcolor="#CCFFFF"><b><font face = "Calibri">Name:</b></td>
<td colspan="3" bgcolor="#CCFFFF"><input type="text"
size="30" maxlength="30" name="namefull"></td>
</tr>
The full code is below:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<meta name="GENERATOR" content="Microsoft FrontPage 2.0">
<title>HABLA Order Form</title>
</head>
<script language="javascript">
// Do not steal, modify, or claim these scripts as your own! Thank You.
// Alterations and additions by Gordon Smith Mearns#mearns.org.uk
index = 0;
function getFields() {
fullname = document.getElementById('namefull').value;
email = document.getElementById('email').value;
phone = document.getElementById('phone').value;
zip = document.getElementById('zip').value;
amount = document.getElementById('total').value;
type = document.getElementById('order_type').value;
seller = 'TestSeller';
specinstruct = document.getElementById('specinstr').value;
xact_num = 'StripeDummy';
};
function writeXact() {
var sendtext;
getFields();
if (fullname == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
sendtext = fullname + "||" + email + "||" + phone + "||" + zip +
"||" + amount + "||" + type + "||" + seller + "||" + specinstruct +
"||" + xact_num;
xmlhttp.open("GET","writeXact.php?q="+sendtext,true);
xmlhttp.send();
}
};
function format(val, post)
{
var decpoint;
var begin;
var end;
var valstr;
var temp_char;
valstr = "" + val;
//alert('valstr = ' + valstr);
decpoint = valstr.indexOf(".")
if (decpoint != -1) {
//alert('decpoint = ' + decpoint);
begin = valstr.substring(0,decpoint);
end = valstr.substring(decpoint+1,valstr.length);
//alert('begin = ' + begin + '\nend= ' + end);
}
else {
begin = valstr;
end = "";
}
if (end.length < post)
{while (end.length < post)
{
end += "0";
}
}
end = end.substring(0,post);
//alert('begin = ' + begin + '\nend= ' + end);
return (begin+"."+end);
};
function orderSubmit(type)
{
if (type == 'order')
{if ( ! ( (document.order.order_type.checked) ||
checkRequired() ))
{document.order.form_action.value = type;
getFields();
writeXact(fullname, email, phone, zip, amount, type, seller, specinstruct, xact_num);
document.order.submit();
return true;
}
else {
// alert('first false');
return false;
}
}
};
var infowin = null;
function checkRequired() {
if (!document.order.namefull.value.length ||
!document.order.email.value.length ||
!document.order.zip.value.length ||
!document.order.phone.value.length) {
alert('You have not completed all required fields:\n' +
'Please enter Name, Email, Phone, Zip');
return true;
}
else {
return false;
}
};
<!-- -->
</script><!-- --><a name="top"></a>
<body background="images/thisback.gif" bgcolor="#FFFFFF"
text="#000000" onLoad=parent.refresh_order_details(parent.order_details) onUnload=parent.add_order_details(parent.order_details)>
<center>
<script
language="javascript">
<!-- hide
if (self==parent){document.write('<font color=#ff000><b>This is a frame element, click <a href=shopcartindex.html> here </a>for correct page</b></font>')};
<!-- end hide -->
</script>
<p><size="6" color="black" font face="Calibri"><b>HABLA Event Order Form</b><br>
</font></p>
<!-- YOU CAN PUT YOUR EMAIL ADDRESS IN THE FORM COMMAND BELOW AND THE -->
<!-- THEN IT WILL BE SENT TO YOU AS A SIMPLE MAILTO GUESTBOOK FORM -->
<!-- IF YOU DO THAT - BE SURE TO ADD THE COMMAND enctype="plain/text" -->
<!-- IN ORDER TO DELINEATE THE MAIL FOR YOU -->
<!-- YOU CAN ALSO USE TE .PL FILE AS A CGI TO HELP WTH THE MAIL. SEE THE TUTORIAL -->
<!-- FOR MORE ON HOW THAT IS DONE -->
<form action="MAILTO:hablariverglen#gmail.com" method="POST" name="order">
<input type="hidden" name="subject"
value="Order Forms - HABLA Balie 2015"><input type="hidden"
name="recipient" value="YOUR EMAIL ADDRESS HERE"><input
type="hidden" name="redirect"
value="thanku.htm"><input
type="hidden" name="retailer" value="NAME OF YOUR BUSINESS HERE"><input
type="hidden" name="form_action" value="order">
<script
language="javascript">
<!-- hide from Browsers
document.write('<table width=400><td align=center>');
document.write('<table width=400 ><tr><tr><td align=right colspan=3 ><font face="Calibri"><b>Total Purchase $</b></td><td colspan=3> <input type=text name=total font face="Calibri" value='+ format(parent.all_order_totals(),2) + '></font></td><tr>');
if (parent.items_ordered == 0)
document.write('<font color=#000080><b>There are no items in your cart<b></font>');
if (parent.item_num > 0);
{
for (i =1;i < parent.item_num;i++)
{ if (parent.itemlist[i].quan > 0)
{index = index + 1;
document.write('<input size=10 type=text font face="Calibri" name= ' + parent.itemlist[i].code + ' value= ' + parent.itemlist[i].code + '><input size=6 type=text name= ' + parent.itemlist[i].code + ' value=' + parent.itemlist[i].price + '><input size=20 type=text name= ' + parent.itemlist[i].code + ' value= '+ parent.itemlist[i].desc + '><input size=2 type=text name= ' + parent.itemlist[i].desc + ' value= '+ parent.itemlist[i].quan + '><br>');
}
}
};
<!-- end hiding -->
</script>
<!-- Customer Info Table -->
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td align="center" colspan="5" bgcolor="#CCFFFF"><b><font face = "Calibri">All Fields Required so we can contact you</b></td>
</tr>
<tr>
<td align="right" colspan="2" bgcolor="#CCFFFF"><b><font face = "Calibri">Name:</b></td>
<td colspan="3" bgcolor="#CCFFFF"><input type="text"
size="30" maxlength="30" name="namefull"></td>
</tr>
<tr>
<td align="right" colspan="2" bgcolor="#CCFFFF"><b><font face = "Calibri">Email Address:</b></td>
<td colspan="3" bgcolor="#CCFFFF"><input type="text"
size="30" maxlength="60" name="email"></td>
</tr>
<tr>
<td align="right" colspan="2" bgcolor="#CCFFFF"><b><font face = "Calibri">Zip:</b></td>
<td bgcolor="#CCFFFF"><input type="text" size="9"
maxlength="10" name="zip"></td>
</tr>
<tr>
<td align="right" colspan="2" bgcolor="#CCFFFF"><b><font face = "Calibri">Phone:</b></td>
<td colspan="3" bgcolor="#CCFFFF"><input type="text"
size="25" maxlength="15" name="phone"></td>
</tr>
</table>
<p align="center">
<table border="0" width=400>
<tr>
<td align="center" colspan="6"<b><font face = "Calibri"><b>Special Instructions</b><br></td>
</tr>
<tr>
<td colspan="6"><center><textarea name="specinstr" rows="3"
cols="40"></textarea></center></td>
</tr>
</table>
<!-- Order Method Table --> </p>
<table border="0" cellspacing="0" width=400>
<tr>
<td align="center" colspan="5" bgcolor="#CCFFFF"><font
size="4"><b>Choose Order Method:</b></font></td>
</tr>
<tr>
<td align="center" colspan="5" bgcolor="#CCFFFF">
<font size="2">Credit Card: <input type="radio"
name="order_type" value="phone"></font> </td>
</tr>
<tr>
<td align="center" colspan="5" bgcolor="#CCFFFF">
<font size="2">Cash: <input type="radio"
name="order_type" value="phone"></font> </td>
</tr>
<tr>
<td align="center" colspan="5" bgcolor="#CCFFFF">
<font size="2">Check: <input type="radio"
name="order_type" value="phone"></font> </td>
</tr>
<tr>
<td align="center" colspan="5" bgcolor="#CCFFFF"><a
href="options.htm" target=navigate>
</td>
</tr>
</table>
<p><br>
<p><br>
<! Stripe Credit Card Integration >
<form action="" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="pk_test_zzzzzz"
data-amount="2000"
data-name="Demo Site"
data-description="2 widgets ($20.00)"
data-image="/128x128.png"
data-locale="auto">
</script>
</form>
<input
type="button" value="Place Order"
onclick="orderSubmit('order')"
<input type="reset" value="Reset Cart"> </p>
<b>HABLA Friends of River Glen <a href=mailto:hablariverglen#gmail.com>hablariverglen#gmail.com</a> </b>
</form>
</td></table>
</center>
</p>
</body >
</html>
Yes, I know the code is a mess, but I'm doing this for a school/charity fundraiser, so any help is much appreciated.
You are looking for an element with id="namefull", but in your html, you only specify the name attribute: <input type="text" size="30" maxlength="30" name="namefull">
Try including id="namefull" in here:
<input type="text" id="namefull" name="namefull" size="30" maxlength="30">
You'll want to follow suit on each of your inputs to specify the id, since that's what you're looking for with document.getElementById().
getElementById() get's an element by it's ID. You need to set the id for that to work.
Change your markup to:
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td align="center" colspan="5" bgcolor="#CCFFFF"><b><font face = "Calibri">All Fields Required so we can contact you</b></td>
</tr>
<tr>
<td align="right" colspan="2" bgcolor="#CCFFFF"><b><font face = "Calibri">Name:</b></td>
<td colspan="3" bgcolor="#CCFFFF"><input type="text"
size="30" maxlength="30" name="namefull" id="namefull"></td>
</tr>
Notice I added id="namefull" to the input element.
Hi and sorry for my bad English
I have a contact page and i am using javascript to make a "captcha". so peaople must make a math and if thats correct they can send me a e-mail. Now my problem is that javasctipt give a alert that the math is wrong or not filled but the e-mail is still seended.
my html:
<script type="text/javascript">
function validate () {
var ta = document.getElementById("ta").value;
var answer = document.getElementById("answer").value;
var digit1 = parseInt(document.getElementById("digit1").innerHTML);
var digit2 = parseInt(document.getElementById("digit2").innerHTML);
var sum = digit1+ digit2;
if (answer === null || answer === "") {
alert("reken de cijfers uit");
return false;
} else if (answer != sum){
alert("je som is fout");
} else if (ta === null || ta === ""){
alert("schrijf een bericht");
} else {
document.getElementById("answer").innerHTML = "bezig met sturen";
document.getElementById("answer").innerHTML = "";
}
}
function randNums () {
var rand_num1 = Math.floor(Math.random()*10)+1;
var rand_num2 = Math.floor(Math.random()*10)+1;
document.getElementById("digit1") .innerHTML=rand_num1;
document.getElementById("digit2") .innerHTML=rand_num2;
}
</script>
<body onload="randNums() ;">
<form action="/cgi-bin/form.cgi" method="POST" onsubmit="return validate ();">
<input type="hidden" name="DEBUG" value="0">
<input type="hidden" name="MAILFILE" value="peymankarimi/form/sjabloon.txt">
<input type="hidden" name="MAILTO" value="peyman_50#hotmail.com">
<input type="hidden" name="REPLYFAULT" value="peymankarimi/form/formulier.html">
<input type="hidden" name="REPLYOK" value="peymankarimi/form/verzonden.html">
<table border="0" width="374" id="contactformulier">
<tr>
<td width="137">Naam:</td>
<td width="230"><input type="text" size="31" name="naam" placeholder="Naam"></td>
</tr>
<tr>
<td width="137">Voornaam:</td>
<td width="230"><input type="text" size="31" name="voornaam" placeholder="Voornaam"></td>
</tr>
<tr>
<td width="137">Woonplaats:</td>
<td width="230"><input type="text" size="31" name="woonplaats" placeholder="Woonplaats"></td>
</tr>
<tr>
<td width="137">Telefoonnummer:</td>
<td width="230"><input type="text" size="31" name="telefoon" placeholder="Telefoonnummer"> </td>
</tr>
<tr>
<td width="137">E-mailadres: <br></br></td>
<td width="230">
<input type="text" size="31" name="MAILFROM" placeholder="E-mailadres"> <br></br> </td>
</tr>
</tr>
<tr>
<td width="137">Onderwerp:</td>
<td width="230"><input type="text" size="31" maxlength="30" name="SUBJECT"> </td>
</tr>
<tr>
<td colspan="2">Uw vragen, opmerkingen, suggesties, ... :<br>
<textarea id="ta" name="omschrijving" rows="6" cols="43" ></textarea>
<br />
<strong> Tel deze cijfers op </strong>
<span id="digit1"> </span> +
<span id="digit2"> </span> =
<input type="text" id="answer" size="2"; />
<br />
<p align="right"><input type="submit" name="cmdVerzenden" value="Verzenden">
<input type="reset" name="cmdWissen" value="Wissen"></td>
</form>
</tr>
</table>
</form>
</body>
Your validate function needs to return false on all errors to stop the form from submitting. You only seem to have it for one error.
function validate () {
var ta = document.getElementById("ta").value;
var answer = document.getElementById("answer").value;
var digit1 = parseInt(document.getElementById("digit1").innerHTML);
var digit2 = parseInt(document.getElementById("digit2").innerHTML);
var sum = digit1+ digit2;
if (answer === null || answer === "") {
alert("reken de cijfers uit");
return false;
} else if (answer != sum){
alert("je som is fout");
return false;
} else if (ta === null || ta === ""){
alert("schrijf een bericht");
return false;
} else {
document.getElementById("answer").innerHTML = "bezig met sturen";
document.getElementById("answer").innerHTML = "";
}
}
I m trying to write on a txt file from a form... the idea is that the user press the register button and that will save on a txt file and go back to the index page.
This is my php file:
<?php
if(!empty($_POST)){
$rut = $_POST['rut'];
$dv = $_POST['dv'];
$pnom = $_POST['pnom'];
$snom = $_POST['snom'];
$pape = $_POST['pape'];
$mape = $_POST['mape'];
$sex = $_POST['sex'];
$dir = $_POST['dir'];
$comu = $_POST['comu'];
$pais = $_POST['pais'];
$fono = $_POST['fono'];
$movil = $_POST['movil'];
$mail = $_POST['mail'];
$user = $_POST['user'];
$pass = $_POST['pass'];
$rpas = $_POST['rpas'];
$usuarios = fopen("usuarios.txt", "a");
fwrite($usuarios, $rut);
fwrite($usuarios,$dv,";");
fwrite($usuarios,$pnom,";");
fwrite($usuarios,$snom,";");
fwrite($usuarios,$pape,";");
fwrite($usuarios,$mape,";");
fwrite($usuarios,$sex,";");
fwrite($usuarios,$dir,";");
fwrite($usuarios,$comu,";");
fwrite($usuarios,$pais,";");
fwrite($usuarios,$fono,";");
fwrite($usuarios,$movil,";");
fwrite($usuarios,$mail,";");
fwrite($usuarios,$user,";");
fwrite($usuarios,$pass,";");
fwrite($usuarios,$rpas,"\r\n");
fclose($usuarios);
}
?>
And this is the form html file:
<html>
<head>
<title>E1Formulario</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="diseno/diseno.css">
</head>
<script language="JavaScript" src="funciones.js"></script>
<body>
<form name="formulario" action="generar_txt.php" method="POST">
<table border="2" align="center" width="50%">
<th colspan="2">FORMULARIO DE INGRESO</th>
<tr>
<td align="left">
Rut:<input name="rut" type="text" size="8">
<select name="dv">
<option value = 0>0</option>
<option value = 1>1</option>
<option value = 2>2</option>
<option value = 3>3</option>
<option value = 4>4</option>
<option value = 5>5</option>
<option value = 6>6</option>
<option value = 7>7</option>
<option value = 8>8</option>
<option value = 9>9</option>
<option value = K>K</option>
</select>
<br><label name="lrut" style="color:#cc0000">*(Campo Obligatorio)</label>
</td>
<td align="left">Primer Nombre:* <input name="pnom" type="text"><br><label style="color:#cc0000">*(Campo Obligatorio)</label></td>
</tr>
<tr>
<td align="left">Segundo Nombre: <input name="snom" type="text"></td>
<td align="left">Apellido Paterno: <input name="pape" type="text"><br><label style="color:#cc0000">*(Campo Obligatorio)</label></td>
</tr>
<tr>
<td align="left">Apellido Materno: <input name="mape" type="text"></td>
<td align="left">
Sexo<br>
Masculino <input name="sex" type="radio" value="Masculino"><br>
Femenino <input name="sex" type="radio" value="Femenino">
<br><label style="color:#cc0000">*(Campo Obligatorio)</label>
</td>
</tr>
<tr>
<td align="left">Dirección: <input name="dir" type="text" size="50"><br><label style="color:#cc0000">*(Campo Obligatorio)</label></td>
<td align="left">Comuna: <input name="comu" type="text"><br><label style="color:#cc0000">*(Campo Obligatorio)</label></td>
</tr>
<tr>
<td align="left">País: <input name="pais" type="text" size="15"><br><label style="color:#cc0000">*(Campo Obligatorio)</label></td>
<td align="left">Teléfono: <input name="fono" type="text" size="9" onkeypress="JavaScript: return isNumber(event);"><br><label style="color:#cc0000">*(Campo Obligatorio)</label></td>
</tr>
<tr>
<td align="left">Movil: <input name="movil" type="text" onkeypress="JavaScript: return isNumber(event);"><br><label style="color:#cc0000">*(Campo Obligatorio)</label></td>
<td align="left">Email: <input name="mail" type="text" size="25"><br><label style="color:#cc0000">*(Campo Obligatorio)</label></td>
</tr>
<tr>
<td align="left">Usuario: <input name="user" type="text"><br><label style="color:#cc0000">*(Campo Obligatorio)</label></td>
<td align="left">Contraseña: <input name="pass" type="password"><br><label style="color:#cc0000">*(Campo Obligatorio)</label></td>
</tr>
<tr>
<td align="left" colspan="2">Repetir Contraseña: <input name="rpas" type="password" size="9"><br><label style="color:#cc0000">*(Campo Obligatorio)</label></td>
</tr>
<tr>
<td colspan="2" align="center">
<input class="boton" name="reg" type="button" value="REGISTRAR" onclick="JavaScript: verificar_datos();"/>
</td>
</tr>
</table>
</form>
</body>
This is the function that submit the form to the php file and then goes to the index html file:
function verificar_datos(){
var f = document.formulario;
//Validar que el usuario ingrese todos los campos obligatorios
if(f.rut.value === ""){
alert("El Rut es un campo obligatorio!");
f.rut.focus();
return 0;
}
if(revisarRut(f.rut.value.concat(f.dv.value)) === 0){
return 0;
}
if(f.pnom.value === ""){
alert("El Nombre es un campo obligatorio!");
f.pnom.focus();
return 0;
}
if(f.pape.value === ""){
alert("El Apellido Paterno es un campo obligatorio!");
f.pape.focus();
return 0;
}
if(f.sex.value === ""){
alert("El Sexo es un campo obligatorio!");
f.sex.focus();
return 0;
}
if(f.dir.value === ""){
alert("La Dirección es un campo obligatorio!");
f.dir.focus();
return 0;
}
if(f.comu.value === ""){
alert("La Comuna es un campo obligatorio!");
f.comu.focus();
return 0;
}
if(f.pais.value === ""){
alert("El País es un campo obligatorio!");
f.pais.focus();
return 0;
}
if(revisarTelefonos() === 0){
return 0;
}
if(verificarEmail() === 0){
return 0;
}
if(f.user.value === ""){
alert("Favor ingresar su Usuario");
f.user.focus();
return 0;
}
if(f.pass.value === ""){
alert("Favor Ingrese su Contraseña");
f.pass.focus();
return 0;
}
if(f.rpas.value === ""){
alert("Favor repetir su contraseña en el campo repetir");
f.rpas.focus();
return 0;
}
if(f.rpas.value !== f.pass.value){
alert("La Segunda Contraseña no concuerda");
f.rpas.value = "";
f.rpas.focus();
return 0;
}
f.submit();
alert("DATOS DE USUARIO INGRESADOS EXITOSAMENTE");
window.location= 'index.html';
}
I would be happy if someone could lead me because i think i have everything correct but i still dont get the php to write on txt file.
First, add the follow line, to begin of your PHP File
error_reporting(E_ALL);
Now, change the next line:
$usuarios = fopen("usuarios.txt", "a");
To:
$usuarios = fopen("usuarios.txt", "a+");
The a+ will create a file if not exists.
And, verify if the file is opened.
$usuarios = fopen("usuarios.txt", "a+");
if (!$usuarios) {
die("Could not open file");
} else {
fwrite($usuarios, $rut);
fwrite($usuarios,$dv,";");
fwrite($usuarios,$pnom,";");
fwrite($usuarios,$snom,";");
fwrite($usuarios,$pape,";");
fwrite($usuarios,$mape,";");
fwrite($usuarios,$sex,";");
fwrite($usuarios,$dir,";");
fwrite($usuarios,$comu,";");
fwrite($usuarios,$pais,";");
fwrite($usuarios,$fono,";");
fwrite($usuarios,$movil,";");
fwrite($usuarios,$mail,";");
fwrite($usuarios,$user,";");
fwrite($usuarios,$pass,";");
fwrite($usuarios,$rpas,"\r\n");
fclose($usuarios);
}
Now, everything will work as expected.
Also you should check the file "usuarios.txt" is writable from your webserver user at system like apache or www-user etc. simply check the chmod of the file and the directory
I would like to run a for loop that will insert a word in a text box from a table; then insert a new word in a text box right after that.
However i only get one word when i click submit is there a way to do this without ajax?
function check()
{
var myrows = new Array();
myrows[0] = "row1";
myrows[1] = "row2";
var server =" ";
var root = " ";
for (var i=0;i<myrows.length;i++){
root = myrows[i]+ "rootname";
server = myrows[i]+ "servername";
var j = document.getElementById(root);
var y = document.getElementById(server);
document.getElementById('id_rootname').value=j.textContent;
document.getElementById('id_servername').value=y.textContent;
}
var x;
var r=confirm("Are you sure you?" );
if (r==true)
{
x="You pressed OK!";
}
else
{
Object.cancel;
}
}
</script>
<tr >
<td align="center"><input type="checkbox" class="selectedId"
onclick="resetSelectedAll(this);" id= "check" value="row1" name="row{{ forloop.counter }" ></td>
<td name = "root" id="row1rootname">appBOWSERtest033</td>
<td style="display:none;" name = "server" id="row1servername">Bowser</td>
<td name= "url" id="row1urls">21</td>
<td id="row1custs">3</td>
<td id="row1jvmms"> 1024</td>
<td id="row1x64">1</td>
<td id="row1currentplatform"> platform_11.3.111129.38873</td>
<td id="row1currentjdk"> jdk_1.6.0_26-b03</td>
<td id="row1currenttomcat">tomcat_6.0.32</td>
</tr>
<tr >
<td align="center"><input type="checkbox" class="selectedId"
onclick="resetSelectedAll(this);" id= "check" value="row2" name="row{{ forloop.counter }" ></td>
<td name = "root" id="row2rootname">appLUIGItest033</td>
<td style="display:none;" name = "server" id="row2servername">LUIGI</td>
<td name= "url" id="row2urls">12</td>
<td id="row2custs">3</td>
<td id="row2jvmms"> 1024</td>
<td id="row2x64">0</td>
<td id="row2currentplatform"> platform_12.1.120510.42747</td>
<td id="row2currentjdk"> jdk_1.6.0_31-b04</td>
<td id="row2currenttomcat">tomcat_7.0.27</td>
</tr>
<form action=" " id ="forms" name = "forms" >{% csrf_token %}
<table>
<tr><th><label for="id_servername">Servername:</label></th><td><input id="id_servername" maxlength="50" name="servername" type="text" value="LUIGI" /></td></tr>
<tr><th><label for="id_rootname">Rootname:</label></th><td><input id="id_rootname" maxlength="50" name="rootname" type="text" value="appLUIGItest033" /></td></tr>
<tr><th><label for="id_action">Action:</label></th><td><select id="id_action" name="action">
<option value="Restart" selected="selected">Restart</option>
<option value="Full_Dump">Full_Dump</option>
<option value="Redeploy">Redeploy</option>
<option value="Thread">Thread</option>
</select></td></tr>
<tr><th><label for="id_loginname">Loginname:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input id="id_loginname" maxlength="50" name="loginname" type="text" /></td></tr>
<tr><th><label for="id_choice">Choice:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input id="id_choice" name="choice" type="checkbox" /></td></tr>
</table>
<input name = "hello" type="submit" onclick="check()" value="Submit">
</form>
root = myrows[i]+ "rootname";
server = myrows[i]+ "servername";
var j = document.getElementById(root);
var y = document.getElementById(server);
instead of this try this one.
start var i = 1 in for loop.
var j= document.getElementById("row"+i+"rootname");
I am trying to get this script to work, but it is failing somewhere in the last alert. The script is supposed to pull everything from a form, and then spit out the results as an alert box. I'm pretty sure my html is correct.
function calcServiceTotal() {
var animalName = document.getElementById("name").value;
var ownerName = document.getElementById("owner").value;
var currentDate = document.getElementById("date").value;
var choosenService = document.getElementById("service");
var serviceName = choosenService.options[choosenService.selectedIndex].text;
var serviceCost = document.getElementById("value").value;
var taxCost = serviceCost * 0.07;
var totalCost = serviceCost + taxCost;
if (animalName == null || animalName == "")
{
alert("Please give us your pet's name.");
return false;
}
else if (ownerName == null || ownerName == "")
{
alert("Please give us your name.");
return false;
}
else if (currentDate== null || currentDate == "")
{
alert("Please give us a date.");
return false;
}
else
{
alert("Pet's Name:" + animalName + '\n' + "Owner's Name:" + ownerName + '\n' + "Service:" + choosenService + '\n' + "Cost: $" + serviceCost.toFixed(2) + '\n' + "Tax: $" + taxCost.toFixed(2) + "Total Cost:" + totalCost.toFixed(2));
}
}
Here is the relevant html code.
<table width="339" border="0">
<tr>
<td width="329"><strong>Patient Information</strong></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>Name:
<label for="textfield"></label> <input type="text" name="textfield" id="name" /></td>
</tr>
<tr>
<td>Owner:
<input type="text" name="textfield2" id="owner" /></td>
</tr>
<tr>
<td>Date:
<input type="text" name="textfield3" id="date" /></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td><strong>Services</strong></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td><form id="form1" name="form1" method="post">
Select a Service:
<label for="select"></label>
<select name="select" id="service">
<option>Basic Appointment - $50</option>
<option>Extended Appointment - $75</option>
<option>Vacination - $25</option>
<option>Grooming - $35</option>
<option>Bathing - $35</option>
</select>
</form></td>
</tr>
<tr>
<td>Service Fee (from above):
<label for="textfield4"></label>
<input type="text" name="textfield4" id="value" />
</td>
</tr>
<tr>
<td><form id="form2" name="form2" method="post" action="">
<input type="button" onclick="calcServiceTotal();" name="button" id="button" value="calculate"/>
</form></td>
</tr>
</table>
The problem is you're using a function that is not defined, namely toFixed()
It is easy to find these errors if you use a debugging tool such as Firebug:
To clarify, toFixed is a function, but even though Javascript is loosely typed, in the context it's supplied your are applying toFixed to a string (for which it is undefined) and in this context the string cannot be coerced into a number.
You must specify it manually, by changing your last alert to:
alert("Pet's Name:" + animalName + '\n' + "Owner's Name:" + ownerName + '\n' + "Service:" + choosenService + '\n' + "Cost: $" + Number(serviceCost).toFixed(2) + '\n' + "Tax: $" + Number(taxCost).toFixed(2) + "Total Cost:" + Number(totalCost).toFixed(2));
Note that there are other errors in your code, such as concatenating two string values (which store Numbers) instead of addition.
I removed some bugs:
function calcServiceTotal() {
var animalName = document.getElementById("name").value;
var ownerName = document.getElementById("owner").value;
var currentDate = document.getElementById("date").value;
var choosenService = document.getElementById("service").value;
var serviceCost = Number(document.getElementById("value").value);
var taxCost = serviceCost * 0.07;
var totalCost = serviceCost + taxCost;
if (animalName == null || animalName == "") {
alert("Please give us your pet's name.");
return false;
} else if (ownerName == null || ownerName == "") {
alert("Please give us your name.");
return false;
} else if (currentDate== null || currentDate == "") {
alert("Please give us a date.");
return false;
} else {
alert("Pet's Name:" + animalName + '\n' + "Owner's Name:" + ownerName + '\n' + "Service:" + choosenService + '\n' + "Cost: $" + serviceCost.toFixed(2) + '\n' + "Tax: $" + taxCost.toFixed(2) + "Total Cost:" + totalCost.toFixed(2));
}
<table width="339" border="0">
<tr>
<td width="329"><strong>Patient Information</strong></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>Name:
<label for="textfield"></label> <input id="name" type="text" name="textfield" id="name" /></td>
</tr>
<tr>
<td>Owner:
<input type="text" name="textfield2" id="owner" /></td>
</tr>
<tr>
<td>Date:
<input type="text" name="textfield3" id="date" />
</td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td><strong>Services</strong></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>
<form id="form1" name="form1" method="post">
Select a Service:
<label for="select"></label>
<select name="select" id="service">
<option value="Basic Appointment - $50">Basic Appointment - $50</option>
<option value="Extended Appointment - $75">Extended Appointment - $75</option>
<option value="Vacination - $25">Vacination - $25</option>
<option value="Grooming - $35">Grooming - $35</option>
<option value="Bathing - $35">Bathing - $35</option>
</select>
</form>
</td>
</tr>
<tr>
<td>Service Fee (from above):
<label for="textfield4"></label>
<input type="text" name="textfield4" id="value" />
</td>
</tr>
<tr>
<td>
<form id="form2" name="form2" method="post" action="">
<input type="button" onclick="calcServiceTotal();" name="button" id="button" value="calculate"/>
</form>
</td>
</tr>
</table>