how to create two dimentional matrix 2 inside javascript - javascript

I want to create two dimentional array matrix 2 inside javascript for input. But all of record datas are inside first input. I have to show relevant record data every input. Can you help me for two dimentional array.
HTML CODES
<div id="hiddenProduct">
<label>Company Product Number</label>
<select onchange="addProducts()" name="firmProductNumber" id="prdcts" class="form-control form-control-sm" style="width: 100%;">
<option value="0">Unselected</option>
<option #if($saproduct->firmProductNumber == 1 ) selected="true" id="btnProduct" onclick="addProducts()" #endif>1</option>
<option #if($saproduct->firmProductNumber == 2 ) selected="true" id="btnProduct" onclick="addProducts()" #endif>2</option>
</select>
<hr>
</div>
</div>
<div id="product" class="form-group col-md-4">
<div id="hiddenContainerP">
<div id="containerP"></div>
</div>
</div>
JavaScript Codes
function addProducts() {
var number = document.getElementById("prdcts").value;
var container = document.getElementById("containerP");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
var p = [];
p = <?php echo json_encode($x); ?>
//Controller $x = []; $x[] = [$arrayProductName,$arrayProductAmount,$arrayProductAmountType];
for (i = 0; i < number; i++) {
// Append a node with a random text
// Create an <input> element, set its type and name attributes
var productName = document.createElement("input");
productName.type = "text";
productName.name = "name[]";
productName.value = p[[0][i]];
productName.className = "form-control form-control-sm";
productName.placeholder = "Product Name";
container.appendChild(productName);
var amount = document.createElement("input");
amount.type = "number";
amount.name = "amount[]";
amount.className = "form-control form-control-sm";
amount.placeholder = "Amount";
amount.value = p[[1][i]];
container.appendChild(amount);
var amountType = document.createElement("input");
amountType.type = "text";
amountType.name = "amountType[]";
amountType.value = p[[2][i]];
amountType.className = "form-control form-control-sm";
amountType.placeholder = "Amount Type";
container.appendChild(amountType);
container.appendChild(document.createElement("br"));
}
}
</script>```

Related

Messing up the dynamic dropdown. What am I doing wrong?

I am trying to add dropdown list dynamically to a WebApp using google appscript. I wrote a few lines of javascript code in the client side to communicate the server side to fetch the data from google-sheets. After a lot of trying, I'm somewhat successful. However, it looks like, whenever I click on the "Add Product" button, for first 1-2 times the array from which the dropdown is generated is empty. As a result the dropdown remains blank. However after 1 or 2 blank dropdowns the it starts working as it's suppose to.
What am I doing wrong ?
I have 3 files-
form.html
code.gs
js_script.html
Link to the google sheet
Content of form.html-
<body>
<div class="container">
<div class = "row">
<h1>Order Form</h2>
</div> <!-- end of row -->
<div class = "row">
<input id="orderno" type="text" class="validate">
<label for="orderno">Order Number</label>
</div> <!-- end of row -->
<div class = "row">
<input id="clientname" type="text" class="validate">
<label for="clientname">Client Name</label>
</div> <!-- end of row -->
<div class = "row">
<input id="clientaddr" type="text" class="validate">
<label for="clientaddr">Client Address</label>
</div> <!-- end of row -->
<div class = "row">
<input id="clientphone" type="text" class="validate">
<label for="clientphone">Client Phone Number</label>
</div> <!-- end of row -->
<div class = "row">
<input id="ordertype" type="text" class="validate">
<label for="ordertype">Order Type</label>
</div> <!-- end of row -->
<div id="productsection"></div>
<div class = "row">
<button id="addproduct">Add Product</button>
</div> <!-- end of row -->
<div class = "row">
<button id="submitBtn">Submit</button>
</div> <!-- end of row -->
</div> <!-- End of "container" class -->
<?!= include("js_script"); ?>
</body>
Content of code.gs
const ssID = "1YKZYgKctsXU3DKTidVVPUhmPXUkzjjocaiMz1S76JAE";
const ss = SpreadsheetApp.openById(ssID);
function doGet(e){
Logger.log(e);
return HtmlService.createTemplateFromFile("form").evaluate();
}
function include(fileName){
return HtmlService.createHtmlOutputFromFile(fileName).getContent();
}
function appendDataToSheet(userData){
const ws = ss.getSheetByName("orders");
ws.appendRow([new Date(), userData.orderNumber, userData.clientName, userData.clientAddress, userData.clientPhone, userData.orderType, userData.products].flat());
}
function getOptionArray(){
const ws = ss.getSheetByName("product_list");
const optionList = ws.getRange(2, 1, ws.getRange("A2").getDataRegion().getLastRow() - 1).getValues()
.map(item => item[0]);
return optionList;
}
function logVal(data){
Logger.log(data);
}
Content of js_script.html
<script>
let counter = 0;
let optionList = [];
document.getElementById("submitBtn").addEventListener("click", writeDataToSheet);
document.getElementById("addproduct").addEventListener("click", addInputField);
function addInputField(){
counter++;
// The idea is, everytime when "add product" button is clicked, the following element must be added to the "<div id="productoption></div>" tag.
// <div class="row">
// <select id="productX">
// <option>option-X</option>
// </select>
// </div>
const newDivTag = document.createElement('div');
const newSelectTag = document.createElement('select');
newDivTag.class = "row";
newSelectTag.id = "product" + counter.toString();
google.script.run.withSuccessHandler(updateOptionList).getOptionArray();
google.script.run.logVal(optionList); // This is just to test the optionList array if it's updated or not
for(let i = 0; i < optionList.length; i++){
const newOptionTag = document.createElement('option');
newOptionTag.textContent = optionList[i];
newOptionTag.value = optionList[i];
newSelectTag.appendChild(newOptionTag);
}
newDivTag.appendChild(newSelectTag);
document.getElementById('productsection').appendChild(newDivTag);
}
function writeDataToSheet(){
const userData = {};
userData.orderNumber = document.getElementById("orderno").value;
userData.clientName = document.getElementById("clientname").value;
userData.clientAddress = document.getElementById("clientaddr").value;
userData.clientPhone = document.getElementById("clientphone").value;
userData.orderType = document.getElementById("ordertype").value;
userData.products = [];
for(let i = 0; i < counter; i++) {
let input_id = "product" + (i+1).toString();
userData.products.push(document.getElementById(input_id).value);
}
google.script.run.appendDataToSheet(userData);
}
function updateOptionList(arr){
optionList = arr.map(el => el);
}
</script>
About your current issue of However, it looks like, whenever I click on the "Add Product" button, for first 1-2 times the array form which the dropdown is generated is empty. As a result the dropdown remains blank. However after 1 or 2 blank dropdowns the it starts working as it's suppose to., when I saw your script, I thought that the reason for your issue might be due to that google.script.run is run with the asynchronous process. If my understanding is correct, how about the following modification?
In this case, your js_script.html is modified.
Modified script:
<script>
let counter = 0;
// let optionList = []; // Removed
document.getElementById("submitBtn").addEventListener("click", writeDataToSheet);
document.getElementById("addproduct").addEventListener("click", addInputField);
// Modified
function addInputField(){
counter++;
const newDivTag = document.createElement('div');
const newSelectTag = document.createElement('select');
newDivTag.class = "row";
newSelectTag.id = "product" + counter.toString();
google.script.run.withSuccessHandler(arr => {
const optionList = updateOptionList(arr);
google.script.run.logVal(optionList);
for(let i = 0; i < optionList.length; i++){
const newOptionTag = document.createElement('option');
newOptionTag.textContent = optionList[i];
newOptionTag.value = optionList[i];
newSelectTag.appendChild(newOptionTag);
}
newDivTag.appendChild(newSelectTag);
document.getElementById('productsection').appendChild(newDivTag);
}).getOptionArray();
}
function writeDataToSheet(){
const userData = {};
userData.orderNumber = document.getElementById("orderno").value;
userData.clientName = document.getElementById("clientname").value;
userData.clientAddress = document.getElementById("clientaddr").value;
userData.clientPhone = document.getElementById("clientphone").value;
userData.orderType = document.getElementById("ordertype").value;
userData.products = [];
for(let i = 0; i < counter; i++) {
let input_id = "product" + (i+1).toString();
userData.products.push(document.getElementById(input_id).value);
}
google.script.run.appendDataToSheet(userData);
}
// Modified
function updateOptionList(arr){
return arr.map(el => el); // I cannot understand this mean.
}
</script>
or, in this case, updateOptionList might not be required to be used as follows.
<script>
let counter = 0;
// let optionList = []; // Removed
document.getElementById("submitBtn").addEventListener("click", writeDataToSheet);
document.getElementById("addproduct").addEventListener("click", addInputField);
// Modified
function addInputField(){
counter++;
const newDivTag = document.createElement('div');
const newSelectTag = document.createElement('select');
newDivTag.class = "row";
newSelectTag.id = "product" + counter.toString();
google.script.run.withSuccessHandler(optionList => {
google.script.run.logVal(optionList);
for(let i = 0; i < optionList.length; i++){
const newOptionTag = document.createElement('option');
newOptionTag.textContent = optionList[i];
newOptionTag.value = optionList[i];
newSelectTag.appendChild(newOptionTag);
}
newDivTag.appendChild(newSelectTag);
document.getElementById('productsection').appendChild(newDivTag);
}).getOptionArray();
}
function writeDataToSheet(){
const userData = {};
userData.orderNumber = document.getElementById("orderno").value;
userData.clientName = document.getElementById("clientname").value;
userData.clientAddress = document.getElementById("clientaddr").value;
userData.clientPhone = document.getElementById("clientphone").value;
userData.orderType = document.getElementById("ordertype").value;
userData.products = [];
for(let i = 0; i < counter; i++) {
let input_id = "product" + (i+1).toString();
userData.products.push(document.getElementById(input_id).value);
}
google.script.run.appendDataToSheet(userData);
}
</script>
Note:
When you modified the Google Apps Script of Web Apps, please modify the deployment as a new version. By this, the modified script is reflected in Web Apps. Please be careful about this.
You can see the detail of this in my report "Redeploying Web Apps without Changing URL of Web Apps for new IDE (Author: me)".
Reference:
Class google.script.run (Client-side API)

Why the IndexedDB cursor.value.key from a dictionary key gives me undefined?

I want to append each value from each key from the dictionary that was added in the IDB to a cell on a table.
The way that the dictionary was added goes something like this:
var trans_write = data_base.transaction(["students"], "readwrite");
var petition_write = trans_write.objectStore("students");
var query = petition_write.add(dictionary);
data_base is the global variable that stored the e.target.result; when the onsuccess event was triggered
Then I passed the same dictionary to a function that will iterate the value from each key from the same dictionary so I can add its value to a cell, then the cell to a row and finally to the main table:
function displayDataOnTable(dictionary) {
var trans = data_base.transaction(["students"], "readonly");
var query = trans.objectStore("students");
var cursor = query.openCursor();
cursor.addEventListener("success", function(e) {
var the_cursor = e.target.result;
if (the_cursor) {
var new_row = document.createElement("tr");
for (var key in dictionary) {
var cell_data = the_cursor.value.key;
var new_cell = document.createElement("td");
new_cell.append(cell_data);
new_row.append(new_cell);
}
table.append(new_row);
the_cursor.continue();
}
}, false);
}
As you can guess, table is the global variable that has assigned a HTMLTable who was obtain by its id: document.getElementById("idTable");
The issue that I'm having is that the line var cell_data = the_cursor.value.key; assigns cell_data as undefined and also the iterator key from for (var key in dictionary) quotes that it is declared but it is never readed. So that results in the table having in all its cells "undefined".
Any solutions? Best regards. Thanks.
Update #2 (Sharing the original full code, both JS and HTML. English is not my primary language, so excuse me for that):
var campos = [];
var base_de_datos;
var tabla;
function main() {
var ids_campo = [
"no_control", "nombre", "curp", "masculino",
"femenino", "otro", "grado", "grupo",
"peso", "estatura", "sangre", "fecha_nac"
];
var boton_reg = document.getElementById("envio_datos");
var abrir_bd = indexedDB.open("AlumnosBD");
tabla = document.getElementById("tablaDatosAlumno");
abrir_bd.onupgradeneeded = function(e) {
base_de_datos = e.target.result;
base_de_datos.createObjectStore("alumnos", {keyPath: "no_control"});
}
abrir_bd.onsuccess = function(e) {
base_de_datos = e.target.result;
}
boton_reg.addEventListener("click", function(e) {
obtenerCampos(ids_campo);
agregarDatosAlObjetoStore();
}, false);
}
function obtenerCampos(ids_campo) {
for (i = 0; i < ids_campo.length; i++) {
if (i >= 3 && i <= 5) {
var radio_button = document.getElementById(ids_campo[i]);
if (radio_button.checked) {
campos.push(radio_button);
}
} else {
campos.push(document.getElementById(ids_campo[i]));
}
}
}
function agregarDatosAlObjetoStore() {
var valores = [];
var dicc = {};//haciendo diccionario con las claves y valores para luego añadirlo a la bd.
for (i = 0; i < campos.length; i++) {
if (i == 3){
valores.push(campos[i].id);
dicc[campos[i].name] = valores[i];
}
valores.push(campos[i].value);
dicc[campos[i].id] = valores[i];
}
var trans_write = base_de_datos.transaction(["alumnos"], "readwrite");
var peticion_escritura = trans_write.objectStore("alumnos");
var query = peticion_escritura.add(dicc);
query.addEventListener("success", function() {
alert("Datos añadidos satisfactoriamente.")
mostrarDatosEnTabla(dicc);
}, false)
}
function mostrarDatosEnTabla(d) {
var trans_lectura = base_de_datos.transaction(["alumnos"], "readonly");
var peticion_lectura = trans_lectura.objectStore("alumnos");
var puntero = peticion_lectura.openCursor();
puntero.addEventListener("success", function(e) {
var indice_puntero = e.target.result;
if (indice_puntero) {
var fila_nueva = document.createElement("tr");
for (var clave in d) {
var info_celda = indice_puntero.value.clave
var celda_nueva = document.createElement("td");
celda_nueva.append(info_celda);
fila_nueva.append(celda_nueva);
}
tabla.append(fila_nueva);
indice_puntero.continue();
}
}, false);
}
window.addEventListener("load", main, false);
<!DOCTYPE html>
<html lang = "es">
<head>
<title>HTML</title>
<meta charset="utf-8">
<meta name = "keywords" content = "Test">
<link rel = "stylesheet" href = "styleForm.css">
<script src = "scriptDB.js"></script>
</head>
<body>
<section id = "zonaFormulario">
<datalist id = "tipos_sangre">
<option value = "A+"></option>
<option value = "A-"></option>
<option value = "B+"></option>
<option value = "B-"></option>
<option value = "O+"></option>
<option value = "O-"></option>
<option value = "AB+"></option>
<option value = "AB-"></option>
</datalist>
<form id = "reg_alumno" method = "get">
<div id = "seccion1">
<p id = "lbl_secc1">CURP: <input id = "curp" name = "curp" minlength = "18" maxlength = "18" required></p>
<p id = "lbl_secc1">NOMBRE: <input id = "nombre" name = "nombre" type = "text" maxlength = "60" required></p>
</div>
<div id = "seccion2">
<p id = "lbl_secc2">Género:</p>
<p id = "lbl_secc2"><input type = "radio" id = "masculino" name = "genero" required> Masculino</p>
<p id = "lbl_secc2"><input type = "radio" id = "femenino" name = "genero" required> Femenino</p>
<p id = "lbl_secc2"><input type = "radio" id = "otro" name = "genero" required> Otro</p>
<p id = "lbl_secc2">No. de Control: <input id = "no_control" name = "no_control" type = "text" pattern = "[0-9]{8}" maxlength = "8" required></p>
<p id = "lbl_secc2">Grado: <input id = "grado" name = "grado" type = "number" min = "1" max = "9" required></p>
<p id = "lbl_secc2">Grupo: <input id = "grupo" name = "grupo" type = "text" pattern = "[A-D]" required></p>
</div>
<div id = "seccion3">
<p id = "lbl_secc3">Peso: <input id = "peso" name = "peso" type = "number" min = "32" max = "150" required></p>
<p id = "lbl_secc3">Estatura: <input id = "estatura" name = "estatura" type = "number" min = "120" max = "200" required></p>
<p id = "lbl_secc3">Tipo de sangre: <input id = "sangre" name = "sangre" type = "text" list = "tipos_sangre" required></p>
<br><br>
<p id = "lbl_secc3">Fecha de nacimiento: <input id = "fecha_nac" name = "fecha_nac" type = "date" required></p>
</div>
<div id = "seccion4">
<input type="button" id = "envio_datos" name = "envio_datos" value = "Registrar">
</div>
</form>
</section>
<section id = "zonaTabla">
<table id = "tablaDatosAlumno">
<thead>
<tr>
<th>Número de control</th>
<th>Nombre</th>
<th>CURP</th>
<th>Género</th>
<th>Grado</th>
<th>Grupo</th>
<th>Peso (kg)</th>
<th>Estatura (cm)</th>
<th>Tipo de sangre</th>
<th>Fecha de nacimiento</th>
</tr>
</thead>
</table>
</section>
</body>
</html>
You cannot read data from IndexedDB until after it has been written to IndexedDB. You are most likely calling displayDataOnTable before the data has been written. If you query for data before it exists, then you will experience the problems you are describing.
For more help, please provide the code that calls the write code, and show when you call the write code, where in your code you wait for the write call to complete, and then where in the code you perform the read.
Remember, IndexedDB's API uses non-blocking functions. If you start performing a write, do not wait for it to complete (block until it is complete), and then start a read, you have a race condition. Search through the questions with the keywords "indexeddb" and "async" to learn more, or search around for general topics on asynchronous JavaScript.

Keep html that is generated with javascript after laravel POST with old data

There are 2 fields that belong together price and size. Some products have more then 1 size, so the html offers a button to generate more fields. However if some validation fails the fields are gone and not populated anymore.
Here are the non generated html fields
<div class="col-md-6">
<label for="price" class="form-label">Prijs* </label>
<input type="text"
name="priceAndSize[price][0]"
class="form-control #if($errors->has('priceAndSize.price.*')) border-danger #endif"
id="price"
value="{{ old('priceAndSize.price[0]') }}">
</div>
<div class="col-md-6">
<label for="stock" class="form-label">Inhoud in ml</label>
<input type="text"
name="priceAndSize[size][0]"
class="form-control"
id="size"
value="{{ old('priceAndSize.size[0]') }}">
</div>
With a button to generate more fields
<input type="button" class="btn btn-info mt-3 text-white" onclick="addInput()"
value="Meerdere prijzen & inhoud"/>
the javascript to generate the fields:
counter = 1;
function addInput() {
// Input
const newInputPrice = document.createElement('input');
newInputPrice.id = 'price' + counter;
newInputPrice.name = 'priceAndSize[price][' + counter + ']';
newInputPrice.type = 'text';
newInputPrice.className = 'form-control';
const newInputSize = document.createElement('input');
newInputSize.id = 'size' + counter;
newInputSize.name = 'priceAndSize[size][' + counter + ']';
newInputSize.type = 'text';
newInputSize.className = 'form-control';
// Label
const labelPrice = document.createElement('label');
labelPrice.htmlFor = 'price' + counter;
labelPrice.innerHTML = 'Prijs* ';
labelPrice.className = 'form-label';
const labelSize = document.createElement('label');
labelSize.htmlFor = 'size' + counter;
labelSize.innerHTML = 'Inhoud* ';
labelSize.className = 'form-label';
// New boostrap div
const newDivPrice = document.createElement('div');
newDivPrice.className = 'col-md-6';
const newDivSize = document.createElement('div');
newDivSize.className = 'col-md-6';
// Add label and input to div
newDivPrice.appendChild(labelPrice);
newDivPrice.appendChild(newInputPrice);
newDivSize.appendChild(labelSize);
newDivSize.appendChild(newInputSize);
const currentDiv = document.getElementById("test");
currentDiv.appendChild(newDivPrice);
currentDiv.appendChild(newDivSize);
counter++;
}
You can try this in your blade.
$priceAndSize = Request::old('priceAndSize');
#if(count($priceAndSize[price]) > 0)
for (var i = 1; i <= {{count($priceAndSize[price])}}; i++) {
addInput();
}
#elseif(count($priceAndSize[size]) > 0)
for (var i = 1; i <= {{count($priceAndSize[size])}}; i++) {
addInput();
}
#endif

populate drop down lists with data from mysql data-base

I'm creating a form and it asks candidates to post info about their previous education history - here are the screenshots of the form and the code attached to them!
Here's my javascript code:
<script>
function removeFields1(){
//var container1 = document.getElementById("container1");
//container1.removeChild(input);
}
function addFields1(){
var container = document.getElementById("container1");
var option = document.createElement("select"); //? how do I fix this up
//option.text = "Kiwi";
//container.add(option);
container.appendChild(option);//? how do I fix this up
container.appendChild(document.createTextNode("Address: "));//Address form
var input = document.createElement("input");
input.type = "text";
input.id = "instaddress";
input.name = "instaddress";
input.size = 20;
input.maxlenth = 20;
container.appendChild(input);
container.appendChild(document.createTextNode("From: ")); // which year the person started
var from = document.createElement("input"); // studying in that institution
from.type = "text";
from.id = "from";
from.name = "from";
from.size = 4;
from.maxlenth = 4;
container.appendChild(from);
container.appendChild(document.createTextNode("To: ")); // which year the person finished
var to = document.createElement("input"); // studying in that institution
to.type = "text";
to.id = "to";
to.name = "to";
to.size = 4;
to.maxlenth = 4;
container.appendChild(to);
container.appendChild(document.createTextNode(" Did You Graduate?: Yes")); // radio buttons whether someone graduated or not
var grad = document.createElement("input");
grad.type = "radio";
grad.id = "graduate";
grad.name = "graduate";
grad.value = "yes"; //yes value for radio button
container.appendChild(grad);
container.appendChild(document.createTextNode(" No "));
var grad1 = document.createElement("input");
grad1.type = "radio";
grad1.id = "graduate";
grad.value = "no"; //no value for radio button
container.appendChild(grad1);
container.appendChild(document.createTextNode(" Certificate: "));
var certificate = document.createElement("input");
certificate.type = "text";
certificate.id = "certificate";
certificate.name = "certificate";
input.size = 25;
input.maxlenth = 25;
container.appendChild(certificate);
var addInstitution = document.getElementById(" Add");
var removeInstitution = document.getElementById("Remove");
// container.removeChild(addInstitution);
//create and insert input/text
//create and insert button
addInstitution = document.createElement("a");
addInstitution.id="Add"
addInstitution.href="#";
addInstitution.text="Add";
addInstitution.onclick=function(){addFields1();};
removeInstitution = document.createElement("a");
removeInstitution.id="Remove"
removeInstitution.href="#";
removeInstitution.text=" Remove";
container.appendChild(addInstitution);
container.appendChild(removeInstitution);
//removeInstitution.onclick=function(){removeFields1();};
//
container.appendChild(document.createElement("br"));
}
</script>
Here are the form fields as well:
<body>
<form>
<div id="container1">
<select name="institution" id="institution">
<option <?php if(isset($_POST['institution'])) { echo $_POST['institution']; } ?>>Select Institution</option>
<?php
$sql1a = "SELECT * FROM institution ORDER BY institution asc";
$smt1a = $dbs->prepare($sql1a);
$smt1a -> execute();
while($row1a=$smt1a->fetch(PDO::FETCH_ASSOC))
{
if($row1a['institution']==$_GET['id3'])
echo("<option selected value=$row1a[institution]>$row1a[institution]</option>");
else
echo("<option value=$row1a[institution]>$row1a[institution]</option>");
}
?>
</select>
Address: <input size="20" type="text" id="instaddress" name="instaddress" maxlength="20" size="20"> From:<input type="text" id="from" name="from" size="4" > To: <input type="text" id="to" name="to" size="4">
Did You Graduate?: Yes<input type="radio" onclick="checkRadio()" id="graduate" name="graduate" value="yes"> No
<input type="radio" onclick="checkRadio()" id="graduate" name="graduate" value="no"> Certificate: <input size="20" type="text" id="certificate" name="certificate" maxlength="25" size="25">
Add <br>
</div>
</form>
</body>
How can I create a drop-down select menu for the Javascript section when I click addFields1()?
The PHP code for the drop down menu is down here below-the menu is populated with data from a MySQL database. What will be the correct
<option <?php if(isset($_POST['institution'])) { echo $_POST['institution']; } ?>>Select Institution</option>
<?php
$sql1a = "SELECT * FROM institution ORDER BY institution asc";
$smt1a = $dbs->prepare($sql1a);
$smt1a -> execute();
while($row1a=$smt1a->fetch(PDO::FETCH_ASSOC))
{
if($row1a['institution']==$_GET['id3'])
echo("<option selected value=$row1a[institution]>$row1a[institution]</option>");
else
echo("<option value=$row1a[institution]>$row1a[institution]</option>");
}
?>
</select>
Can any of you guys help me out with fixing up the Javascript code?
Here's the snippet of code that needs to be rectified so that I can use Javascript functions to drop down the menu list every time that the "Add" link is pressed:
var option = document.createElement("select"); //? how do I fix this up
var option = document.createElement("select"); //? how do I fix this up
//option.text = "Kiwi";
//container.add(option);
container.appendChild(option);//? how do I fix this up
i think what you want to do is:
var select = document.createElement("select");
var option = document.createElement("option");
option.value = "Kiwi";
option.innerHTML = "Kiwi";
select.appendChild(option);
....but producing these long javascript functions is not a good programming style...a function should consist of no more than 20 to 30 lines of code...so you should consider using one of these:
http://www.sitepoint.com/10-javascript-jquery-templates-engines/
or load the whole line via ajax...

Javascript OnChange not firing on first change

I have an issue concerning an 'onchange' event within a select html element. The code i have written is supposed to display certain text boxes depending on which select option has been selected.
The code I have is as follows:
Customer Type:
<select name="customerType" onchange="cust_type()">
<option value="" selected>Customer Type?</option>
<option value="nonCorp">Customer</option>
<option value="corp">Corporate</option>
</select>
JS:
function cust_type() {
var select_drop = document.getElementsByName('customerType');
var selected = select_drop[0].value;
var f_name = document.getElementById('forename');
var s_name = document.getElementById('surname');
var c_name = document.getElementById('companyName');
if(selected == "") {
f_name.style.visibility = 'hidden';
s_name.style.visibility = 'hidden';
c_name.style.visibility = 'hidden';
f_name.value = "";
s_name.value = "";
c_name.value = "";
}
if(selected == "nonCorp") {
f_name.style.visibility = 'visible';
s_name.style.visibility = 'visible';
c_name.style.visibility = 'hidden';
c_name.value = "";
}
if(selected == "corp") {
f_name.style.visibility = 'hidden';
s_name.style.visibility = 'hidden';
c_name.style.visibility = 'visible';
f_name.value = "";
s_name.value = "";
}
}
The problem I am experiencing is that when I change the option in the select menu the first time, the onchange has no effect. However on the second, third etc etc it seems to be working perfectly fine.
Thank you for taking the time to read my question.
Did you try to add the event in JavaScript ?
var yourSelectElement = document.getElementById('test');
yourSelectElement.onchange = cust_type;
Let see : http://jsfiddle.net/YtuxP/
Do you try to do that ?
Fix:
Instead of directly changing the visibility of the text boxes I wrapped them in separate divs. The code solution is as follows.
HTML:
Customer Type:
<select name="customerType" onchange="cust_type()">
<option value="" selected>Customer Type?</option>
<option value="nonCorp">Customer</option>
<option value="corp">Corporate</option>
</select>
<div id="nonCorpCustDetails" class="custDetails" style="visibility:hidden">
Forename <input type="text" name="forename" id="forename" onchange="submit_check()" />
Surname <input type="text" name="surname" id="surname" onchange="submit_check()" /.
</div>
<div id="corporateCustDetails" class="custDetails" style="visibility:hidden">
Company Name <input type="text" name="companyName" id="companyName" onchange="submit_check()" />
</div>
JS function:
function cust_type() {
var select_drop = document.getElementsByName('customerType');
var selected = select_drop[0].value;
var f_name = document.getElementById('forename');
var s_name = document.getElementById('surname');
var c_name = document.getElementById('companyName');
var nonCorp = document.getElementById('nonCorpCustDetails');
var corp = document.getElementById('corporateCustDetails');
if(selected == "") {
nonCorp.style.visibility = 'hidden';
corp.style.visibility = 'hidden';
f_name.value = "";
s_name.value = "";
c_name.value = "";
}
if(selected == "nonCorp") {
nonCorp.style.visibility = 'visible';
corp.style.visibility = 'hidden';
c_name.value = "";
}
if(selected == "corp") {
nonCorp.style.visibility = 'hidden';
corp.style.visibility = 'visible';
f_name.value = "";
s_name.value = "";
}
}

Categories