Problem disable fields of a select in html with JS - javascript

I try to disable a field when an option is chosen in a select. I have created a script with a function in JS to disable it, more however it does not work. Any ideas what to do? When I select "T in% compared to the previous day", I need the "Time /%" field to be disabled, which I have not achieved.
So the code I have implemented for the select is this
Here I create the selectable menu with the fields that they will have and then through a script I pass it to fill the fields and I also create the function to disable the "Hours" boxes. So, here the problem arises, inside the script when const select = document.querySelector (# 'TipoPatron2') is started The table disappears, more however when the query selector is commented the table is still there
<table border="0">
<body>
<td><strong>Patrón 2</strong>(
<select name="TipoPatron2" id="TipoPatron2">
<option value="00">T desde el encendido</option>
<option value="01" selected="selected">T desde las 12:00</option>
<option value="10">T en % respecto día anterior</option>
</select>)</td>
<td><input type="button" onclick="changeP2();" value="Actualizar"> <label id="Error2" style="color: red"></label>
</td>
</tr>
<tr>
<td>
<table>
<thead>
<tr color="#ccff00">
<td>Cambio</td>
<td>Hora/%</td>
<td>Minutos</td>
<td>Dimado</td>
<td>Dimado Entrada</td>
<td>Color</td>
</tr>
</thead>
<tbody id="mytbody2">
</tbody>
<script language="javascript">
let tbody2 = document.querySelector("#mytbody2");
var I = 1;
for (I = 1; I <= 8; I++) {
document.writeln("<tr align=center>");
document.writeln("<td>" + I + " <input type=\"checkbox\" checked id=\"AP2C" + I + "\"></td>");
document.writeln("<td><input type=\"text\" onpaste = \"alerta()\" value=\"0\" id=\"HP2C" + I + "\" maxlength=3 size=3></td>");
document.writeln("<td><input type=\"text\" value=\"0\" id=\"MP2C" + I + "\" maxlength=2 size=2></td>");
document.writeln("<td><select name=\"dimado\" id=\"DP2C" + I + "\"><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=\"10\">10%</option><option value=\"11\">11%</option><option value=\"12\">12%</option><option value=\"13\">13%</option><option value=\"14\">14%</option><option value = \"15\">15%</option><option value=\"16\">16%</option><option value=\"17\">17%</option><option value=\"18\">18%</option><option value=\"19\">19%</option><option value = \"20\">20%</option><option value=\"21\">21%</option><option value=\"10\">10%</option><option value = \"22\">22%</option><option value = \"23\">23%</option><option value = \"24\">24%</option><option value = \"25\">25%</option><option value = \"26\">26%</option><option value = \"27\">27%</option><option value = \"28\">28%</option><option value = \"29\">29%</option><option value = \"30\">30%</option><option value = \"31\">100%</option></select></td>");
document.writeln("<td><input type=\"text\" value=\"0\" id=\"IP2C" + I + "\" maxlength=2 size=2></td>");
document.writeln("<td><input type=\"text\" value=\"0\" id=\"CP2C" + I + "\" maxlength=2 size=2></td>");
document.writeln("</tr>");
}
//Creo una selector para que valide si se selecciona la opción de "T%" se ejecute la función desactivar
/*const select = document.querySelector('#TipoPatron2')
select.onchange = () => {
if (select.value == '10') {
desact()
}
}
*/
//Se crea la función alerta para cuando se haga un pegado en los box se ejecute la alerta
function alerta() {
alert("Seguro que quieres actualizar?");
}
//Se crea una función desactivar que se efectua en un for de 0 a 8 con el ID de las horas
function desact() {
for (let i = 1; i <= 8; i++)
document.getElementById('HP2C' + i).setAttribute("disabled", "disabled");
}
</script>
<tr align="center">
</tbody>
</table>
</body>
</td>
Photos when when queryselector is not commented
Now, I go to the page and the table disappears enter image description here
And if I comment the const select = document.querySelector ('# TipoPatron2') the table appears enter image description here
I need this query selector, since this is in charge of disabling the "Hora/%" when "T en % respecto día anterior" is selected in the first select. Any ideas what to do pls?

Have a look at this
I made the creation of the select simpler
I assume you mean to disable the HP2Cs when TipoPatron2 have value "10"
const tbody2 = document.getElementById("mytbody2");
tbody2.innerHTML = Array.from({length: 8}, (_, index) => index + 1).map(i => `<tr align=center>
<td>${i}<input type="checkbox" checked id="AP2C${i}" /></td>
<td><input type="text" value="0" id="HP2C${i}" maxlength=3 size=3 /></td>
<td><input type="text" value="0" id="MP2C${i}" maxlength=2 size=2 /></td>
<td><select name="dimado" id="DP2C ${i}">${Array.from({length: 29}, (_, index) => index + 1).map(i => `<option value="${i}">${i}%</option>`).join("") }
<option value = "31">100%</option></select></td>
<input type="text" value="0" id="IP2C${i}" maxlength=2 size=2 /></td>
<td><input type="text" value="0" id="CP2C${i}" maxlength=2 size=2 /></td>
</tr>`).join("")
const HP2Cs = document.querySelectorAll("[id^=HP2C]")
document.getElementById("TipoPatron2").addEventListener("change", function() {
const dis = this.value==="10";
HP2Cs.forEach(hp2c => hp2c.disabled = dis)
})
tbody2.addEventListener("paste", e => {
const tgt = e.target;
if (tgt.id.startsWith("HP2C")) alert("Seguro que quieres actualizar?");
})
<table border="0">
<tbody>
<tr>
<td><strong>Patrón 2</strong>(
<select name="TipoPatron2" id="TipoPatron2">
<option value="00">T desde el encendido</option>
<option value="01" selected="selected">T desde las 12:00</option>
<option value="10">T en % respecto día anterior</option>
</select>)</td>
<td><input type="button" onclick="changeP2();" value="Actualizar"> <label id="Error2" style="color: red"></label></td>
</tr>
<tr>
<td>
<table>
<thead>
<tr color="#ccff00">
<td>Cambio</td>
<td>Hora/%</td>
<td>Minutos</td>
<td>Dimado</td>
<td>Dimado Entrada</td>
<td>Color</td>
</tr>
</thead>
<tbody id="mytbody2">
</tbody>
</table>
</td>
</tr>
</tbody>
</table>

Related

How to call function JS for selected row only in table?

I'm trying to increment Quantity for second row only but the first row that increment and not the second ?!
this is my code Html of my table :
<table class="table">
<thead>
<tr>
<th class="">Item Name</th>
<th class="">Item Price</th>
<th class="">Quantité</th>
<th class="">Actions</th>
</tr>
</thead>
#foreach(var item in #Model.panierWebs) {
<tbody>
<tr class="">
<td class="">
<div class="product-info">
<img width="80" src="#Url.Content(item.Image)" alt="" />
#Html.DisplayFor(modelItem => item.Model)
</div>
</td>
<td class=""> #Html.DisplayFor(modelItem => item.Prix) DA</td>
<td class="">
<div class="quantity buttons_added">
<input onclick="decrement(#item.Prix,#item.Qte)" type="button" value="-" class="minus"><input type="number" name="quantity" id="qte" value="#item.Qte" title="Qty" class="input-text qty text" pattern="" inputmode=""><input onclick="increment(#item.Prix,#item.Qte)"
type="button" value="+" class="plus">
</div>
</td>
<td class="">
<a onclick="remove(#item.Id)" class="product-remove" href="#!">Remove</a>
</td>
</tr>
</tbody>
}
</table>
and my Script JS of increment and decrement Qte :
function decrement(prix, qte) {
console.log("qte avant dec" + document.getElementById("qte").value);
if (parseInt(document.getElementById("qte").value) != 1) {
qte = parseInt(document.getElementById("qte").value) - 1; // increment qte
console.log("qte apres dec" + qte);
$("#qte").val(qte); // affecter la nouvelle valeur de qte
var currenttotal = document.getElementById("total").value; // calculer le nouveau total
var newtotal = parseFloat(currenttotal) - parseFloat(prix);
$("#total").val(newtotal);
}
}
function increment(prix, qte) {
console.log("qte avant incr" + document.getElementById("qte").value);
if (parseInt(document.getElementById("qte").value) <= 5) {
qte = parseInt(document.getElementById("qte").value) + 1; // increment qte
console.log("qte apres incr" + qte);
$("#qte").val(qte); // affecter la nouvelle valeur de qte
var currenttotal = document.getElementById("total").value; // calculer le nouveau total
var newtotal = parseFloat(currenttotal) + parseFloat(prix);
$("#total").val(newtotal);
}
}
First, fix some problems:
You must avoid use duplicated identifiers in the DOM. You can use a class and work with classes instead of ids.
Also, you have tbody inside your foreach, making your table has lots of tbodys. You must put tbody tag outside the foreach
On approach to solve the problem is work with the concrete tag in which you call to your functions (the + and - buttons). To do that, add a parameter "this" to your functions. "this" is the input button in which you do the click
<input onclick="decrement(this,#item.Prix,#item.Qte)" ...>
<input type="number" ...>
<input onclick="increment(this,#item.Prix,#item.Qte)" ...>
And modify a bit your functions:
function increment(input, prix, qte) {
var number = $(input).closest("div").find("input[type=number]")
var inputVal = parseInt(number.val());
if (inputVal <= 5) {
qte = inputVal + 1; // increment qte
console.log("qte apres incr" + qte);
number.val(qte); // affecter la nouvelle valeur de qte
// ... your total part
}
}
The $(input).closest("div") give you the div that contains your buttons and the textbox. In that div, you search an input of type=number (the textbox), get it's value and do the job

