Saving the value of a checkbox in an array when clicked (jQuery) - html

I'm trying to make a joke generator. The user can choose between Programming, Miscellaneous and Dark jokes (or two / all of them but cannot choose none). Right now, for my Javascript and HTML, I have this:
$("#first-input").val("Programming");
$("#middle-input").val("Miscellaneous");
$("#bottom-input").val("Dark");
let checkboxes = $(".content-top input[type=checkbox]");
let submitButton = $("button[type=submit]");
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Joke</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<form action="/joke" method="POST">
<div class="section">
<label><span>*</span> Select a category / categories:</label>
<div class="content content-top">
<input type="checkbox" name="category" id="first-input">
<h5>Programming</h5>
<br>
<input type="checkbox" name="category" id="middle-input">
<h5>Miscellaneous</h5>
<br>
<input type="checkbox" name="category" id="bottom-input">
<h5>Dark Jokes</h5>
</div>
</div>
<button type="submit">Generate Joke</button>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>
The HTML I have right now are three checkboxes with the same name attribute, but with different values set (values were set in Javascript above). How do I use jQuery to make it so that once the submit button is clicked, there is an array, and the items in the array are the ones the user checked?
So for example:
If the user selects the "Programming", "Miscellaneous" and "Dark" check boxes, the array would have the 3 items (the three items would be "Programming", "Miscellaneous" and "Dark"). Then if the user proceeds to uncheck the "Dark" checkbox (so now only the "Programming" and "Miscellaneous" checkboxes are checked), the array would also remove the "Dark" item and would now only have 2 items.
I've been trying a lot of things and searching on Google, and tried using "input:checked", is(), etc. but I couldn't figure out how to get it to work.
Question:
How do I get an array, and the items in the array are the values of the checkboxes the user checked (e.g. "Programming", "Dark", etc.) with no repeats, and if the user, for example, initially selected all three checkboxes, and then proceeds to uncheck the "Dark" checkbox, the array should also remove "Dark" as one of it's items.
I've been stuck on this for hours and would really appreciate any help, thanks!

First, change your checkboxes to declare their values in the HTML:
<input type="checkbox" name="category" id="first-input" value="programming">
<h5>Programming</h5>
<br>
<input type="checkbox" name="category" id="middle-input" value="miscellaneous">
<h5>Miscellaneous</h5>
<br>
<input type="checkbox" name="category" id="bottom-input" value="dark">
<h5>Dark Jokes</h5>
Add the following onclick attribute to your submit button:
<button type="submit" onclick="submit(event)">Generate Joke</button>
Then add the following script tag after your inclusion of jQuery:
<script type="text/javascript">
window.submit = event => {
event.preventDefault();
let checkedValues = Array.from($('input:checked')).map(input => input.value);
// ... looks like, e.g., ["programming", "miscellaneous"]
// ... do stuff with checkedValues here...
console.log(checkedValues);
};
</script>
I added the event.preventDefault() thing so that the form doesn't actually send anything to the server. It seems like you'll need that if you want to do things in JS first.
The whole thing should look like this:
<form id="form" action="/joke" method="POST">
<div class="section">
<label><span>*</span> Select a category / categories:</label>
<div class="content content-top">
<input type="checkbox" name="category" id="first-input" value="programming">
<h5>Programming</h5>
<br>
<input type="checkbox" name="category" id="middle-input" value="miscellaneous">
<h5>Miscellaneous</h5>
<br>
<input type="checkbox" name="category" id="bottom-input" value="dark">
<h5>Dark Jokes</h5>
</div>
</div>
<button type="submit" onclick="submit(event)">Generate Joke</button>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
window.submit = event => {
event.preventDefault();
let checkedValues = Array.from($('input:checked')).map(input => input.value);
// ... looks like, e.g., ["programming", "miscellaneous"]
// ... do stuff with checkedValues here...
console.log(checkedValues);
};
</script>
I don't think you need those few lines of JS at the top of your question.

