UPDATE: The issue was being caused by the button in the HTML, it was a type submit, when it should have been type button. Type submit was resetting the process so all the variables were being set to 0 before being pushed into the array
I made another question earlier about how to select the values of a checked radio input for a user register form. That issue was solved, however, it brought up a new issue.
It seems my code is not saving anything into the new user array, here's the code
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Registro</title>
</head>
<body>
<form>
<label for="txtIdentificacion">Identifación</label>
<input type="text" placeholder="Número de identificación" id="txtIdentificacion" required>
<label for="txtPrimerNombre">Primer Nombre</label>
<input type="text" placeholder="Primer Nombre" id="txtPrimerNombre" required>
<label for="txtSegundoNombre">Segundo Nombre</label>
<input type="text" placeholder="Segundo Nombre" id="txtSegundoNombre">
<label for="txtPrimerApellido">Primer Apellido</label>
<input type="text" placeholder="Primer Apellido" id="txtPrimerApellido" required>
<label for="txtSegundoApellido">Segundo Apellido</label>
<input type="text" placeholder="Segundo Apellido" id="txtSegundoApellido" >
<label for="txtNacionalidad">Nacionalidad</label>
<input type="text" placeholder="Nacionalidad" id="txtNacionalidad" required>
<label for="txtTipoIdentificacion">Tipo de Identificacion</label>
<input type="text" placeholder="Tipo de Identificacion" id="txtTipoIdentificacion" required>
<label for="datFechaNacimiento">Fecha de nacimiento</label>
<input type="date" id="datFechaNacimiento" required>
<label for="">Género:</label>
<label for="rbtFemenino">Femenino</label>
<input type="radio" name="rbtGenero" value="Femenino" id="rbtFemenino" required >
<label for="rbtMasculino">Masculino</label>
<input type="radio" name="rbtGenero" value="Masculino" id="rbtMasculino" required >
<label for="rbtIndefinido">Indefinido</label>
<input type="radio" name="rbtGenero" value="Indefinido" id="rbtIndefinido" required>
<label for="numNumeroTelefonico">Número Telefonico </label>
<input type="number" placeholder="Sin guiones" id="numNumeroTelefonico" required>
<label for="txtNombreUsuario">Nombre de usuario</label>
<input type="text" placeholder="Nombre de usuario" id="txtNombreUsuario" required>
<label for="txtPassword">Contraseña</label>
<input type="password" placeholder="Contraseña" id="txtPassword" required>
<label for="rbtTipoUsuario">Soy un instructor</label>
<input type="radio" name="rbtTipoUsuario" value="Instructor" id="rbtInstructor">
<label for="rbtTipoUsuario">Soy un cliente</label>
<input type="radio" name="rbtTipoUsuario" value="Cliente" id="rbtCliente">
<label for="numEmergencia">Número de emergencia</label>
<input type="number" placeholder="Sin guiones" id="numEmergencia" required>
<button type="submit" class="btnRegistrar" id="btnRegistrar">Registrar</button>
</form>
<script src="js/logicaNegociosRegistro.js"></script>
<script src="js/logicaInterfazRegistro.js"></script>
</body>
</html>
JS
document.querySelector('#btnRegistrar').addEventListener('click', registrarNuevoUsuario);
function registrarNuevoUsuario() {
var aNuevoUsuario = [];
var sIdentificacion = '';
var sPrimerNombre = '';
var sSegundoNombre = '';
var sPrimerApellido = '';
var sSegundoApellido = '';
var sNacionalidad ='';
var sTipoIdentificacion = '';
var sFechaNacimiento = '';
var sGenero = '';
var nNumeroTelefonico = 0;
var sNombreUsuario = '';
var sPassword = '';
var nEdad = 0;
var sTipoUsuario = '';
var nEmergencia = '';
sIdentificacion = document.querySelector('#txtIdentificacion').value;
sPrimerNombre = document.querySelector('#txtPrimerNombre').value;
sSegundoNombre = document.querySelector('#txtSegundoNombre').value;
sPrimerApellido = document.querySelector('#txtPrimerApellido').value;
sSegundoApellido = document.querySelector('#txtSegundoApellido').value;
sNacionalidad = document.querySelector('#txtNacionalidad').value;
sTipoIdentificacion = document.querySelector('#txtTipoIdentificacion').value;
sFechaNacimiento = document.querySelector('#datFechaNacimiento').value;
sGenero = document.querySelector('input[name="rbtGenero"]:checked') ? document.querySelector('input[name="rbtGenero"]:checked').value : '';
nNumeroTelefonico = document.querySelector('#numNumeroTelefonico').value;
sNombreUsuario = document.querySelector('#txtNombreUsuario').value;
sPassword = document.querySelector('#txtPassword').value;
nEdad = calcularEdad();
sTipoUsuario = document.querySelector('input[name="rbtTipoUsuario"]:checked') ? document.querySelector('input[name="rbtUserTipoUsuario"]:checked').value: '';
nEmergencia = document.querySelector('#numEmergencia').value;
aNuevoUsuario.push(sIdentificacion, sPrimerNombre, sSegundoNombre, sPrimerApellido, sSegundoApellido, sNacionalidad, sTipoIdentificacion, sFechaNacimiento, sGenero, nNumeroTelefonico, sNombreUsuario, sPassword, nEdad, sTipoUsuario, nEmergencia );
console.log(aNuevoUsuario);
}
function calcularEdad() {
var fechaHoy = new Date();
var fechaNacimiento = new Date(document.querySelector("#datFechaNacimiento").value);
var edad = fechaHoy.getFullYear() - fechaNacimiento.getFullYear();
var meses = fechaHoy.getMonth() - fechaNacimiento.getMonth();
if (meses < 0 || (meses === 0 && fechaHoy.getDate() < fechaNacimiento.getDate())){
edad--;
}
}
Upon hitting the register button, I get the results of the console log, however, it's showing all the fields as being "" (or undefined, in the case of the nEdad variable) and the length being 15.
So, since it's actually getting the correct length, the push itself is working, but it seems that it's not getting ANY of the updated values.
At first, I thought the issue could be the nEdad variable, but I disabled it via comments and the issue persisted.
The browser's console itself is not showing any error
Any idea about what's going on?
nEdad is showing undefined because calcularEdad() function is not returning anything.
I am getting the correct output with non-null values after adding one attribute to the form tag.
You should declare the array outside the function, when the function is called the array is reassigned
Related
This simple form is part of a larger web app I have created. Both the required attributes and the pattern attributes only work intermittently. Changing the event listener to "submit" rather than "click" makes the form validation work properly, but then I get a blank page when I submit with the proper input formatting.
var v = "userForm"
document.getElementById("clockIn").addEventListener("click", addLine); //CHANGE TO CLICK FOR WORKING PAGE BUT PATTERN WONT WORK
function addLine() {
//e.preventDefault();
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
var jobNumber = document.getElementById("jnum").value;
var process = document.querySelector('input[name="operation"]:checked').value;
var comment = document.getElementById("comment").value;
var timeIn = new Date().toLocaleString();
var info = [firstName, lastName, jobNumber, process, timeIn, comment];
google.script.run.addEntry(info);
document.getElementById("fname").value = "";
document.getElementById("lname").value = "";
document.getElementById("jnum").value = "";
document.getElementById("comment").value = "";
document.querySelector('input[name="operation"]:checked').checked = false;
alert("Submitted");
}
function addEntry(info) {
var ssid = "1E81r5Xy**********************W1o4Q";
var ss = SpreadsheetApp.openById(ssid);
var oj = ss.getSheetByName("Open Jobs");
var FileIterator = DriveApp.getFilesByName("Drawings & Links");
while (FileIterator.hasNext()) {
var file = FileIterator.next();
if (file.getName() == "Drawings & Links") {
// var Sheet = SpreadsheetApp.open(file);
var dlid = file.getId();
}
}
var drawingLinks = SpreadsheetApp.openById(dlid);
var dl = drawingLinks.getSheetByName("Sheet1");
Logger.log(dlid)
oj.appendRow(info);
}
<form id="inputForm">
<h2 class="subHead">
Enter Basic Information
</h2>
<label for="fname" class="form">First name:</label><br><br>
<input type="text" id="fname" name="fname" size="25" style="font-size:25px;" placeholder="John" required><br><br>
<label for="lname" class="form">Last name:</label><br><br>
<input type="text" id="lname" name="lname" size="25" style="font-size:25px;" placeholder="Doe" required><br><br>
<label for="jnum" class="form">Job number:</label><br><br>
<input type="text" id="jnum" name="jnum" size="25" style="font-size:25px;" pattern="[A-Z]-[0-9]{4}" placeholder="A-1234" required><br>
<h2 class="subHead">
Select Operation
</h2>
<div>
<label for="cut" class="form">Cut</label>
<input type="radio" id="cut" name="operation" value="cut" required><br><br>
<label for="drill" class="form">Drill</label>
<input type="radio" id="drill" name="operation" value="drill" required><br><br>
<label for="fitup" class="form">Fit Up</label>
<input type="radio" id="fitup" name="operation" value="fit up" required><br><br>
<label for="weld" class="form">Weld</label>
<input type="radio" id="weld" name="operation" value="weld" required><br>
</div>
<h2 class="subHead">
Enter Comments
</h2>
<input type="text" id="comment" size="25" style="font-size:25px;" placeholder="Optional"><br>
<br>
<input type="submit" id="clockIn" class="button" value="Clock In">
</form>
Thanks for the help.
I think I have narrowed the problem down to something to do with the event listener. My thought is that when the "click" event is used, the function runs before the fields are validated by the browser. Yet, I just get a blank page if I use the "submit" event. The function "addEntry" doesn't appear to run; the logged data doesn't appear. Same goes for "addLine" when I add an alert. I have isolated the regex code and verified it works as expected.
Edit: I found that when I remove the event listener on the submit button and add an onsubmit (onsubmit="addLine()") attribute to the form, the alert in "addLine" appears. The "Submitted" alert also appears. Still a blank page after.
Your validation fails but that is outside the scope of the question as I see it since you need to check the actual values before you let it submit and probably need a preventDefault() on the form if any fail.
You get an error because you cannot filter by :checked unless you then determine if that is null OR filter it after you get the nodeList.
Here I show a couple of ways to handle the radio buttons; up to you to determine which suits you.
var v = "userForm"
document.getElementById("clockIn").addEventListener("click", addLine); //CHANGE TO CLICK FOR WORKING PAGE BUT PATTERN WONT WORK
function addLine() {
//e.preventDefault();
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
var jobNumber = document.getElementById("jnum").value;
//demonstrate a few ways to hanlde the radio buttons:
const procOne = document.querySelector('input[name="operation"]:checked');
console.log(!!procOne ? procOne.value : procOne, typeof procOne); // null and object if none are checked
let processValue = procOne === null && typeof procOne === "object" ? "" : procOne.value;
// querySelectorAll to get all of them so we can filter the list
const processAll = document.querySelectorAll('input[name="operation"]');
// creates an array like object of the nodelist; then filters it for checked ones
const checkProcess = [...processAll].filter(item => item.checked);
console.log("How many?:", processAll.length);
console.log("How many checked?:", checkProcess.length);
console.log(checkProcess.length ? checkProcess.value : "nothing");
// anther way to get value:
processValue = checkProcess.length ? checkProcess.value : "nothing"
if (checkProcess.length !== 0) { //Test if something was checked
console.log(checkProcess.value); // the value of the checked.
} else {
console.log('Nothing checked'); // nothing was checked.
}
var comment = document.getElementById("comment").value;
var timeIn = new Date().toLocaleString();
let process = processValue;
var info = [firstName, lastName, jobNumber, process, timeIn, comment];
//ccommented out as google is not defined
//google.script.run.addEntry(info);
// hitting the DOM again is not a great thing here but left as not part of the question/issue
document.getElementById("fname").value = "";
document.getElementById("lname").value = "";
document.getElementById("jnum").value = "";
document.getElementById("comment").value = "";
// cannot filter by :checked if none are so check first and set to false
if (procOne != null) procOne.checked = false;
alert("Submitted");
}
function addEntry(info) {
var ssid = "1E81r5Xy**********************W1o4Q";
var ss = SpreadsheetApp.openById(ssid);
var oj = ss.getSheetByName("Open Jobs");
var FileIterator = DriveApp.getFilesByName("Drawings & Links");
while (FileIterator.hasNext()) {
var file = FileIterator.next();
if (file.getName() == "Drawings & Links") {
// var Sheet = SpreadsheetApp.open(file);
var dlid = file.getId();
}
}
var drawingLinks = SpreadsheetApp.openById(dlid);
var dl = drawingLinks.getSheetByName("Sheet1");
Logger.log(dlid)
oj.appendRow(info);
}
<form id="inputForm">
<h2 class="subHead">
Enter Basic Information
</h2>
<label for="fname" class="form">First name:</label><br><br>
<input type="text" id="fname" name="fname" size="25" style="font-size:25px;" placeholder="John" required><br><br>
<label for="lname" class="form">Last name:</label><br><br>
<input type="text" id="lname" name="lname" size="25" style="font-size:25px;" placeholder="Doe" required><br><br>
<label for="jnum" class="form">Job number:</label><br><br>
<input type="text" id="jnum" name="jnum" size="25" style="font-size:25px;" pattern="[A-Z]-[0-9]{4}" placeholder="A-1234" required><br>
<h2 class="subHead">
Select Operation
</h2>
<div>
<label for="cut" class="form">Cut</label>
<input type="radio" id="cut" name="operation" value="cut" required><br><br>
<label for="drill" class="form">Drill</label>
<input type="radio" id="drill" name="operation" value="drill" required><br><br>
<label for="fitup" class="form">Fit Up</label>
<input type="radio" id="fitup" name="operation" value="fit up" required><br><br>
<label for="weld" class="form">Weld</label>
<input type="radio" id="weld" name="operation" value="weld" required><br>
</div>
<h2 class="subHead">
Enter Comments
</h2>
<input type="text" id="comment" size="25" style="font-size:25px;" placeholder="Optional"><br>
<br>
<input type="submit" id="clockIn" class="button" value="Clock In">
</form>
I am trying to create a form that the submit btn is disabled untill all (except for one) of the fields are filled.
this is the html:
<section id="contacSection">
<form id="contactForm">
<fieldset id="contactSection">
<legend>Your contact information</legend>
<label for="FirstName">First Name</label>
<input type="text" id="FirstName" name="FirstName" placeholder="First Name" required>
<label for="LastName">Last Name</label>
<input type="text" id="LastName" name="LastName" placeholder="Last Name">
<label for="email">E-mail</label>
<input type="email" id="email" name="email" placeholder="example#gmail.com" required>
<label for="comments">Comment</label>
<textarea type="text" id="comments" name="comments" placeholder="Don't be shy, drop a comment here!" required></textarea>
</fieldset>
<fieldset>
<legend>Would you like to meet for?</legend>
<div class="radiobtn">
<input type="radio" id="meetingtype1" name=meetingtype value="coffee" checked> A coffee</input>
<input type="radio" id="meetingtype2" name=meetingtype value="zoom"> A zoom meeting</input>
<input type="radio" id="meetingtype3" name=meetingtype value="drive"> A drive to Eilat</input>
<input type="radio" id="meetingtype4" name=meetingtype value="chef"> A chef meal</input>
</div>
</fieldset>
<button id="submitform" type="submit" >Submit</button>
</form>
</section>
this is the js:
const firstName = document.querySelector('#FirstName');
const lastName = document.querySelector('#LastName');
const email = document.querySelector('#email');
const comments = document.querySelector('#comments');
const submitform = document.querySelector('#submitform');
const contactForm = document.querySelector('#contactForm');
submitform.disabled = true;
contactForm.addEventListener('keyup', function (){
var ins = document.getElementsByTagName("INPUT");
var txs = document.getElementsByTagName("TEXTAREA");
var filled = true;
for(var i = 0; i < txs.length; i++){
if(txs[i].value === "")
filled = false;
}
for(var j = 0; j < ins.length; j++){
if(ins[j].value === "")
filled = false;
}
submitform.disabled = filled;
});
first, it takes a few seconds until the btn becomes disabled. secondly, after I fill any field the btn becomes enabled.
thank you!
Disregarding the comments and the radio buttons and focusing on the main issue, try changing the second half of the code to:
submitform.disabled = true;
contactForm.addEventListener('keyup', function() {
var ins = document.getElementsByTagName("INPUT");
filled = []
for (var j = 0; j < ins.length; j++) {
if (ins[j].value === "")
filled.push(false);
else {
filled.push(true)
}
}
if (filled.includes(false) === false) {
submitform.disabled = false
};
});
and see if it works.
The reason it becomes enabled when you input something is because you are setting
submitform.disabled = filled
At the start, filled is set to true which is why the button is disabled. However, once you type something in any input, you set filled to false which enables the button (submitform.disabled = false).
There's a lot of ways to go about this but here's one. It increments a counter when ever something is filled in. Then you check if that counter is the same as the amount of inputs and textareas.
Secondly, we set the button to be disabled at the very start so even if you remove text from an input, the button will be disabled again if it wasn't
const firstName = document.querySelector('#FirstName');
const lastName = document.querySelector('#LastName');
const email = document.querySelector('#email');
const comments = document.querySelector('#comments');
const submitform = document.querySelector('#submitform');
const contactForm = document.querySelector('#contactForm');
submitform.disabled = true;
contactForm.addEventListener('keyup', function (){
var ins = document.getElementsByTagName("INPUT");
var txs = document.getElementsByTagName("TEXTAREA");
var amountFilled = 0
submitform.disabled = true
for(var i = 0; i < txs.length; i++){
if(txs[i].value !== "") {
amountFilled += 1
}
}
for(var j = 0; j < ins.length; j++){
if(ins[j].value !== "") {
amountFilled += 1
}
}
if (amountFilled === ins.length + txs.length) {
submitform.disabled = false
}
});
<section id="contacSection">
<form id="contactForm">
<fieldset id="contactSection">
<legend>Your contact information</legend>
<label for="FirstName">First Name</label>
<input type="text" id="FirstName" name="FirstName" placeholder="First Name" required>
<label for="LastName">Last Name</label>
<input type="text" id="LastName" name="LastName" placeholder="Last Name">
<label for="email">E-mail</label>
<input type="email" id="email" name="email" placeholder="example#gmail.com" required>
<label for="comments">Comment</label>
<textarea type="text" id="comments" name="comments" placeholder="Don't be shy, drop a comment here!" required></textarea>
</fieldset>
<fieldset>
<legend>Would you like to meet for?</legend>
<div class="radiobtn">
<input type="radio" id="meetingtype1" name=meetingtype value="coffee" checked> A coffee</input>
<input type="radio" id="meetingtype2" name=meetingtype value="zoom"> A zoom meeting</input>
<input type="radio" id="meetingtype3" name=meetingtype value="drive"> A drive to Eilat</input>
<input type="radio" id="meetingtype4" name=meetingtype value="chef"> A chef meal</input>
</div>
</fieldset>
<button id="submitform" type="submit" >Submit</button>
</form>
</section>
In my html form, when users leave blank fields I want to print a message below the fields. At first I tried using empty spans in my html to contain the possible error messages and it worked. But now, I want to generate those empty spans via javascript. The problem comes when I try to print a innerHTML in my empty spans, the console shows me "Can not set property' innerHTML 'of undefined" but variable statusMessageHTML is defined outside both loops so I do not understand why I'm getting this error.
JS
var myForm = document.getElementsByTagName('form')[0];
var formFields = document.getElementsByTagName('label');
myForm.addEventListener('submit', function(){
event.preventDefault();
var statusMessageHTML;
// create empty spans
for(i = 0; i < formFields.length; i++){
statusMessageHTML = document.createElement('span');
statusMessageHTML.className = 'status-field-message';
formFields[i].appendChild(statusMessageHTML);
}
// print a string in empty spans
for(i = 0; i < formFields.length; i++){
statusMessageHTML[i].innerHTML = "Error Message"
}
return false;
});
HTML
<form method="POST" action="form.php">
<label>
<input type="text" name="name" placeholder="Your name*">
</label>
<label>
<input type="text" name="number" placeholder="Your phone number*">
</label>
<label>
<input type="text" name="email" placeholder="Your e-mail*">
</label>
<label>
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="female">Female
</label>
<label>
<textarea name="message" rows="2" placeholder="Your message"></textarea>
</label>
<button type="submit" value="Submit">SUBMIT</button>
</form>
CODEPEN
PD: I want to solve this with pure javascript.
the attribute [i] does not exist on the statusMessageHTML object. That is the reason for the undefined message. If statusMessageHTML[i] is undefined, then you cannot set the innerHTML attribute of something that does not exist.
var myForm = document.getElementsByTagName('form')[0];
var formFields = document.getElementsByTagName('label');
myForm.addEventListener('submit', function(){
event.preventDefault();
var statusMessageHTML;
var elementArray = [];
// create empty spans
for(i = 0; i < formFields.length; i++){
statusMessageHTML = document.createElement('span');
statusMessageHTML.className = 'status-field-message';
formFields[i].appendChild(statusMessageHTML);
elementArray.push(statusMessageHTML);
}
// print a string in empty spans
for(i = 0; i < elementArray.length; i++){
elementArray[i].innerHTML = "Error Message"
}
return false;
});
<form method="POST" action="form.php">
<label>
<input type="text" name="name" placeholder="Your name*">
</label>
<label>
<input type="text" name="number" placeholder="Your phone number*">
</label>
<label>
<input type="text" name="email" placeholder="Your e-mail*">
</label>
<label>
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="female">Female
</label>
<label>
<textarea name="message" rows="2" placeholder="Your message"></textarea>
</label>
<button type="submit" value="Submit">SUBMIT</button>
</form>
statusMessageHTML is treated as element object in the first for loop but in the second loop you are assuming it as an array
// create empty spans
for(i = 0; i < formFields.length; i++){
statusMessageHTML = document.createElement('span');
statusMessageHTML.className = 'status-field-message';
formFields[i].appendChild(statusMessageHTML);
statusMessageHTML.innerHTML = "Error Message"
}
Ok, so I am trying to push the value of an HTML form input to a JavaScript array. When I load the page and submit values through the form, it returns empty strings in the array. I don't understand why this is happening. Thank you for your help.
Relevant HTML:
<form>
<div class="form-group">
<label for="name1">Name: </label>
<input type="text" class="form-control b" id="nameone">
<label for="pref1">Preferences: </label>
<input type="text" class="form-control a" id="prefone"> </div>
<div class="form-group">
<label for="name2">Name: </label>
<input type="text" class="form-control c" id="nametwo">
<label for="pref2">Preferences: </label>
<input type="text" class="form-control a" id="preftwo"> </div>
<div class="form-group">
<label for="name3">Name: </label>
<input type="text" class="form-control d" id="namethree">
<label for="pref3">Preferences: </label>
<input type="text" class="form-control a" id="prefthree"> </div>
<div class="form-group">
<label for="name4">Name: </label>
<input type="text" class="form-control e" id="namefour">
<label for="pref4">Preferences: </label>
<input type="text" class="form-control a" id="preffour"> </div>
<!-- ... -->
<button type="submit" class="btn btn-primary" id="sbm">Submit</button>
</form>
Relevant JavaScript:
var table1 = [];
var table2 = [];
var table3 = [];
var table4 = [];
var names = [];
var pref = [];
// ...
function namesdefine() {
names.push(document.getElementById('nameone').value);
names.push(document.getElementById('nametwo').value);
names.push(document.getElementById('namethree').value);
names.push(document.getElementById('namefour').value);
names.push(document.getElementById('namefive').value);
names.push(document.getElementById('namesix').value);
names.push(document.getElementById('nameseven').value);
names.push(document.getElementById('nameeight').value);
names.push(document.getElementById('namenine').value);
names.push(document.getElementById('nameten').value);
names.push(document.getElementById('nameeleven').value);
names.push(document.getElementById('nametwelve').value);
names.push(document.getElementById('namethirteen').value);
names.push(document.getElementById('namefourteen').value);
names.push(document.getElementById('namefifthteen').value);
names.push(document.getElementById('namesixteen').value);
names.push(document.getElementById('nameseventeen').value);
names.push(document.getElementById('nameeighteen').value);
names.push(document.getElementById('namenineteen').value);
names.push(document.getElementById('nametwenty').value);
names.push(document.getElementById('nametwentyone').value);
names.push(document.getElementById('nametwentytwo').value);
names.push(document.getElementById('nametwentythree').value);
names.push(document.getElementById('nametwentyfour').value);
console.log(names);
var testvar = document.getElementById('nameone').value;
console.log(testvar);
console.log("Look here please");
}
document.getElementById('sbm').onclick = namesdefine();seat(document.getElementsByClassName('a').value);check();changeHTML();
console.log(table1);
console.log(table2);
console.log(table3);
console.log(table4);
console.log("second call");
You're calling the namesdefine() function when you assign to .onclick. You should be assigning the function to .onclick, so leave out the () after it.
document.getElementById('sbm').onclick = namesdefine;
Either use:
document.getElementById('sbm').onclick = namesdefine;
Or
document.getElementById('sbm').addEventListener('click', namesdefine);
If you need to call them all, use this:
document.getElementById('sbm').onclick = function () {
namesdefine();
seat(document.getElementsByClassName('a').value);
check();
changeHTML();
}
And it's always a good practice to check for null after getElementById()
Try to get your data in a loop.
You can use getElementByTagName or getElementByClassName.
var elements = document.getElementsByTagName("input")
for (var i = 0; i < elements.length; i++) {
//Create array here arr.push(elements[i].value);
}
You can call that in your click function.
Hope that helps.
I'm new to JavaScript and I need to use the string method all in one html page. I need to make sure user input the data, but I can't get my function calling to work. Any idea? I finished all of it, but just to make sure that one button submit can validate all string method function perfectly.
This is my HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset ="utf-8"/>
<h1> Try 1</h1>
<p>Please enter all the field below.</p>
</head>
<body>
<form id="myForm">
<fieldset>
<legend>String Methods</legend>
<p>Using concat()</p>
<input type="text" id="word1" size="25" placeholder="Enter first word/sentences."></br>
<input type="text" id="word2" size="25" placeholder="Enter second word/sentences."></br></br>
<p>Using substr()</p>
<input type="text" id="subtr" size="25" placeholder="Please enter word/sentences."></br></br>
<p>Using lastIndexOf()</p>
<input type="text" id="lastindex" size="25" placeholder="Please enter word/sentences."></br>
<input type="text" id="srch" size="25" placeholder="Word that you want to search."></br></br>
<p>Using toLowerCase()</p>
<input type="text" id="lcase" size="35" placeholder="Please enter Uppercase word/sentences."></br></br>
<p>Using toUpperCase()</p>
<input type="text" id="ucase" size="35" placeholder="Please enter Lowercase word/sentences."></br></br>
<p>Using match()</p>
<input type="text" id="match" size="25" placeholder="Please enter word/sentences."></br>
<input type="text" id="match1" size="25" placeholder="Words that you want to find match."></br></br>
<p>Using replace()</p>
<p id="phrase"><i>The voice in my head shouts out through the world like a breath.</i></p>
<input type="text" id="replce" size="35" placeholder="Word you want to change in sentence above."></br>
<input type="text" id="replce2" size="25" placeholder="Word you want to change with."></br></br>
<p>Using split()</p>
<input type="text" id="splt" size="25" placeholder="Please enter word/sentences."></br></br>
<p>Using charCodeAt()</p>
<input type="text" id="cca" size="25" placeholder="Please enter word/sentences."></br></br>
<p>Using slice()</p>
<input type="text" id="slce" size="25" placeholder="Please enter word/sentences."></br></br>
<input type="submit" value="Submit" id="btnSubmit" onclick="validateEverything()">
</fieldset>
</form>
<div id="answers"></div>
</body>
</html>
This is my JavaScript code:
<script>
function validateEverything(){
var wo1 = document.getElementById("word1").value;
var wo2 = document.getElementById("word2").value;
var sub = document.getElementById("subtr").value;
var lin = document.getElementById("lastindex").value;
var sea = document.getElementById("srch").value;
var lca = document.getElementById("lcase").value;
var uca = document.getElementById("ucase").value;
var mat = document.getElementById("match").value;
var ma1 = document.getElementById("match1").value;
var phr = document.getElementById("phrase").value;
var rep = document.getElementById("replce").value;
var re1 = document.getElementById("replce1").value;
var ph1 = document.getElementById("phrase1").value;
var spl = document.getElementById("splt").value;
var cha = document.getElementById("cca").value;
var slc = document.getElementById("slce").value;
var ans = document.getElementById("answers");
//Concat
var con = wo1.concat(" "+wo2);
//Subtr
var subr = sub.substring(1, 7);
//lastindexof
var n = lin.lastIndexOf(sea);
//toLowerCase
var lc = lca.toLowerCase();
//toUpperCase
var uc = uca.toUpperCase();
//match
var mc = mat.match(ma1);
//replace
var rp = phr.replace(replce, replce1);
//split
var sp = sp1.split(" ")
//charCodeAt
var cc = cha.charCodeAt(0);
//slice
var sl = slc.slice(1, 5);
show();
}
function show(){
ans.innerHTML = answersHTML();
}
//answers
function answersHTML(){
var ans = document.getElementById("answers").innerHTML;
document.write(con);
document.write(subr);
document.write(n);
document.write(lc);
document.write(uc);
document.write(mc);
document.write(rp);
document.write(sp);
document.write(cc);
document.write(sl);
}
</script>
There are multiple issues in your snippet.In some case there is no DOM element present but still you are doing document.getElementById();
Also how answerHTML will know about con,sub,.... ? They are local to validateEverything function & you are not passing it to answerHTML function
You are using input type = "submit". You need to use event.preventDefault() to stop submission. You are not submitting anything. Rather use input type = "button"
There is also no use of show() function
Everytime you are using document.write, so it will delete anything which is previously written. Instead string concatenation and innerHTML will be fine.
Here is a working snippet with minimum code.
JS
function validateEverything(event){
event.preventDefault();
var wo1 = document.getElementById("word1").value;
var wo2 = document.getElementById("word2").value;
var sub = document.getElementById("subtr").value;
var ans = document.getElementById("answers");
//Concat
var con = wo1.concat(" "+wo2);
//Subtr
var subr = sub.substring(1, 7);
ans.innerHTML = con+" "+subr;
}
HTML
<input type="submit" value="Submit" id="btnSubmit" onclick="validateEverything(event)">
JSFIDDLE