I've tried many different methods, and even tried searching on SO. No answer was what I was looking for.
What I want is to have two input buttons that do some things in pure javascript.
Button one: Have it say "Add" when the page loads. When clicked, the value changes to "Cancel." Also, when it's clicked, have it display a form with three fields. When it's clicked again, have the form disappear. One named 'name', the second named 'location', the third named 'type'. I want the user to be able to submit these three things and have them be stored in the code.
Button two: Take the user input from the form and each time the user clicks, it displays all three information values, but have the button act as random generator. Let's say the code has 5 separate entries, I want them to be randomly selected and displayed when the button is clicked.
Like I said, I tried to make this work, but couldn't quite get over the top of where I wanted to go with it. If you want to see my original code, just ask, but I doubt it will be of any assistance.
Thanks in advance.
EDIT: Added the code.
function GetValue() {
var myarray = [];
var random = myarray[Math.floor(Math.random() * myarray.length)];
document.getElementById("message").innerHTML = random;
}
var testObject = {
'name': BWW,
'location': "Sesame Street",
'type': Bar
};
localStorage.setItem('testObject', JSON.stringify(testObject));
var retrievedObject = localStorage.getItem('testObject');
function change() {
var elem = document.getElementById("btnAdd1");
if (elem.value == "Add Spot") {
elem.value = "Cancel";
} else elem.value = "Add Spot";
}
window.onload = function() {
var button = document.getElementById('btnAdd1');
button.onclick = function show() {
var div = document.getElementById('order');
if (div.style.display !== 'none') {
div.style.display = 'none';
} else {
div.style.display = 'block';
}
};
};
<section>
<input type="button" id="btnChoose" value="Random Spot" onclick="GetValue();" />
<p id="message"></p>
<input type="button" id="btnAdd1" value="Add Spot" onclick="change();" />
<div class="form"></div>
<form id="order" style="display:none;">
<input type="text" name="name" placeholder="Name of Resturant" required="required" autocomplete="on" />
<input type="text" name="type" placeholder="Type of Food" required="required" autocomplete="off" />
<input type="text" name="location" placeholder="Location" required="required" autocomplete="off" />
<input type="submit" value="Add Spot" />
</form>
</div>
</section>
The randomizer works, and so does the appear/hide form. Only thing is storing the input and switching the input value.
Here's one way to do this. Each form submission is stored as an object in an array. The random button randomly selects an item from the array and displays it below.
HTML:
<section>
<input type="button" id="btnChoose" value="Random Spot" />
<p id="message"></p>
<input type="button" id="btnAdd1" value="Add Spot" />
<div class="form">
<form id="order" style="display:none;">
<input id="orderName" type="text" name="name" placeholder="Name of Resturant" required="required" autocomplete="on" />
<input id="orderType" type="text" name="type" placeholder="Type of Food" required="required" autocomplete="off" />
<input id="orderLocation" type="text" name="location" placeholder="Location" required="required" autocomplete="off" />
<input type="submit" value="Add Spot" />
</form>
</div>
</section>
<div id="randomName"></div>
<div id="randomLocation"></div>
<div id="randomType"></div>
JS:
var formData = [];
var formSubmission = function(name, location, type) {
this.name = name;
this.location = location;
this.type = type;
}
var spotName = document.getElementById("orderName"),
spotLocation = document.getElementById("orderLocation"),
spotType = document.getElementById("orderType");
var addClick = function() {
if (this.value === 'Add Spot') {
this.value = "Cancel";
document.getElementById('order').style.display = 'block';
}
else {
this.value = 'Add Spot';
document.getElementById('order').style.display = 'none';
}
}
document.getElementById("btnAdd1").onclick = addClick;
document.getElementById('order').onsubmit = function(e) {
e.preventDefault();
var submission = new formSubmission(spotName.value, spotLocation.value, spotType.value);
formData.push(submission);
submission = '';
document.getElementById('btnAdd1').value = 'Add Spot';
document.getElementById('order').style.display = 'none';
this.reset();
}
var randomValue;
document.getElementById('btnChoose').onclick = function() {
randomValue = formData[Math.floor(Math.random()*formData.length)];
document.getElementById('randomName').innerHTML = randomValue.name;
document.getElementById('randomLocation').innerHTML = randomValue.location;
document.getElementById('randomType').innerHTML = randomValue.type;
}
I was working on something since you first posted, and here is my take on it:
HTML:
<section>
<p id="message">
<div id="name"></div>
<div id="location"></div>
<div id="type"></div>
</p>
<input type="button" id="btnAdd" value="Add" onclick="doAdd(this);" />
<input type="button" id="btnShow" value="Show" onclick="doShow(this);" />
<div class="form">
<script id="myRowTemplate" type="text/template">
<input type="text" name="name" placeholder="Name of Resturant" required="required" autocomplete="on" onchange="onChanged(this, {{i}})" />
<input type="text" name="type" placeholder="Type of Food" required="required" autocomplete="off" onchange="onChanged(this, {{i}})" />
<input type="text" name="location" placeholder="Location" required="required" autocomplete="off" onchange="onChanged(this, {{i}})" />
</script>
<form id="order" style="display:none;">
<div id="formItems">
</div>
<input type="button" value="Add Spot" onclick="addSpot()" />
</form>
</div>
</section>
JS:
function GetValue() {
if (enteredItems.length) {
var entry = enteredItems[Math.floor(Math.random() * enteredItems.length)];
document.getElementById("name").innerHTML = entry.name;
document.getElementById("location").innerHTML = entry.location;
document.getElementById("type").innerHTML = entry.type;
}
}
function doAdd(elem) {
switch (elem.value) {
case "Add":
document.getElementById('order').style.display = "";
elem.value = "Cancel";
break;
case "Cancel":
document.getElementById('order').style.display = "none";
elem.value = "Add";
break;
}
}
function doShow(elem) {
GetValue();
}
function addSpot(index) { // (note: here, index is only for loading for the first time)
if (index == undefined) index = enteredItems.length;
var newRowDiv = document.createElement("div");
newRowDiv.innerHTML = document.getElementById("myRowTemplate").innerHTML.replace(/{{i}}/g, index); // (this updates the template with the entry in the array it belongs)
if (enteredItems[index] == undefined)
enteredItems[index] = { name: "", location: "", type: "" }; // (create new entry)
else {debugger;
newRowDiv.children[0].value = enteredItems[index].name;
newRowDiv.children[1].value = enteredItems[index].location;
newRowDiv.children[2].value = enteredItems[index].type;
}
document.getElementById("formItems").appendChild(newRowDiv);
}
function onChanged(elem, index) {
enteredItems[index][elem.name] = elem.value;
localStorage.setItem('enteredItems', JSON.stringify(enteredItems)); // (save each time
}
// update the UI with any saved items
var enteredItems = [];
window.addEventListener("load", function() {
var retrievedObject = localStorage.getItem('enteredItems');
if (retrievedObject)
enteredItems = retrievedObject = JSON.parse(retrievedObject);
for (var i = 0; i < enteredItems.length; ++i)
addSpot(i);
});
https://jsfiddle.net/k1vp8dqn/
It took me a bit longer because I noticed you were trying to save the items, so I whipped up something that you can play with to suit your needs.
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 created a script which exports a CSV from Google Sheets. This CSV is exported to a Drive folder, and I initially placed an ID in the code using var folder = DriveApp.getFolderById("ID goes here");
Now, I want to make the export location dynamic for my users. I also want them to select the frequency of automated exports. I created an html file and call a dialog box up for users to input their desired ID and frequency.
function openFolderForm() {
var html = HtmlService.createHtmlOutputFromFile('html')
.setHeight(525)
.setWidth(800);
SpreadsheetApp.getUi().showModalDialog(html, 'Export Settings');
}
In the html file, I have..
<form id="form">
<div class="block form-group">
<input type='text' name='IDdrive' id="IDdrive" style="width: 300px;"/>
</div>
<br>
<p>Frequency?</p>
<div>
<input type="radio" name="radio" id="radioDaily">
<label for="radioDaily">Daily</label>
</div>
<div>
<input type="radio" name="radio" id="radioWeekly">
<label for="radioWeekly">Weekly</label>
</div>
<button type = "submit" class = "action"
onClick="google.script.run.updateSettings();">Submit</button>
</form>
Finally, in my code I have...
function updateSettings(form) {
var formQ1 = form.IDdrive;
if (form.radioDaily == true) { var formQ2 = 1; } else { var formQ2 = 7}
};
function exportCSV() {
var changelogSheetName = "data";
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
var tab = ss.getSheetByName('data');
var folder = DriveApp.getFolderById(formQ1); //putting in dynamic form
etc etc etc
function createTimeTrigger() {
ScriptApp.newTrigger("exportCSV")
.timeBased()
.atHour(3)
.inTimezone("America/Los_Angeles")
.everyDays(formQ2) //input radio variable answer here
.create();
}
};
However, my code is not working. The variables for the form answers are not passing to client side successfully. The code does work if I put in the ID directly.
I realize that this has been asked in various forms already on this site, but I have read most of those threads and have still been unable to resolve. Could someone help out of Scripts App newbie please? :)
Full code below, starting with .gs :
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ui = SpreadsheetApp.getUi();
ui.createMenu('Scripts')
.addItem('Export CSV', 'exportCSV')
.addItem('Update export settings', 'openFolderForm')
.addToUi();
}
function openFolderForm() {
var html = HtmlService.createHtmlOutputFromFile('html').setHeight(525).setWidth(800);
SpreadsheetApp.getUi().showModalDialog(html, 'Export Settings');
}
function updateSettings(form) {
var formQ1 = form.IDdrive;
if (form.radioDaily == true) { var formQ2 = 1; } else { var formQ2 = 7};
google.script.host.close();
};
function exportCSV() {
var changelogSheetName = "data";
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
var tab = ss.getSheetByName('data');
var folder = DriveApp.getFolderById(formQ1);
//export code here
}
function convertRangeToCsvFile_(csvFileName, sheet) {
var activeRange = sheet.getDataRange();
try {
var data = activeRange.getValues();
var csvFile = undefined;
if (data.length > 1) {
var csv = "";
for (var row = 0; row < data.length; row++) {
for (var col = 0; col < data[row].length; col++) {
if (data[row][col].toString().indexOf(",") != -1) {
data[row][col] = "\"" + data[row][col] + "\"";
}
}
if (row < data.length-1) {
csv += data[row].join(",") + "\r\n";
}
else {
csv += data[row];
}
}
csvFile = csv;
}
return csvFile;
}
catch(err) {
Logger.log(err);
Browser.msgBox(err);
}
}
function createTrigger() {
ScriptApp.newTrigger('exportCSV')
.timeBased()
.atHour(3)
.everyDays(formQ2) //radio question here
.inTimezone("America/Los_Angeles")
.create();
and HTML full...
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<title><b>Output Folder</b></title>
</head>
<body>
<p>Enter the ID of your output folder. A Drive ID is made up by the characters after the last /folder/ in the URL</p>
<form id="form">
<div class="block form-group">
<input type='text' name='IDdrive' id="IDdrive" style="width: 300px;"/>
</div>
<div>
<input type="radio" name="radio" id="radioDaily"> <label for="radioDaily">Daily</label>
</div>
<div>
<input type="radio" name="radio" id="radioWeekly"> <label for="radioWeekly">Weekly</label>
</div>
<br>
<div class="inline form-group">
<input type="button" value="Submit" class="action" onClick="google.script.run.updateSettings();" /> //or "google.script.run.updateSettings(this.parentNode);"
<input type="button" value="Cancel" class="cancel" onClick="google.script.host.close();" />
</div>
<br>
</form>
</body>
</html>
Your not passing anything to updateSettings google.script.run.updateSettings();>
I would do it like this:
<input type = "button" value="Submit" onClick="google.script.run.updateSettings(this.parentNode);" />
I'm running this as a dialog and it runs okay now. I added values to the radio buttons and now the weekly one returns 'weekly' and the daily one returns 'daily' and the IDdrive returns a string.
gs:
function openFolderForm() { SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('ah1').setHeight(525).setWidth(800), 'Export Settings');
}
function updateSettings(form) {
console.log(form)
var formQ1=form.IDdrive;
if (form.radioDaily == true) { var formQ2 = 1; } else { var formQ2 = 7}
}
function exportCSV() {
var changelogSheetName = "data";
var ss=SpreadsheetApp.getActive();
var sheets=ss.getSheets();
var tab=ss.getSheetByName('data');
var folder=DriveApp.getFolderById(formQ1);
}
html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<title><b>Output Folder</b></title>
</head>
<body>
<p>Enter the ID of your output folder. A Drive ID is made up by the characters after the last /folder/ in the URL</p>
<form>
<input type='text' name='IDdrive' id="IDdrive" style="width: 300px;"/><br />
<input type="radio" name="radio" id="radioDaily" value="daily"> <label for="radioDaily">Daily</label><br />
<input type="radio" name="radio" id="radioWeekly" value="weekly"> <label for="radioWeekly">Weekly</label><br />
<input type="button" value="Submit" class="action" onClick="google.script.run.updateSettings(this.parentNode);" />
<input type="button" value="Cancel" class="cancel" onClick="google.script.host.close();" />
</form>
</body>
</html>
Got it to work. The secret was needed to just JSON to properly store the form input criteria.
CODE
function updateSettings(formObject) {
var uiForm = SpreadsheetApp.getUi();
JSON.stringify(formObject);
var formText = formObject.formQ1;
var formRadio = formObject.formQ2;
if (formRadio == "Daily") { var frequency = 1; } else { var frequency = 7};
etc etc
HTML
<form id="myForm" onsubmit="event.preventDefault(); google.script.run.updateSettings(this); google.script.host.close();">
<div>
<input type='text' name='formQ1' id="formQ1" style="width: 300px;"/>
</div>
<div class="inline form-group">
<input type="radio" name="formQ2" id="formQ2" value="Daily" /> <label for="radioDaily">Daily</label>
</div>
<div>
<input type="radio" name="formQ2" id="formQ2" value="Weekly" /> <label for="radioWeekly">Weekly</label>
</div>
<br><br>
<div class="inline form-group">
<input type="submit" value="Submit" style="color:#4285F4"/>
<input type="button" value="Cancel" class="cancel" onClick="google.script.host.close();" />
I have a HTML5 form and I'm using javascript to validate the form.
I have several 'if's checking the form and if it valid they change a variable ('pass') to true or false. They also display an error message. The problem is that even if just one thing is valid it changes the variable is true and I need it to only make pass true if everything else is valid.
My HTML:
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
</head>
<body>
<div>
<form name="register" action="register.php" method="POST" >
<label>First Name:</label>
<input type="text" id="firstName" name="firstName"><br />
<label id="warning_first"></label>
<br />
<label>Surname:</label>
<input type="text" id="lastName" name="lastName"><br />
<label id="warning_second"></label>
<br />
<label>Gender:</label>
<input type="radio" name="gender" value="Male" id="male">Male
<input type="radio" name="gender" value="Female">Female
<input type="radio" name="gender" value="Other">Other
<input type="radio" name="gender" value="Prefer not to say"> Prefer not to say <br />
<label id="warning_third"></label>
<br />
<label>Email:</label>
<input type="email" id="email" name="email"> <br />
<label id="warning_fourth"></label>
<br />
<label>Confirm Email:</label>
<input type="email" id="confirmEmail" name="confirmEmail">
<br />
<label>Mobile:</label>
<input type="tel" id="mobileNumber" name="mobileNumber">
<br />
<label>Telephone:</label>
<input type="tel" id="telephoneNumber" name="telephoneNumber">
<br />
<input type="button" id="cancel" name="cancel" value="Cancel" onclick="cancel();">
<input type="button" name="submit" value="Register" onclick="submitCheck();">
</form>
<script src="script.js"></script>
</div>
</body>
</html>
My JavaScript:
function submitCheck() {
var pass = false;
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var genderTest = document.getElementsByName("gender");
var genderIf = false;
for (var a = 0; a < genderTest.length; a += 1) {
if (genderTest[a].checked) {
genderIf = true;
}
}
var emailCheck = document.getElementById("email").value;
if (firstName.length > 0) {
document.getElementById("warning_first").innerHTML = "";
pass = true;
} else {
document.getElementById("warning_first").innerHTML = "This is required!";
pass = false;
}
if (lastName.length > 0) {
document.getElementById("warning_second").innerHTML = "";
pass = true;
} else {
document.getElementById("warning_second").innerHTML = "This is required!";
pass = false;
}
if (genderIf) {
document.getElementById("warning_third").innerHTML = "";
pass = true;
} else {
document.getElementById("warning_third").innerHTML = "This is required!"
pass = false;
}
if (emailCheck.length > 0) {
document.getElementById("warning_fourth").innerHTML = "";
pass = true;
} else {
document.getElementById("warning_fourth").innerHTML = "Your email is too short!";
pass = false;
}
if (pass) {
console.log("OK");
} else {
console.log("NO");
}
}
As you can see, if the email is true, the console will log "OK" (which I am using to see if everything is valid"). How can I solve this so that it doesn't 'pass' to true if just the email is valid?
I am using a normal button instead of a submit button because of issues with the #onsubmit.
At the moment, you default pass to false and change it to true if any element passes the test.
Reverse your logic.
Set the default value of pass to true. Change it to false if any element fails its test.
Its simple, at the start of your code change your pass variable to have a value of 1 like so:
var pass = 1;
Now change the line of code in your IF statements where you have your pass variable. For a true condition set to this:
pass *= 1;
And for a false condition to this
pass *= 0;
This ensures that unless all IF conditions are satisfied your pass variable will not return a true state.
I have a form in HTML and that if the fields are left blank, the Javascript will print inside the fields error. Please can some one give me a piece of code that will validate the form and then will print Error on top of the form if its left blank and not inside the fields of the form?
My Form:
<form id="contact" onsubmit="checkContactForm(); return false;" onreset="resetForm();">
<p>Fill in the form below to send me a message!</p>
<div id="errormessage"></div>
<p>
<label for=""> </label>
<input type="text" name="" id="" onfocus="" />
<p>
<label for="name">Name:</label>
<input type="text" name="name" id="name" onfocus="resetField(this);" />
</p>
<p>
<label for="email">E-mail address:</label>
<input type="text" name="email" id="email" onfocus="resetField(this);" />
</p>
<p>
<label for="message">Your Message:</label>
<textarea name="message" id="message" rows="5" cols="25" onfocus="resetField(this);"></textarea>
</p>
<p>
<button type="submit">Send Message</button>
<button type="reset">Reset Form</button>
</p>
My Javascript:
var requiredFields = ["name", "email", "message"];
function checkContactForm() {
var myForm = document.forms[0];
for (i in requiredFields) {
fieldName = requiredFields[i];
if (!myForm[fieldName].value || myForm[fieldName].value == "Error") {
myForm[fieldName].style.color = "#f66";
myForm[fieldName].value = "";
var emptyFields = true;
}
}
if (!emptyFields) { myForm.submit(); }
}
function resetField(myField) {
if (myField.value == "Error") {
myField.style.color = "#000";
myField.value = "";
}
}
function resetForm(myForm) {
var myForm = document.forms[0];
for (i in requiredFields) {
fieldName = requiredFields[i];
myForm[fieldName].style.color = "#000";
}
}
Since HTML5 there is a form-validation API (http://www.w3schools.com/js/js_form_validation.asp)
Here you can find a pretty good "tutorial": http://www.smashingmagazine.com/2009/07/07/web-form-validation-best-practices-and-tutorials/
If I've understand you want the error will be printed in the #errormessage div, right?
If so you can simply do something like this:
function addError(str){
document.getElementById("errormessage").innnerHTML = document.getElementById("errormessage").innerHTML + str + "<br>";
}
function checkContactForm() {
var myForm = document.forms[0];
for (i in requiredFields) {
fieldName = requiredFields[i];
if (!myForm[fieldName].value || myForm[fieldName].value == "Error") {
myForm[fieldName].style.color = "#f66";
myForm[fieldName].value = "";
var emptyFields = true;
addError(fiedlName+" is empty!");
}
}
if (!emptyFields) { myForm.submit(); }
}
hi i am using javascript function to balnk ma textboxes when its clicked, initially the text boxes contain their respective label names, eg: Client Name, Company etc. When the text box is clicked it makes the text box empty so data can be types. for this i am using a javascript function and for each textbox i have to have a seperate function, can anyone tell me how i can combine all these function, the only different thing in each function is the value used in the textbox and the textbox name.
The Javascript function
function clientnameclear() {
if(document.bunkerfrm.clientname.value=="Client Name") {
var bunkerfrm = document.bunkerfrm.clientname.value="";
var bunkerfrm = document.bunkerfrm.clientname.focus();
}
else {
var bunkerfrm = document.bunkerfrm.clientname.focus();
}
}
function clientnamereset() {
if(document.bunkerfrm.clientname.value=="") {
var bunkerfrm = document.bunkerfrm.clientname.value="Client Name";
}
}
function vesselnameclear() {
if(document.bunkerfrm.vesselname.value=="Vessel Name") {
var bunkerfrm = document.bunkerfrm.vesselname.value="";
var bunkerfrm = document.bunkerfrm.vesselname.focus();
}
else {
var bunkerfrm = document.bunkerfrm.vesselname.focus();
}
}
function vesselnamereset() {
if(document.bunkerfrm.vesselname.value=="") {
var bunkerfrm = document.bunkerfrm.vesselname.value="Vessel Name";
}
}
function compclear() {
if(document.bunkerfrm.company.value=="Company") {
var bunkerfrm = document.bunkerfrm.company.value="";
var bunkerfrm = document.bunkerfrm.company.focus();
}
else {
var bunkerfrm = document.bunkerfrm.company.focus();
}
}
function compreset() {
if(document.bunkerfrm.company.value=="") {
var bunkerfrm = document.bunkerfrm.company.value="Company";
}
}
The Html Code is
<form name="bunkerfrm" id="bunkerfrm" action="#" method="post"><br>
<input type="text" name="clientname" class="txtbox" value="Client Name" onmousedown="clientnameclear()" onclick="clientnameclear()" onblur="clientnamereset()" />
<br /><br>
<input type="text" name="company" class="txtbox" value="Company" onmousedown="compclear()" onclick="compclear()" onblur="compreset()" />
<br /><br>
<input type="submit" name="submitting" class="bunksubmit" value="Send Your Inquiry" /><br>
</form>
First, store the default values somewhere, such as the alt of the given input.
<form name="bunkerfrm" id="bunkerfrm" action="#" method="post"><br>
<input type="text" name="clientname" alt="Client Name" class="txtbox" value="Client Name" onfocus="clear_text(this);" onblur="reset_text(this);" />
<br /><br>
<input type="text" name="company" class="txtbox" alt="Company" value="Company" onfocus="clear_text(this);" onblur="reset_text(this);" />
<br /><br>
<input type="submit" name="submitting" class="bunksubmit" value="Send Your Inquiry" /><br>
</form>
Then pass the input element this as the parameter to these onfocus/onblur functions:
function clear_text(elem)
{
if (elem.value == elem.alt)
elem.value = "";
}
function reset_text(elem)
{
if (elem.value == "")
elem.value = elem.alt;
}
Which will clear the input when it gets focus if its value is the same as the placeholder stored in the alt attribute. The event onblur will trigger the reset_text function which will check if the value is empty and restore it to the default placeholder stored in the alt attribute.
Use placeholder:
<input type="text" name="clientname" placeholder="Client Name" class="txtbox" />
<br /><br>
<input type="text" name="company" class="txtbox" placeholder="Company" />
<br /><br>
<input type="submit" name="submitting" class="bunksubmit" placeholder="Send Your Inquiry" /><br>
</form>
I suggest you use and/or study existing libraries, such as:
In-Field http://fuelyourcoding.com/scripts/infield/
ClearField http://labs.thesedays.com/projects/jquery/clearfield/