Add the value attribute to your inputs then get all checkboxes iterate through them then push the values to the array, the elements in the array will be removed each time you click submit which means you will always get the new values checked by the user pushed to the result array
results = []
let submitButton = $("button[type=submit]");
submitButton.click(function(e) {
var $checkboxes = $('input[name=category]:checked');
e.preventDefault()
results.splice(0,results.length)
$checkboxes.each(function(){
results.push($(this).val())
});
console.log(results)
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Joke</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<form action="/joke" method="POST">
<div class="section">
<label><span>*</span> Select a category / categories:</label>
<div class="content content-top" id="checkb">
<input type="checkbox" name="category" id="first-input" value="Programming">
<h5>Programming</h5>
<br>
<input type="checkbox" name="category" id="middle-input" value="Miscellaneous">
<h5>Miscellaneous</h5>
<br>
<input type="checkbox" name="category" id="bottom-input" value="Dark Jokes">
<h5>Dark Jokes</h5>
</div>
</div>
<button type="submit">Generate Joke</button>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>

I don't do jQuery for years, but if you want to sent an array you have to ending element's names with [] and set a value for each.
here it is in javascript
const DomParser = new DOMParser()
, myForm = document.getElementById('my-form')
;
function newCategory(val)
{
let elm = `<input type="hidden" name="category[]" value="${val}">`
return DomParser.parseFromString( elm, 'text/html').body.firstChild
}
myForm.oninput=()=>
{
while (el=myForm.querySelector('input[name="category[]"]')) el.remove();
myForm.querySelectorAll('input[data-category]:checked').forEach(el=>
{
myForm.appendChild( newCategory( el.dataset.category ) )
})
}
label, button {
display: block;
float: left;
clear: both;
}
button { margin-top: 1em;}
<form id="my-form" action="/joke" method="POST">
<label>
<input type="checkbox" data-category="Programming">
Programming
</label>
<label>
<input type="checkbox" data-category="Miscellaneous">
Miscellaneous
</label>
<label>
<input type="checkbox" data-category="Dark Jokes">
Dark Jokes
</label>
<button type="submit">Generate Joke</button>
</form>

Related

console.log() input value?

Why won't this code just take the input value and console.log() it?
The updated code reads.
!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form class="" action="index.html" method="get">
<h1>thank you</h1>
<a href="index.html">
<button>Home</button>
</a>
<br>
<br>
<a href="https://github.com/shanegibney/link-two-pages">
<button>Back to repositoryy</button>
</a>
<br>
<br>
<form>
<input type="number" id="Idkey" value="5" min="0" max="10">
<button type="submit">submit</button>
</form>
</body>{
<script>
let Idkey = document.getElementById(Idkey).value;
console.log(Idkey);
</script>
</html>
The submit button is not rendering at all.
The error I get is,
settings.html:26 Uncaught TypeError: Cannot read properties of null (reading 'value')
The script will only read the initial value in the input field (it will always log 5).
You need to tell the script to read the input value each time the submit button is clicked by adding the oninput attribute, like this:
<form>
<input type="number" value="5" id="Idkey" oninput="myfunction()" />
</form>
<script>
function myfunction() {
let val = document.getElementById("Idkey").value;
console.log(val);
}
</script>

Adding the 'required' attribute to all input fields which are 'shown' and with a specific class

I have a web form which shows/hides secondary input fields based upon various radio buttons and checkboxes. This show/hide is done using JQuery triggered by a $(".id").on('change', function(){ which them hides all optional fields and show specific ones:
$(".optionalInfo").hide();
$('#releaseRelated').prop('checked', false); // Uncheck the 'Is this Release Related' box.
$('input[name="repIdAvail"]').prop('checked', false); //Uncheck all the 'Is the Report ID available' boxes.
$('.newRepData').show(); // show the new report DIV
etc.
I could add a $(".newReportInput").prop('required',true); for every field, but was wondering if I could add a single line at the end of the function to make all fields with a class of #optionalInfo and an attribute of 'show' as 'required'?
I found this JQuery to change all fields matching 2 attributes : input[id][name$='man']" ).val( "only this one" ); except I want to make all input fields required if they are in a dvi with a class of .optionalInfo and the div has the 'Show' attribute'
New to JQuery, so maybe this is just a bad thing to do.
Edit:
Small web page showing what I want to do:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Request</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<form target="_blank">
<!-- Radio buttons for request type. Subsequent input fields will appear depending upon the request type -->
<input type="radio" required name="type" id="ADD" class="reqType">
<label class="form-check-label" for="ADD">Add new report</label>
<input type="radio" name="type" id="DELETE" class="reqType">
<label class="form-check-label" for="DELETE">Delete report</label>
<!-- 'Add report' fields -->
<div class="optionalInfo newRepData">
<label for="reportId">New Report ID :</label>
<input type="text" name="reportId" id="reportId">
<label for="reportName">New Report Name :</label>
<input type="text" name="reportName" id="reportName">
</div>
<br><br><input type="submit" value="Submit Request">
</form>
<script>
// Hide all optional fields when the page is loaded
$(document).ready(function() {
$(".optionalInfo").hide();
});
// Hide all optional fields when a request type is chosen and then reveal the relevant fields
$(".reqType").on('change', function(){
// hide all of the optional inputs
$(".optionalInfo").hide();
// Show/hide optional fields depending upon the request chosen
switch ($(this).attr('id')) {
case "ADD":
$('.newRepData').show();
break;
case "DELETE":
break;
}
});
</script>
</body>
</html>
When the 'Add' option is chosen, I'd like the 2 fields that switch from 'hide' to 'show' to gain the 'required' tag.
Note - this is just a simple example, as my form is much longer. I had to rollback the edits which added the executable code snippet as these edits changed the nature of the question.
the underlying question is: How to make all visible input fields in a form 'required' after some JS code that hides/shows various input fields.
you can use this:
on click add show newrepdata and add required attribute to inputs, on click delete hide newrepdata and remove required attribute from inputs:
// Hide all optional fields when the page is loaded
$(document).ready(function() {
$(".optionalInfo").hide();
});
// Hide all optional fields when a request type is chosen and then reveal the relevant fields
$(".reqType").on('change', function() {
// hide all of the optional inputs
$(".optionalInfo").hide().children("input").removeAttr("required");
// Show/hide optional fields depending upon the request chosen
switch ($(this).attr('id')) {
case "ADD":
$('.newRepData').show().children("input").attr("required","");
break;
case "DELETE":
break;
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>Request</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<form target="_blank">
<!-- Radio buttons for request type. Subsequent input fields will appear depending upon the request type -->
<input type="radio" required name="type" id="ADD" class="reqType">
<label class="form-check-label" for="ADD">Add new report</label>
<input type="radio" name="type" id="DELETE" class="reqType">
<label class="form-check-label" for="DELETE">Delete report</label>
<!-- 'Add report' fields -->
<div class="optionalInfo newRepData">
<label for="reportId">New Report ID :</label>
<input type="text" name="reportId" id="reportId">
<label for="reportName">New Report Name :</label>
<input type="text" name="reportName" id="reportName">
</div>
<br><br><input type="submit" value="Submit Request">
</form>
</body>
</html>
if I have understood, i set required on input of section shown:
to all div hidden i put off required
$('div.optionalInfo:hidden').find('input').prop("required", false");
to all div visible i set required
$('div.optionalInfo:visible').find('input').prop("required", true");
you could adapt the syntax, for example selector input :
$('div.optionalInfo input:visible').prop("required", true");

onClick on Google Script not working for HTML Form

I'm trying to create a html pop up that will then populate a gsheet. I've basically used the same solution found here. For some strange reason though, it isn't working. When I click the submit button on the HTML pop up box after filling out all the data, it doesn't respond. I click, it doesn't close, append the data, or do anything.
The html pop up is created, but the Submit button doesn't work. I am almost sure that it is has something to do with the onClick method I am using.
Here is the code I am working with:
gs file
function registerCustomer() {
var html = HtmlService.createHtmlOutputFromFile('customerMenu.html').setSandboxMode(HtmlService.SandboxMode.IFRAME);
SpreadsheetApp.getUi()
.showModalDialog(html, 'Add Customer');
}
function customerAdd(customerForm) {
var ss = SpreadsheetApp.getActiveSpreadsheet;
var cus_db = ss.getSheetByName("customer_db");
cus_db.appendRow([" ", customerForm.name_1, customerForm.name_2, customerForm.phone, customerForm.age, customerForm.channel]);
return true;
}
html file
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<br>
<customerForm>
First Name:<br>
<input type="text" name="name_1">
<br>
Second Name:<br>
<input type="text" name="name_2">
<br>
Phone Number:<br>
<input type="text" name="phone">
<br>
Age:<br>
<input type="number" name="age">
<br>
How did they hear about us?:<br>
<input type="text" name="channel">
<br><br>
<input type="submit" value="Add Customer" class ="submit"
onclick="google.script.run
.withSuccessHandler(google.script.host.close)
.customerAdd(this.parentNode)" />
</customerForm>
</html>
I've scoured stackoverflow for almost every solution:
I am running two pop ups so I changed the function names based on the advice here
I tried to use the '''document.forms[0]''' method found here also didn't work
What am I missing?
onClick on Google Script working for HTML Form
GS:
function registerCustomer() {
var html = HtmlService.createHtmlOutputFromFile('ah2')
SpreadsheetApp.getUi().showModelessDialog(html, 'Add Customer');
}
function customerAdd(obj) {
var ss = SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Sheet15');
sh.appendRow(["", obj.name_1, obj.name_2, obj.phone, obj.age, obj.channel]);
return true;
}
html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<body>
<form>
First Name:<br>
<input type="text" name="name_1" />
<br>
Second Name:<br>
<input type="text" name="name_2"/>
<br>
Phone Number:<br>
<input type="text" name="phone"/>
<br>
Age:<br>
<input type="number" name="age"/>
<br>
How did they hear about us?:<br>
<input type="text" name="channel"/>
<br><br>
<input type="button" value="Add Customer" onClick="addCust(this.parentNode);" />
</form>
<script>
function addCust(obj) {
google.script.run
.withSuccessHandler(function(){google.script.host.close();})
.customerAdd(obj);
}
</script>
</body>
</html>

Calculation result not displaying after user input HTML

I'm completing an assignment in HTML where we're supposed to create a page that uses at least one function to perform a mathematical calculation based on user input. I've got the code written below, but when I hit the "calculate" button I've coded in, nothing displays on the screen. Could someone tell me what I'm doing wrong? Here is my code:
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<Title>Goals Against Average Calculator</Title>
<body>
<script src="modernizr.custom.05819.js"></script><!--Links to file containing modernizer library-->
<!-- Navigation -->
<nav>
<ul class="w3-navbar w3-black">
<li>Home</li> <!--Link to Home Page-->
<li>NHL Teams</li><!--Link to Page of NHL Teams-->
<li>AHL Teams</li><!--Link to Page of AHL Teams-->
<li>WHL Teams</li><!--Link to Page of WHL Teams-->
<li>G.A.A. Calculator</li><!--Link to Page of WHL Teams-->
</ul>
</nav>
<header>
<h1 style="text-align:center;">Goals Against Average Calculator</h1><!--Title of Page-->
</header>
<article>
<form>
<fieldset>
<label for="GoalsAllowed">
Enter Number of Goals Allowed
</label>
<input type="Goals" id="GoalsAllowed" /><!--Input for Goals Allowed-->
</fieldset>
<fieldset>
<label for="MinutesPlayed">
Enter Minutes Played
</label>
<input type="MinPlayed" id="MPlayed" /><!--Input for Minutes Played-->
</fieldset>
<fieldset>
<label for="GameLength">
Regulation Game Length
</label>
<input type="Minutes" id="MinGame" /><!--Input for Length of Regulation Game-->
</fieldset>
<fieldset>
<button type="button" id="button">Calculate</button><!--Calculation Button-->
</fieldset>
<fieldset>
<p>Goals Against Average</p>
<p id="GAA"> </p>
</fieldset>
</form>
</article>
<script>
function convert() {
var Goals = document.getElementById("GoalsAllowed").value;
var Minutes = document.getElementById("MinutesPlayed").value;
var GameLength = document.getElementById("GameLength").value;
var GAA = (Goals * GameLength) / Minutes;
document.getElementById("GAA").innerHTML = GAA;
}
document.getElementById("button").
addEventListener("click", convert, false);
</script>
</body>
</html>
You do not have inputs with IDs MinutesPlayed and GameLength. There is an error that you cannot access property value of null.
Your JavaScript code should look as follow:
function convert() {
var Goals = document.getElementById("GoalsAllowed").value;
var Minutes = document.getElementById("MPlayed").value;
var GameLength = document.getElementById("MinGame").value;
var GAA = (Goals * GameLength) / Minutes;
document.getElementById("GAA").innerHTML = GAA;
}
you can have another alternative here using jQuery
you can include it locally by downloading the file or use google CDN as shown below
<!DOCTYPE html>
<html>
<head>
<title>Enjoy</title>
</head>
<body>
<article>
<form>
<fieldset>
<label for="GoalsAllowed">
Enter Number of Goals Allowed
</label>
<input type="Goals" id="GoalsAllowed" /><!--Input for Goals Allowed-->
</fieldset>
<fieldset>
<label for="MinutesPlayed">
Enter Minutes Played
</label>
<input type="MinPlayed" id="MPlayed" /><!--Input for Minutes Played-->
</fieldset>
<fieldset>
<label for="GameLength">
Regulation Game Length
</label>
<input type="Minutes" id="MinGame" /><!--Input for Length of Regulation Game-->
</fieldset>
<fieldset>
<button type="button" id="button">Calculate</button><!--Calculation Button-->
</fieldset>
<fieldset>
<p>Goals Against Average</p>
<h1 id="GAA"> </h1>
</fieldset>
</form>
</article>
<!--
include a jquery file am using jquery-2.1.1.min.js
you can find a later version
-->
<script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
var number_of_goals, minutes_played, regulation_game_length, GAA = ""; //initialize all the variables that we are going to use
$(document).on('click','#button', function(e){ //this is to check if the button with id button has been clicked
e.preventDefault(); //here you prevent its default action so that it does not refresh the page
number_of_goals = $('#GoalsAllowed').val(); //get the value entered for the number of goals
minutes_played = $('#MPlayed').val(); //get the value entered for the minutes played
regulation_game_length = $('#MinGame').val(); //capture the regulation game length
GAA = (number_of_goals * regulation_game_length) / minutes_played; //compute using your formular based on the values you have captured
$('#GAA').html(GAA); //print the result in your h1 tag that has id GAA
});
</script>
</body>
</html>

one textbox one button two different pages in html

i am trying to assign a textbox value to a php variable now problem is i want one button to work for two different pages i.e if i enter in a text box 'a'and click on button it should redirect to 'a.php' page if i write in a text box 'b' it should redirect to 'b.php'.
so one textbox,one button two different pages.
Code :
<html><head>
<meta charset="UTF-8" />
<script>
function submitForm(action)
{
document.getElementById('a').action = action;
document.getElementById('a').submit();
}
function submitForm1(action)
{
document.getElementById('b').action = action;
document.getElementById('b').submit();
}
</script>
</head>
<body >
<h3><font face="verdana" size="3"><b>Enter Text:</b></h3>
<input type="text" align="right" style="font-size:15pt;height:32px;"><br><br>
<form action="b.php" name="b" id="b" method="post">
<form action="a.php" name="a" id="a" method="post">
<input type="submit" onclick="submitForm('a.php')" value="TRY" name="a">
<input type="button" onclick="submitForm1('b.php')" value="TRY" name="b">
</form>
</form>
</body>
</html>
You can change the action onsubmit based on the text inside the input.
<html>
<head>
<script type="text/javascript">
function onsubmit_handler(){
var myForm = document.getElementById('myForm');
var data = document.getElementById('data').value;
if(data == "a")
myForm.setAttribute('action', 'a.php');
else if(data == "b")
myForm.setAttribute('action', 'b.php');
else
myForm.setAttribute('action', 'error.php');
}
</script>
</head>
<body>
<h3>Enter Text:</h3>
<form id="myForm" method="post" onsubmit="onsubmit_handler()">
<input type="text" id="data" name="data" value="">
<input type="submit" value="Post">
</form>
</body>
</html>
Test code here : http://jsfiddle.net/Eg9S4/
use this codes buddy
<html><head>
<meta charset="UTF-8" />
<script>
function submitForm()
{
var link=document.getElementById('a');
var str1 = "a.php";
var n = str1.localeCompare(link);
if(n==1)
{
window.open("main.html");
}
else if(n==-1)
{
window.open("index.html");
}
}
</script>
</head>
<body >
<h3><font face="verdana" size="3"><b>Enter Text:</b></h3>
<input type="text" align="right" style="font-size:15pt;height:32px;"><br><br>
<input type="submit" onclick="submitForm()" value="TRY" name="a">
</form>
</form>
</body>
</html>
The problem looks to be that you're using getElementById but the input elements don't have an ID (they only have a name).
I'd also recommend attaching an onSubmit event to the form and removing the onClick events from the buttons.
Edit: After looking at the code in detail I saw that there were some other issues that were probably hindering the opersation. The most notable one was that you can't nest form tags. There were some other CSS and validation issues.
Here is some working code:
Test Page
function SubmitForm(el) {
// Get the form element so that we can set the action later
var form = document.getElementById('theForm');
// Set the action for the form based on which button was clicked
if (el.id == "A")
form.action = "a.php";
if (el.id == "B")
form.action = "b.php";
// You dont need to submit the form. It's alreasdy happening, so there is no need for an explicit call.
}
</script>
<h3 style="font-family: Verdana; font-weight: bold;">Enter Text:</h3>
<input type="text" style="font-size:15pt;height:32px;"><br><br>
<form method="post" onsubmit="SubmitForm();" action="fake.html" id="theForm">
<input type="submit" id="A" value="A" onclick="SubmitForm(this);">
<input type="submit" id="B" value="B" onclick="SubmitForm(this);">
</form>