Disable fields of a select in html with JS [duplicate]

This question already has an answer here:
Problem disable fields of a select in html with JS
(1 answer)
Closed 1 year ago.
I try to disable a field when an option is chosen in a select. I have created a script with a function in JS to disable it, more however it does not work. Any ideas what to do?
When I select "T in% compared to the previous day", I need the "Time /%" field to be disabled, which I have not achieved.
So the code I have implemented for the select is this:
<tr>
<td color="#66ccff"><strong>Patrón 1 (<select name="TipoPatron1" id="TipoPatron1">
<option value="00" selected="selected">T desde el encendido</option>
<option value="01">T desde las 12:00</option>
<option value="10" onclick="desactivar()">T en % respecto día anterior</option>
</select>
)</strong></td>
</tr>
<tr>
<td>
<table border="0">
<tbody>
<tr color="#ccff00" align="center">
<td>Cambio</td>
<td>Hora/%</td>
<td>Minutos</td>
<td>Dimado</td>
<td>Dimado Entrada</td>
<td>Color</td>
</tr>
</tbody>
</table>
</td>
</tr>
Here I create the selectable menu with the fields they will have and then through a script I pass it to fill the fields and I also create the function to disable the "Hours" boxes
<script language="javascript">
var I = 1;
for (I = 1; I <= 8; I++) {
document.writeln("<tr align=center>");
document.writeln("<td>"+I+" <input type=\"checkbox\" checked id=\"AP1C"+I+"\"></td>");
document.writeln("<td><input type=\"text\" onpaste = \"alerta()\" value=\"0\" id=\"HP1C"+I+"\" maxlength=3 size=3></td>");
document.writeln("<td><input type=\"text\" value=\"0\" id=\"MP1C"+I+"\" maxlength=2 size=2></td>");
document.writeln("<td><select name=\"dimado\" id=\"DP1C"+I+"\"><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=\"10\">10%</option><option value=\"11\">11%</option><option value=\"12\">12%</option><option value=\"13\">13%</option><option value=\"14\">14%</option><option value = \"15\">15%</option><option value=\"16\">16%</option><option value=\"17\">17%</option><option value=\"18\">18%</option><option value=\"19\">19%</option><option value = \"20\">20%</option><option value=\"21\">21%</option><option value=\"10\">10%</option><option value = \"22\">22%</option><option value = \"23\">23%</option><option value = \"24\">24%</option><option value = \"25\">25%</option><option value = \"26\">26%</option><option value = \"27\">27%</option><option value = \"28\">28%</option><option value = \"29\">29%</option><option value = \"30\">30%</option><option value = \"31\">100%</option></select></td>");
document.writeln("<td><input type=\"text\" value=\"0\" id=\"IP1C"+I+"\" maxlength=2 size=2></td>");
document.writeln("<td><input type=\"text\" value=\"0\" id=\"CP1C"+I+"\" maxlength=2 size=2></td>");
document.writeln("</tr>");
}
function alerta() {
alert("Seguro que quieres actualizar?");
}
function desactivar() {
document.getElementById('HP1C').setAttribute("disabled", "disabled");
}
</script>
In the desactivar() function, I try to pass with the ID of the HP1C element representing the hours ID, I pass the getElementByID and the disable attribute, but it doesn't work.
In the photo, when you see the "Patron1" select with "T en % respecto al dia anterior" The "Hora/%" field must be deactivated
disabled is a boolean attribute.
function desactivar() {
for (let i = 0; i < 8; i++)
document.getElementById('HP1C1'+i).setAttribute("disabled", true);
}
Edit: You don't use the right event
<body>
<h1>Patrón 1</h1>
<select name="TipoPatron1" id="TipoPatron1">
<option value="00" selected="selected">T desde el encendido</option>
<option value="01">T desde las 12:00</option>
<option value="10">T en % respecto día anterior</option>
</select>
<table>
<thead>
<tr color="#ccff00">
<td>Cambio</td>
<td>Hora/%</td>
<td>Minutos</td>
<td>Dimado</td>
<td>Dimado Entrada</td>
<td>Color</td>
</tr>
</thead>
<tbody id="mytbody">
</tbody>
</table>
<script language="javascript">
let i = 1;
let tbody = document.querySelector("#mytbody");
for (let i = 1; i <= 8; i++) {
tbody.innerHTML += "<tr>";
tbody.innerHTML += "<td>"+i+" <input type=\"checkbox\" checked id=\"AP1C"+i+"\"></td>";
tbody.innerHTML += "<td><input type=\"text\" onpaste = \"alerta()\" value=\"0\" id=\"HP1C"+i+"\" maxlength=3 size=3></td>";
tbody.innerHTML += "<td><input type=\"text\" value=\"0\" id=\"MP1C"+i+"\" maxlength=2 size=2></td>";
tbody.innerHTML += "<td><select name=\"dimado\" id=\"DP1C"+i+"\"><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=\"10\">10%</option><option value=\"11\">11%</option><option value=\"12\">12%</option><option value=\"13\">13%</option><option value=\"14\">14%</option><option value = \"15\">15%</option><option value=\"16\">16%</option><option value=\"17\">17%</option><option value=\"18\">18%</option><option value=\"19\">19%</option><option value = \"20\">20%</option><option value=\"21\">21%</option><option value=\"10\">10%</option><option value = \"22\">22%</option><option value = \"23\">23%</option><option value = \"24\">24%</option><option value = \"25\">25%</option><option value = \"26\">26%</option><option value = \"27\">27%</option><option value = \"28\">28%</option><option value = \"29\">29%</option><option value = \"30\">30%</option><option value = \"31\">100%</option></select></td>";
tbody.innerHTML += "<td><input type=\"text\" value=\"0\" id=\"iP1C"+i+"\" maxlength=2 size=2></td>";
tbody.innerHTML += "<td><input type=\"text\" value=\"0\" id=\"CP1C"+i+"\" maxlength=2 size=2></td>";
tbody.innerHTML += "</tr>";
}
const select = document.querySelector('#TipoPatron1')
select.onchange = () => {
if (select.value == '10') {
desactivar()
}
}
function alerta() {
alert("Seguro que quieres actualizar?");
}
function desactivar() {
for (let i = 1; i<= 8; i++)
document.getElementById('HP1C' + i).setAttribute("disabled", "disabled");
}
</script>
</body>

