Setting Checkbox Value in a serialized array in javascript - javascript

I am trying to get the value of a checkbox to store in my database, but my code crashes right after running the serialized array.
Here is the javascript:
$(function () {
$('.form-signin').on('submit', function (e) {
e.preventDefault();
var data = $(this).serializeArray(),
pname = data[0].value,
score = data[1].value,
cheatm = data[2].value;
var GameScore = Parse.Object.extend("GameScore");
var gs = new GameScore();
gs.set("score", parseInt(score));
gs.set("playerName", pname);
gs.set("cheatMode", cheatm === 'true');
gs.set("user", Parse.User.current());
.
.
.
It crashes after cheatm = data[2].value;
Here is the HTML:
<form class="form-signin" role="form">
<h2 class="form-signin-heading" id="login-greeting">Enter Game Score</h2>
<input type="text" name="Player Name" class="form-control" placeholder="Player Name" required="" autofocus="">
<input type="number" name="Score" class="form-control" placeholder="Score" required="">
<input type="checkbox" value = 'true'> Cheat Mode<br>
<button class="btn btn-lg btn-primary btn-block" type="submit">Submit</button>
</form>

You could give the check-box an id and call it in JavaScript like:
HTML:
<input type="checkbox" id="myCheckbox"/>
jQuery:
var isMyCheckboxChecked = $("#myCheckbox").is(":checked");

Related

HTML - Input text pattern/required attributes conflict with submission

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>

400 bad request in graphql

I am trying to insert a new product through a form with javascript into database in grapqhl server and also that product should be displayed in zonaB with javascript ,but i am getting the error 400 bad request. Could someone tell me where is the mistake
here is html code
'''
<form id="formular" action="#" method="POST">
<label>Numar produs:</label>
<input type="text" id="nr">
<label>Denumire produs:</label>
<input type="text" id="nume" ><br>
<label>Categorie produs: </label>
<input type="text" id="categorie"> <br>
<label>Descriere: </label>
<input type="text" id="descriere"><br>
<label>Imagine:</label>
<input type="text" id="imagine"><br>
<label> Pret:</label>
<input type="text" id="pret"><br>
<label> Disponibil:</label>
<input type="text" id="stoc"><br>
<button onmouseover="insereaza1()"> Insereaza</button>
</form>
<script>
var $id = $('#nr').val()
var $name = $('#nume').val()
var $id_categorie = $('#categorie').val()
var $descriere = $('#descriere').val()
var $imagine = $('#imagine').val()
var $pret = $('#pret').val()
var $stoc = $('#stoc').val()
function insereaza1() {
creareProdus={"query":"mutation{createProduct($id:ID!, $name:String, $id_categorie:ID,
$descriere:String, $imagine:String, $pret:Float, $stoc:Boolean){createProduct(id:$id,
name:$name, category_id:$id_categorie, description:$descriere, picture:$imagine,
price:$pret, available:$stoc){product{id }}}}"}
setari={url:"http://localhost:3000",
type:"POST",
data:creareProdus,
contentType:"application/json",
success:vizualizareProdus}
$.ajax(setari)
}
function vizualizareProdus(){
var x = document.getElementById("formular").method
document.getElementById("zonaB").innerHTML = x
}
</script>
</body>
</html>
'''

Launching a new window and filling form values using Javascript

I have been learning JavaScript and i am attempting to launch a new window on click after a user has placed info into a form fields and then placing that info into form fields in the newly launched window. I have read many posts and methods in Stackoverflow however i cant seem to get it to work properly.
Starting page HTML:
<form id="memCat" methed="get" class="member_catalogue">
<button type="submit" class="prodBtn" id="catOrder" onclick="openMemberOrder()"><img class="prodImg" src="../../../Images/bcpot002_thumb.jpg" name="Red Bowl"></button>
<div class="cat_block">
<label class="cat_label" for="cat_name">Product Name:</label>
<input class="cat_input" type="text" id="catID" value="bepot002" readonly>
</div>
<div class="cat_block">
<label class="cat_label" for="cat_description">Product Description:</label>
<input class="cat_input" type="text" id="catDesc" value="Ocre Red Pot" readonly>
</div>
<div class="cat_block">
<label class="cat_label" for="cat_price">Per unit price:$</label>
<input class="cat_input" type="number" id="catVal" value="10" readonly>
</div>
</form>
New page HTML:
<form id="memOrder" method="post">
<div>
<label for="pname">Product Name:</label>
<input type="text" id="orderID" readonly>
</div>
<div>
<label for="pdescription">Product Description:</label>
<input type="text" id="orderDesc" readonly>
</div>
<div>
<label for="quantity">Quantity ordered:</label>
<input type="number" class="quantOrder" id="orderOrder" value="1" min="1" max="10">
</div>
<div>
<label for="ind_price">Per unit price: $</label>
<input type="number" class="quantCount" id="orderVal" readonly>
</div>
<div>
<label for="tot_price">Total Price: $</label>
<input type="number" class="quantCount" id="orderTotal" readonly>
</div>
<div>
<button type="reset">Clear Order</button>
<button type="submit" id="orderCalc">Calculate Total</button>
<button type="submit" id="orderPlace">Place Order</button>
</div>
</form>
Script i have to date:
function openMemberOrder() {
document.getElementById("orderID").value = document.getElementById("catID").document.getElementsByTagName("value");
document.getElementById("orderDesc").value = document.getElementById("catDesc").document.getElementsByTagName("value");
document.getElementById("orderVal").value = document.getElementById("catVal").document.getElementsByTagName("value");
memberOrderWindow = window.open('Member_Orders/members_order.html','_blank','width=1000,height=1000');
};
script and other meta tags in head are correct as other code is working correctly.
So after much trial and error i have had success with this:
On the submission page:
1. I created a button on the page that will capture the input form data
2. i created the localstorage function in JS
3. I then placed the script tag at the bottom of the page before the closing body tag
HTML
<button type="submit" class="prodBtn" id="catOrder" onclick="openMemberOrder()"><img class="prodImg" src="../../../Images/bcpot002/bcpot002_thumb.jpg" name="Red Bowl"></button>
Javascript
var catID = document.getElementById("catID").value;
var catDesc = document.getElementById("catDesc").value;
var catVal = document.getElementById("catVal").value;
function openMemberOrder() {
var memberOrderWindow;
localStorage.setItem("catID", document.getElementById("catID").value);
localStorage.setItem("catDesc", document.getElementById("catDesc").value);
localStorage.setItem("catVal", document.getElementById("catVal").value);
memberOrderWindow = window.open('Member_Orders/members_order.html', '_blank', 'width=1240px,height=1050px,toolbar=no,scrollbars=no,resizable=no');
} ;
Script Tag
<script type="text/javascript" src="../../../JS/catOrder.js"></script>
I then created the new page with the following javascript in the header loading both an image grid as well as input element values:
var urlArray = [];
var urlStart = '<img src=\'../../../../Images/';
var urlMid = '_r';
var urlEnd = '.jpg\'>';
var ID = localStorage.getItem('catID');
for (var rowN=1; rowN<5; rowN++) {
for (var colN = 1; colN < 6; colN++){
urlArray.push(urlStart + ID + '/' + ID + urlMid + rowN + '_c' + colN + urlEnd)
}
}
window.onload = function urlLoad(){
document.getElementById('gridContainer').innerHTML = urlArray;
document.getElementById('orderID').setAttribute('value', localStorage.getItem('catID'));
document.getElementById('orderDesc').setAttribute('value', localStorage.getItem('catDesc'));
document.getElementById('orderVal').setAttribute('value', localStorage.getItem('catVal'));
};
I then created 2 buttons to calculate a total based on inputs and clearing values separately, the script for this was placed at the bottom of the page.
function total() {
var Quantity = document.getElementById('orderQuant').value;
var Value = document.getElementById('orderVal').value;
var Total = Quantity * Value;
document.getElementById('orderTotal').value = Total;
}
function clearForm() {
var i = 0;
var j = 0;
document.getElementById('orderQuant').value = i;
document.getElementById('orderTotal').value = j;
}

Getting elements and values from inside parent div of button click

So I'm still new to JS and jQuery, but I'm trying to learn how to get all the elements and the values inside a div when I click a button inside it.
I was able to get it working for a form when I used FormData to do it. I can't figure out how to do it with a div instead of a form. (I would just use a form, but can't for this unfortunately.)
Here is what I got so far, but I know I'm doing something wrong.
$('button.browsePageImages').on('click', (function(e) {
e.preventDefault();
console.log("Attempting Image Browsing: ");
var myArea = $(this).closest("div");
console.log(myArea);
var myAreaData = new FormData(myArea[0]);
console.log(myAreaData);
var myFormID = $(this).closest("div").attr("id");
console.log(myFormID);
var dataHref = $(this).attr('data-href');
console.log(dataHref);
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12" id="browseImagesDiv">
<h4>Image (Optional) <span></h4>
<input type="text" class="form-control" name="description" value="This is the image description." />
<input type="text" class="form-control" id="areaSection-15" name="image_url" value="" placeholder="Image URL Here"/>
<button type="button" class="btn btn-white btn-xs browsePageImages" data-href="15">Save Image Info</button></span>
</div>
You can use serializeArray for each input.
var myArea = $(this).closest("div").find(':input');
var myAreaData = myArea.serializeArray();
$('button.browsePageImages').on('click', (function(e) {
e.preventDefault();
console.log("Attempting Image Browsing: ");
var myArea = $(this).closest("div").find(':input');
//console.log(myArea);
var myAreaData = myArea.serializeArray();
console.log(myAreaData);
var myFormID = $(this).closest("div").attr("id");
console.log(myFormID);
var dataHref = $(this).attr('data-href');
console.log(dataHref);
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12" id="browseImagesDiv">
<h4>Image (Optional) <span></h4>
<input type="text" class="form-control" name="description" value="This is the image description." />
<input type="text" class="form-control" id="areaSection-15" name="image_url" value="" placeholder="Image URL Here"/>
<button type="button" class="btn btn-white btn-xs browsePageImages" data-href="15">Save Image Info</button></span>
</div>

HTML Form Values don't push to JavaScript array

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.

Categories