fwrite php function not writing

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

Javascript: Atributting value to an id What is wrong with this code?

the thing here is, i have this code, and it was supposed to output the results of the variables into contact form 7 for wordpress hidden fields (i have the modules plugin to enable the hidden fields) that were sent by email, but i dont think the id i display is getting the value i attribute, i js linted the code and all it said was multiple variable declaration, which shouldnt be a problem since it's an if statement, so, there will never be a double declaration of the variable.
This is the code i use to transform the cookies created in my script (using jQuery.cookie) into text that is outputted to a table in my website, but more than outputting it to a table, i would like to email it to the user, i already have a contact-form 7 form prepared to do this, i just need to attribute the value of the returned variable (or at least one of them, the last is the price, i dont need to send that by email) to the contact form field id, yesterday here in stackoverflow someone gave me that code to pass the value into contact form 7, but im afraid it isnt working :/
function readRims() {
var rims_read = $.cookie('rim_color');
if (rims_read=="black" ) {
var jantes = 'Pretas';
var preco = 'Sob Consulta';
}
else if (rims_read=="silver"){
var jantes = 'De Série';
var preco = '';
}
else if (rims_read=="white"){
var jantes = 'Brancas';
var preco = 'Sob Consulta';
}
else if (rims_read=="titanium"){
var jantes = 'Titanium';
var preco = 'Sob Consulta';
}
else {
var jantes = 'Escolha as Jantes';
var preco =' ';
}
$('#cfg_rims').val(jantes);
return {
jantes: jantes,
preco: preco
};
}
HTML
[hidden modelo id:cfg_model]
[hidden cor id:cfg_color]
[hidden jantes id:cfg_rims]
[hidden ac id:cfg_ac]
[hidden abs id:cfg_abs]
[hidden alarme id:cfg_alarm]
[hidden led id:cfg_led]
[hidden chapeleira id:cfg_chapeleira]
<p>Oferecemos a possibilidade de enviar um email à nossa equipa com as suas escolhas no nosso configurador como manifestação de interesse, preencha o seguinte formulário e carregue em enviar para proceder ao envio da informação, a nossa equipa entrará em contacto consigo para dar seguimento à manifestação de interesse.</p>
<p>O seu Nome<br/></p>
[text* nome]
<p>O seu Email<br/></p>
[email* email]
<p>Observações<br/></p>
[textarea obs]
<p>[submit "Enviar"]</p>
Try
<table class="tab_cfg" align="center" width="70%" cellspacing="0"
cellpadding="10">
<tr style="border-bottom: none;">
<th colspan="4"><br />
<p>Abra o Configurador e siga todos os passos, a tabela abaixo
vai mostrar os resultados que escolheu:</p></th>
</tr>
<tr>
<th colspan="4"><a class="readon"
href="http://popo.com.pt/POPO/configurador/cfg/page_model/configurador_model.html"
rel="rokbox[550 600]">Configurador</a> <a class="readon"
href="javascript:setCookies(); document.location.reload(true)">Reset</a>
</th>
</tr>
<tr>
<td colspan="2"> </td>
<td>Característica</td>
<td>Preço</td>
</tr>
<tr>
<td colspan="2">Modelo</td>
<td><p class="modelo-modelo"></p></td>
<td><p class="modelo-preco"></p></td>
</tr>
<tr>
<td colspan="2">Cor</td>
<td><p class="color"></p></td>
<td></td>
</tr>
<tr>
<td colspan="2">Jantes</td>
<td><p class="rims-jantes"></p></td>
<td><p class="rims-preco"></p></td>
</tr>
<tr>
<td style="border-right: 1px solid #d1d1d1;" rowspan="6">Extras</td>
<td>ABS</td>
<td><p class="abs-abs"></p></td>
<td><p class="abs-preco"></p></td>
</tr>
<tr border="1px">
<td>Ar Condicionado</td>
<td><p class="ac-ac"></p></td>
<td><p class="ac-preco"></p></td>
</tr>
<tr>
<td>Alarme</td>
<td><p class="alarm-alarm"></p></td>
<td><p class="alarm-preco"></p></td>
</tr>
<tr>
<td>Luzes LED</td>
<td><p class="led.led"></p></td>
<td><p class="led.preco"></p></td>
</tr>
<tr style="border-bottom: none;">
<td>Chapeleira</td>
<td><p class="chapeleira-chapeleira"></p></td>
<td><p class="chapeleira-preco"></p></td>
</tr>
</table>
<script type="text/javascript">
jQuery(function($) {
var $table = $('.tab_cfg');
var modelo = readModel();
$table.find('.modelo-modelo').html(modelo.modelo)
$table.find('.modelo-preco').html(modelo.preco)
$table.find('.color').html(readColor())
var jantes = readRims();
$table.find('.rims-jantes').html(jantes.modelo)
$table.find('.rims-preco').html(jantes.preco)
var abs = readABS();
$table.find('.abs-abs').html(abs.modelo)
$table.find('.abs-preco').html(abs.preco)
var ac = readAC();
$table.find('.ac-modelo').html(ac.modelo)
$table.find('.ac-preco').html(ac.preco)
var alarm = readAlarm();
$table.find('.alarm-modelo').html(alarm.modelo)
$table.find('.alarm-preco').html(alarm.preco)
var led = readLED();
$table.find('.led-modelo').html(led.modelo)
$table.find('.led-preco').html(led.preco)
var chapeleira = readChap();
$table.find('.chapeleira-modelo').html(chapeleira.modelo)
$table.find('.chapeleira-preco').html(chapeleira.preco)
})
</script>

jquery form validation not fired / working

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() {

Categories