I need to validate the checkbox checked or not before showing the popup static text
This HTML code contains the questions and answers that I give as static in JavaScript and contains the popup style code.
function validate() {
var checkboxes = document.getElementsByName("answer1");
var checkboxChecked = [];
for (var i = 0; i < checkboxes.length; i++) {
}
}
$(document).ready(function() {
$('#trigger').click(function() {
const question1answer1 = document.querySelectorAll('input[name="answer1"]');
for (const question1answer1ans of question1answer1) {
if (question1answer1ans.checked) {
document.getElementById('question1-answer-1').innerHTML = question1answer1ans.value;
}
}
const question1answer2 = document.querySelectorAll('input[name="answer2"]');
for (const question1answer2ans of question1answer2) {
if (question1answer2ans.checked) {
document.getElementById('question1-answer-2').innerHTML = question1answer2ans.value;
}
}
const question1answer3 = document.querySelectorAll('input[name="answer3"]');
for (const question1answer3ans of question1answer3) {
if (question1answer3ans.checked) {
document.getElementById('question1-answer-3').innerHTML = question1answer3ans.value;
}
}
const question1answer4 = document.querySelectorAll('input[name="answer4"]');
for (const question1answer4ans of question1answer4) {
if (question1answer4ans.checked) {
document.getElementById('question1-answer-4').innerHTML = question1answer4ans.value;
}
}
const question1answer5 = document.querySelectorAll('input[name="answer5"]');
for (const question1answer5ans of question1answer5) {
if (question1answer5ans.checked) {
document.getElementById('question1-answer-5').innerHTML = question1answer5ans.value;
}
}
const question1answer6 = document.querySelectorAll('input[name="answer6"]');
for (const question1answer6ans of question1answer6) {
if (question1answer6ans.checked) {
document.getElementById('question1-answer-6').innerHTML = question1answer6ans.value;
}
}
$('#question1overlay').fadeIn(300);
});
$('#question1close').click(function() {
$('#question1overlay').fadeOut(300);
});
});
#question1popup {
max-width: 600px;
width: 90%;
max-height: 600px;
height: 100%;
padding: 20px;
position: relative;
background: white;
color: green;
margin: 20px;
margin-left: 35em;
}
#question1popups {
max-width: 700px;
width: 90%;
max-height: 600px;
height: 82%;
padding: 20px;
position: relative;
background: black;
color: green;
margin: 20px auto;
}
#question1overlay {
position: fixed;
height: 100%;
width: 100%;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: rgba(0, 0, 0, 0.8);
display: none;
}
#question1overlays {
position: fixed;
height: 100%;
width: 100%;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: rgba(0, 0, 0, 0.8);
display: none;
}
#question1close {
position: absolute;
top: 10px;
right: 10px;
cursor: pointer;
color: #fbfbfb;
background-color: black;
padding: 10px;
border-radius: 20px;
}
<!DOCTYPE html>
<html>
<head>
<title></title>
<!-- Activity needed packages -->
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css">
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
<body>
<fieldset id="question1">
<legend>Pick the fruits from the following</legend>
<br>
<div class="row">
<div class="col-md-2">
<label><INPUT TYPE="checkbox" NAME="answer1" VALUE="banana"><br>banana</label>
</div>
<div class="col-md-2">
<label><INPUT TYPE="checkbox" NAME="answer2" VALUE="tomato"><br>tomato</label>
</div>
<div class="col-md-2">
<label><INPUT TYPE="checkbox" NAME="answer3" VALUE="carrot"><br>carrot</label>
</div>
<div class="col-md-2">
<label><INPUT TYPE="checkbox" NAME="answer4" VALUE="mango"><br>mango</label>
</div>
<div class="col-md-2">
<label><INPUT TYPE="checkbox" NAME="answer5" VALUE="onion"><br>onion</label>
</div>
<div class="col-md-2">
<label><INPUT TYPE="checkbox" NAME="answer6" VALUE="apple"><br>apple</label>
</div>
</div>
</fieldset>
<center><button id="trigger">Check answer</button></center>
<br>
<br>
<div id="question1overlay">
<div id="question1popup">
<div id="question1close"><i class="fas fa-times-circle"></i></div>
<h2 style="color: #4aa0dd;text-decoration-line: underline;">These are the Correct answers</h2>
<br>
<p style="color: green;"><b><i class="fas fa-arrow-circle-right"></i>  Option 1</b></p>
<p style="color: green;"><b><i class="fas fa-arrow-circle-right"></i>  Option 4</b></p>
<p style="color: green;"><b><i class="fas fa-arrow-circle-right"></i>  Option 6</b></p>
<h2 style="color: #4aa0dd;text-decoration-line: underline;">Your Answers</h2>
<p id="question1-answer-1" style="color: green;font-weight: bold;"></p>
<p id="question1-answer-2" style="color: red;font-weight: bold;"></p>
<p id="question1-answer-3" style="color: red;font-weight: bold;"></p>
<p id="question1-answer-4" style="color: green;font-weight: bold;"></p>
<p id="question1-answer-5" style="color: red;font-weight: bold;"></p>
<p id="question1-answer-6" style="color: green;font-weight: bold;"></p>
</div>
</div>
<br>
The javascript code given in static text and more script is written manually into the HTML code
instead given in particular js file script
Check using if-condition after button is clicked
$(document).ready(function() {
$('#trigger').click(function() {
//IF CONDITION
if($('.row input:checked').length <= 0){
alert('Please Choose Atleast One Option');
return 1;
}
Related
I am trying to get the values from the two input boxes below the "Welcome to Discussion Portal" i.e. input boxes with the ids "textarea_text" and "id2"
and put these values on the left side two made tags i.e. h2 tag and p tag with the ids "addh2_in_col1" and "addp_in_col1"
The values are getting added but,
the problem is that they keep getting updated every time i click the submit button.
I want all the the values keep getting added to there
Here is my code:
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<style>
#h1a{
background: rgb(2,0,36);
background: linear-gradient(90deg, rgba(2,0,36,1) 0%, rgba(9,121,120,1) 37%, rgba(0,212,255,1) 100%);
color: white;
}
button{
background-color: #0099ff;
height: 48px;
width: 200px;
}
#id1{
height: 45px;
width: 200px;
}
* {
box-sizing: border-box;
}
/* Create two equal columns that floats next to each other */
.column {
float: left;
width: 50%;
padding: 10px;
height: 300px;
}
/* Clear floats after the columns */
.row:after {
content: "";
display: table;
clear: both;
}
textarea{
width: 250px;
height: 100px;
}
</style>
<script>
function function2(){
var a = document.getElementById('id2').value;
document.getElementById("addh2_in_col1").innerHTML = a;
var b = document.getElementById('textarea_text').value;
document.getElementById('addp_in_col1').innerHTML = b;
}
</script>
<div class="row">
<h1 id="h1a">Discussion Portal</h1>
<div class="column">
<button>New Question Form</button> <input id="id1" type="text" placeholder="search questions..." ><br>
<div class="div-2">
<h2 id='addh2_in_col1'></h2>
<p id='addp_in_col1'></p>
</div>
</div>
<div class="column">
<h1>Welcome to Discussion Portal</h1>
<p>Enter a subject and question to get started</p><br>
<input id="id2" type="text" placeholder="subject" ><br><br><br>
<textarea id="textarea_text" placeholder="Question"></textarea><br>
<input type="submit" value="Submit" onclick="function2()">
</div>
</div>
</body>
</html>```
You replaced your variable each time you clicked. I made it with array and plus
function function2(){
let a = []
let b = []
a.push(document.getElementById('id2').value);
a.forEach((item) => {
const para = document.createElement("h2");
para.innerHTML += item;
document.getElementById("div-2").appendChild(para);
})
b.push(document.getElementById('textarea_text').value);
b.forEach((item) => {
const para = document.createElement("p");
para.innerHTML += item;
document.getElementById("div-2").appendChild(para);
})
}
#h1a{
background: rgb(2,0,36);
background: linear-gradient(90deg, rgba(2,0,36,1) 0%, rgba(9,121,120,1) 37%, rgba(0,212,255,1) 100%);
color: white;
}
button{
background-color: #0099ff;
height: 48px;
width: 200px;
}
#id1{
height: 45px;
width: 200px;
}
* {
box-sizing: border-box;
}
/* Create two equal columns that floats next to each other */
.column {
float: left;
width: 50%;
padding: 10px;
height: 300px;
}
/* Clear floats after the columns */
.row:after {
content: "";
display: table;
clear: both;
}
textarea{
width: 250px;
height: 100px;
}
<div class="row">
<h1 id="h1a">Discussion Portal</h1>
<div class="column">
<button>New Question Form</button> <input id="id1" type="text" placeholder="search questions..." ><br>
<div class="div-2" id="div-2">
<h2 id='addh2_in_col1'></h2>
<p id='addp_in_col1'></p>
</div>
</div>
<div class="column">
<h1>Welcome to Discussion Portal</h1>
<p>Enter a subject and question to get started</p><br>
<input id="id2" type="text" placeholder="subject" ><br><br><br>
<textarea id="textarea_text" placeholder="Question"></textarea><br>
<input type="submit" value="Submit" onclick="function2()">
</div>
</div>
So I am working on a temperature converter which converts Celsius to Kelvin (not responsive), and I want to add the value of the Celsius input to 273 but it's considering it a string. type="number" isn't working so I had to write a seperate code for that. Any help? This is my code:
<html>
<head>
<title>
Celsius to Kelvin converter
</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</head>
<body>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.converter {
display: flex;
flex-direction: row;
width: 85%;
position: fixed;
left: 15%;
top: 27%;
}
.forum {
width: 30%;
height: 70px;
background: white;
margin-right: 150px;
}
.heading {
width: 85%;
margin-left: 7.5%;
text-align: center;
position: fixed;
top: 15%;
}
</style>
<div class="heading bg-warning">
<h3> Convert </h3>
</div>
<div class="converter">
<div class="Celsius">
<div class="input-group">
<span class="input-group-text">Celsius</span>
<textarea type="number" class="form-control forum celsii" aria-label="Celsius" onkeyup="checkInput(this)"></textarea>
</div>
</div>
<div class="kelvin">
<div class="input-group overwrite">
<span class="input-group-text">Kelvin</span>
<textarea class="form-control forum kelvii" aria-label="Kelvin" disabled readonly></textarea>
</div>
</div>
<script>
const celsii = document.getElementsByClassName('celsii')[0];
const kelvii = document.getElementsByClassName('kelvii')[0];
celsii.onchange = () => {
kelvii.value = celsii.value + 273;
}
function checkInput() {
var invalidChars = /[^0-9]/gi
if(invalidChars.test(celsii.value)) {
celsii.value = celsii.value.replace(invalidChars,"");
alert('Invalid character');
}
}
</script>
</body>
</html>
The value from input is of type string. Convert it to number before addition
const celsii = document.getElementsByClassName('celsii')[0];
const kelvii = document.getElementsByClassName('kelvii')[0];
celsii.onchange = () => {
const getInputVal = Number(celsii.value)
kelvii.value = !isNaN(getInputVal) ? getInputVal + 273 : alert('Not a number');
}
function checkInput() {
var invalidChars = /[^0-9]/gi
if (invalidChars.test(celsii.value)) {
celsii.value = celsii.value.replace(invalidChars, "");
alert('Invalid character');
}
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.converter {
display: flex;
flex-direction: row;
width: 85%;
position: fixed;
left: 15%;
top: 27%;
}
.forum {
width: 30%;
height: 70px;
background: white;
margin-right: 150px;
}
.heading {
width: 85%;
margin-left: 7.5%;
text-align: center;
position: fixed;
top: 15%;
}
<div class="heading bg-warning">
<h3> Convert </h3>
</div>
<div class="converter">
<div class="Celsius">
<div class="input-group">
<span class="input-group-text">Celsius</span>
<textarea type="number" class="form-control forum celsii" aria-label="Celsius" onkeyup="checkInput(this)"></textarea>
</div>
</div>
<div class="kelvin">
<div class="input-group overwrite">
<span class="input-group-text">Kelvin</span>
<textarea class="form-control forum kelvii" aria-label="Kelvin" disabled readonly></textarea>
</div>
</div>
just replace following code
celsii.onchange = () => {
kelvii.value = parseInt(celsii.value) + 273;
}
rest you have done good job as your are checking whether input is Number Or not
One more suggestion instead of triggering event on change you may trigger it after validating number so NaN will be o/p
You have a string and a number type, javascript will concatenate those values instead of adding them, you must convert the string to a number using parseInt() if you wish to add them as numbers.
Change the following line in your JS:
kelvii.value = parseInt(celsii.value) + 273;
const celsii = document.getElementsByClassName('celsii')[0];
const kelvii = document.getElementsByClassName('kelvii')[0];
celsii.onchange = () => {
kelvii.value = parseInt(celsii.value) + 273;
}
function checkInput() {
var invalidChars = /[^0-9]/gi
if (invalidChars.test(celsii.value)) {
celsii.value = celsii.value.replace(invalidChars, "");
alert('Invalid character');
}
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.converter {
display: flex;
flex-direction: row;
width: 85%;
position: fixed;
left: 15%;
top: 27%;
}
.forum {
width: 30%;
height: 70px;
background: white;
margin-right: 150px;
}
.heading {
width: 85%;
margin-left: 7.5%;
text-align: center;
position: fixed;
top: 15%;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<div class="heading bg-warning">
<h3> Convert </h3>
</div>
<div class="converter">
<div class="Celsius">
<div class="input-group">
<span class="input-group-text">Celsius</span>
<textarea type="number" class="form-control forum celsii" aria-label="Celsius" onkeyup="checkInput(this)"></textarea>
</div>
</div>
<div class="kelvin">
<div class="input-group overwrite">
<span class="input-group-text">Kelvin</span>
<textarea class="form-control forum kelvii" aria-label="Kelvin" disabled readonly></textarea>
</div>
</div>
So I taught myself coding a few years ago, and got it just enough to put together a few tools for work. I recently had to migrate my site out of CodePen and onto an actual web server. Now I'm having an issue where part of my javascript is executing properly (a portion that empties all other input fields when a user enters an input field using JQuery), but the button that calculates an answer will not work. I believe the .click is not picking it up. Either way I'm not getting error messages, the button just does nothing when I press it.
When I put the code in a snippet to share with you guys, it works (just like it did in CodePen), but the exact same code on my web host does not work. I'm really at a loss here and any help would be greatly appreciated. I feel like I'm missing some small line of code that's supposed to be included in all web files.
$(document).ready(function() {
//Clear out input fields when not selected
$("#sg").focusin(function() {
$("#density").val("");
});
$("#density").focusin(function() {
$("#sg").val("");
});
$("#pounds").focusin(function() {
$("#grams").val("");
$("#percentage").val("");
});
$("#grams").focusin(function() {
$("#percentage").val("");
$("#pounds").val("");
});
$("#percentage").focusin(function() {
$("#pounds").val("");
$("#grams").val("");
});
$(".input_field").focusin(function() {
$("#density").removeClass('highlight');
$("#sg").removeClass('highlight');
$("#pounds").removeClass('highlight');
$("#grams").removeClass('highlight');
$("#percentage").removeClass('highlight');
});
//Calculate on press of enter
$("#button").keypress(function(e) {
if (e.which == 13) {
alert("this is working");
}
});
$("#button").click(function() {
calculateButton();
});
//Calculate values on button hit
function calculateButton() {
function numberWithCommas(x) {
x = x.toString();
var pattern = /(-?\d+)(\d{3})/;
while (pattern.test(x))
x = x.replace(pattern, "$1,$2");
return x;
}
function removeCommas(x) {
x = x.replace(",", "");
return x;
}
var results = 0;
//Pulling information from input cells
var densityStr = document.getElementById("density").value;
var sgStr = document.getElementById("sg").value;
var poundsStr = document.getElementById("pounds").value;
var gramsStr = document.getElementById("grams").value;
var percentageStr = document.getElementById("percentage").value;
//remove commas from string and then convert string to number
var densityNum = Number(removeCommas(densityStr));
var sgNum = Number(removeCommas(sgStr));
var poundsNum = Number(removeCommas(poundsStr));
var gramsNum = Number(removeCommas(gramsStr));
var percentageNum = Number(removeCommas(percentageStr));
if (densityStr.length !== 0) {
var sgConversion = densityNum / 8.3454;
$("#sg").val(sgConversion.toFixed(3));
$("#density").addClass('highlight');
} else if (sgStr.length !== 0) {
var densityConversion = sgNum * 8.3454;
$("#density").val(densityConversion.toFixed(3));
$("#sg").addClass('highlight');
}
if (poundsStr.length !== 0) {
$("#pounds").addClass("highlight");
densityNum = document.getElementById("density").value;
var gramsConversion = poundsNum * 119.83;
var percentageConversion = poundsNum / densityNum * 100;
$("#grams").val(gramsConversion.toFixed(0));
$("#percentage").val(percentageConversion.toFixed(2));
} else if (gramsStr.length !== 0) {
$("#grams").addClass("highlight");
densityNum = document.getElementById("density").value;
var poundsConversion = gramsNum / 119.83;
var percentageConversion = poundsConversion / densityNum * 100;
$("#pounds").val(poundsConversion.toFixed(2));
$("#percentage").val(percentageConversion.toFixed(2));
} else if (percentageStr.length !== 0) {
$("#percentage").addClass("highlight");
densityNum = document.getElementById("density").value;
var percentageDec = percentageNum / 100;
var poundsConversion = densityNum * percentageDec;
var gramsConversion = poundsConversion * 119.83;
$("#pounds").val(poundsConversion.toFixed(2));
$("#grams").val(gramsConversion.toFixed(2));
}
}
});
body {
margin: 0;
font-family: 'Lato', sans-serif;
background: #d2d2d2;
}
p {
text-align: center;
}
conatiner {
max-width: 1024px;
margin: 0 auto;
}
#navbarContainer {
background: #F44336;
overflow: hidden;
width: 100%;
margin: 0;
}
.navbar {
float: left;
display: block;
font-family: 'Lato', sans-serif;
height: 40px;
width: 200px;
line-height: 40px;
text-align: center;
background: #F44336;
text-decoration: none;
color: #212121;
}
.navbar:hover {
background: #E57373;
color: white;
}
.active {
background: #C62828;
color: white;
}
#formContainer {
width: 450px;
background: #FDFFFC;
margin: 50px auto;
padding: 0px;
border-radius: 8px;
overflow: hidden;
}
#formContainer header {
width: 100%;
height: 130px;
background-color: #3cba54;
overflow: auto;
color: white;
}
header h1 {
margin: 35px 0 0 0;
text-align: center;
line-height: 30px;
}
header h3 {
line-height: 40px;
text-align: center;
margin: 0;
}
#heading {
background-color: #3cba54;
height: 40px;
color: white;
margin-bottom: 25px;
margin-left: -30px;
}
#heading h3 {
line-height: 40px;
}
form {
padding: 20px 0 0 20px;
text-align: center;
}
label {
display: inline-block;
width: 220px;
text-align: right;
}
#myForm .input_field {
margin-left: 20px;
margin-bottom: 10px;
font-size: 20px;
padding-left: 10px;
width: 125px;
height: 35px;
font-size: 17px;
border-radius: 3px;
background-color: #E0E0E0;
border: none;
}
#button {
display: block;
border-radius: 6px;
width: 200px;
height: 50px;
padding: 8px 15px 8px 15px;
margin: 0 auto;
margin-bottom: 50px;
font-size: 16px;
box-shadow: 0 6px #540000;
background-color: #FF3636;
border: none;
outline: none;
}
#button:active {
background-color: #B81B1B;
box-shadow: 0 1px #27496d;
transform: translateY(5px);
}
.highlight {
background: #FFEB3B !important;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div id="container">
<div id="navbarContainer">
<a class="navbar" id="62" href="https://s.codepen.io/awheat/debug/MpMrEo/yYAyLDjQWgKr">326 IAC 6-2 Tool</a>
<a class="navbar" id="63" href="https://s.codepen.io/awheat/debug/gWmazm/NQkzYnjeQZyA">326 IAC 6-3 Tool</a>
<a class="navbar active" id="voc" href="https://s.codepen.io/awheat/debug/qVpPNm/VGAWNnJYBjZr">VOC Conversion Tool</a>
</div>
<div id="formContainer">
<header>
<h1>VOC Conversion Tool</h1>
<h3>(for conversion of VOC data to other units)</h3>
</header>
<form id="myForm">
<label>Density of Coating (lbs/gal): </label><input type="text" id="density" class="input_field">
<label>Specific Graviy: </label><input type="text" id="sg" class="input_field">
<div id="heading">
<h3>VOC Content</h3>
</div>
<label>Pounds per Gallon (lbs/gal): </label><input type="text" id="pounds" class="input_field">
<label>Grams per Liter (g/L): </label><input type="text" id="grams" class="input_field">
<label>Percentage (%): </label><input type="text" id="percentage" class="input_field"><br><br>
<input type="button" id="button" value="Calculate" autofocus>
</form>
</div>
</div>
</body>
</html>
Sometimes putting script tags before the elements on the page can cause issues. You can try to put the scripts at the bottom of the body like this:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="container">
<div id="navbarContainer">
<a class="navbar" id="62" href="https://s.codepen.io/awheat/debug/MpMrEo/yYAyLDjQWgKr">326 IAC 6-2 Tool</a>
<a class="navbar" id="63" href="https://s.codepen.io/awheat/debug/gWmazm/NQkzYnjeQZyA">326 IAC 6-3 Tool</a>
<a class="navbar active" id="voc" href="https://s.codepen.io/awheat/debug/qVpPNm/VGAWNnJYBjZr">VOC Conversion Tool</a>
</div>
<div id="formContainer">
<header>
<h1>VOC Conversion Tool</h1>
<h3>(for conversion of VOC data to other units)</h3>
</header>
<form id="myForm">
<label>Density of Coating (lbs/gal): </label><input type="text" id="density" class="input_field">
<label>Specific Graviy: </label><input type="text" id="sg" class="input_field">
<div id="heading">
<h3>VOC Content</h3>
</div>
<label>Pounds per Gallon (lbs/gal): </label><input type="text" id="pounds" class="input_field">
<label>Grams per Liter (g/L): </label><input type="text" id="grams" class="input_field">
<label>Percentage (%): </label><input type="text" id="percentage" class="input_field"><br><br>
<input type="button" id="button" value="Calculate" autofocus>
</form>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
Based on a previous question of mine i want to filter a list of divs by different combinations based on the existence of specific div elements.
In the below example i use 3 checkboxes "Card", "Paypal", "Show only open stores" to filter the list. As it is now it works for the "Card" & "Paypal" checkboxes but if you try to check also the "Show only open stores" checkbox it messing it up. How can i fix that?
Here's the code:
var checkboxArea = document.querySelector('.filter-area')
var storeBlocks = Array.from(document.querySelectorAll('.store-block'))
var byCard = document.getElementById('by-card')
var byPaypal = document.getElementById('by-paypal')
var byOpen = document.getElementById('by-open')
var cardBlocks = storeBlocks.filter(function(block) {
return block.querySelector('.card-available')
})
var payPalBlocks = storeBlocks.filter(function(block) {
return block.querySelector('.paypal-available')
})
var openStoreBlocks = storeBlocks.filter(function(block) {
return block.querySelector('.close-small-tag')
})
checkboxArea.addEventListener('change', function(e) {
switch (true) {
case byCard.checked && byPaypal.checked:
storeBlocks.forEach(function(block) {
block.classList.remove('hide-me')
})
break
case byCard.checked:
cardBlocks.forEach(function(block) {
block.classList.remove('hide-me')
})
payPalBlocks.forEach(function(block) {
block.classList.add('hide-me')
})
break
case byPaypal.checked:
cardBlocks.forEach(function(block) {
block.classList.add('hide-me')
})
payPalBlocks.forEach(function(block) {
block.classList.remove('hide-me')
})
break
case byOpen.checked:
openStoreBlocks.forEach(function(block) {
block.classList.toggle('hide-me')
})
break
default:
payPalBlocks.concat(cardBlocks).forEach(function(block) {
block.classList.remove('hide-me')
})
}
})
.close-small-tag,
.open-small-tag {
position: absolute;
left: 130px;
top: 5px;
font-size: 11px;
font-weight: bold;
color: brown;
}
.search-area {
margin-bottom: 10px;
}
.storesList {
margin-top: 20px;
}
#count {
display: inline-block;
}
.store-block {
width: 80%;
margin-bottom: 10px;
padding: 5px;
background: #e5e5e5;
position: relative;
overflow: hidden;
}
.rating {
position: absolute;
right: 70px;
top: 3px;
}
.minorder {
position: absolute;
right: 180px;
top: 3px;
}
.paypal-available,
.card-available {
position: absolute;
right: 10px;
top: 5px;
font-size: 11px;
font-weight: bold;
color: blue;
}
.right {
float: right;
}
.left {
float: left;
}
.hide-me {
display: none;
}
.filter-area {
margin-bottom: 20px;
overflow: hidden;
}
.inputRadioGroup {
float: left;
margin-right: 20px;
font-weight: bold;
font-size: 12px;
text-transform: uppercase;
}
<div class="filter-area">
<div class=" inputRadioGroup">
<input type="checkbox" id="by-card">
<label for="by-card">Card</label>
</div>
<div class=" inputRadioGroup">
<input type="checkbox" id="by-paypal">
<label for="by-paypal">Paypal</label>
</div>
<div class=" inputRadioGroup">
<input type="checkbox" id="by-open">
<label for="by-open">SHOW ONLY OPEN STORES</label>
</div>
</div>
<div class="storesList">
<div class="store-block">
<div class="store-name">Apple Store</div>
<div class="rating">★ 4.5</div>
<div class="open-small-tag">OPEN</div>
<div class="minorder">100 €</div>
<div class="store-payment-options">
<div class="card-available">CARD</div>
</div>
</div>
<div class="store-block">
<div class="store-name">Nokia Store</div>
<div class="rating">★ 3.8</div>
<div class="open-small-tag">OPEN</div>
<div class="minorder">250 €</div>
<div class="store-payment-options">
<div class="paypal-available">PAYPAL</div>
</div>
</div>
<div class="store-block">
<div class="store-name">Samsung Store</div>
<div class="rating">★ 4.0</div>
<div class="close-small-tag">CLOSE</div>
<div class="minorder">25 €</div>
<div class="store-payment-options">
<div class="card-available">CARD</div>
</div>
</div>
<div class="store-block">
<div class="store-name">Linux Store</div>
<div class="rating">★ 4.9</div>
<div class="close-small-tag">CLOSE</div>
<div class="minorder">50 €</div>
<div class="store-payment-options">
<div class="paypal-available">PAYPAL</div>
</div>
</div>
</div>
I'm fairly new to javascript so I thought about creating a simple checklist with buttons that work as checkboxes. I set up HTML for buttons and made the script with a function for the checking them. Below is my code.
var checkbox1 = $("#checkbox1");
checkbox1.on("click", function() {
checkbox1.toggleClass("checked");
if (checkbox1.hasClass("checked")) {
checkbox1.html('<i class="material-icons">check</i>');
} else {
checkbox1.text("");
}
});
var checkbox2 = $("#checkbox2");
checkbox2.on("click", function() {
checkbox2.toggleClass("checked");
if (checkbox2.hasClass("checked")) {
checkbox2.html('<i class="material-icons">check</i>');
} else {
checkbox2.text("");
}
});
var checkbox3 = $("#checkbox3");
checkbox3.on("click", function() {
checkbox3.toggleClass("checked");
if (checkbox3.hasClass("checked")) {
checkbox3.html('<i class="material-icons">check</i>');
} else {
checkbox3.text("");
}
});
*{
margin: 0;
/*color: #fff;*/
}
body {
background-color: #0f0f0f;
}
p {
line-height: 30px;
padding-left: 15px;
}
.task {
background-color: #cbcbcb;
display: flex;
border-radius: 30px;
margin: 15px;
}
.box {
width: 30px;
height: 30px;
}
.checkbox {
border-radius: 50%;
padding: 0;
width: 30px;
height: 30px;
border: none;
}
.checkbox.checked {
background-color: #0d88ce;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
<div class="task">
<div class="box">
<button id="checkbox1" class="checkbox" type="button" name="button"></button>
</div>
<p> Some text</p>
</div>
<div class="task">
<div class="box">
<button id="checkbox2" class="checkbox" type="button" name="button"></button>
</div>
<p> Some text</p>
</div>
<div class="task">
<div class="box">
<button id="checkbox3" class="checkbox" type="button" name="button"></button>
</div>
<p> Some text</p>
</div>
Is there a way to merge all these functions for each element where the only id of it changes?
I think you're looking for a class selector. What you'd end up with is something like this:
var checkboxes = $(".checkbox");
checkboxes.on("click", function() {
$(this).toggleClass("checked");
if ($(this).hasClass("checked")) {
$(this).html('<i class="material-icons">check</i>');
} else {
$(this).text("");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="checkbox1" class="checkbox" type="button" name="button"></button>
<button id="checkbox2" class="checkbox" type="button" name="button"></button>
<button id="checkbox3" class="checkbox" type="button" name="button"></button>
Sure.
Gather all the checkboxes up into a collection. You've already given all of them the checkbox class, so that's the simplest way.
Loop over the collection and give each checkbox a reference to a
common event callback function.
That function will run in the context of the checkbox that was
clicked, so the this keyword will reference that checkbox making
the id irrelevant.
By passing this to the JQuery object you can use the JQuery API.
// Find all the checkboxes by their class and loop over them:
$(".checkbox").each(function(idx, box){
// Set up an event handler for each one
$(box).on("click", function(evt) {
// In the callback, this will reference the checkbox that was clicked
// but we'll wrap it in the JQuery object so we can use it with JQuery
var $this = $(this);
$this.toggleClass("checked");
if ($this.hasClass("checked")) {
$this.html('<i class="material-icons">check</i>');
} else {
$this.text("");
}
});
});
*{
margin: 0;
/*color: #fff;*/
}
body {
background-color: #0f0f0f;
}
p {
line-height: 30px;
padding-left: 15px;
}
.task {
background-color: #cbcbcb;
display: flex;
border-radius: 30px;
margin: 15px;
}
.box {
width: 30px;
height: 30px;
}
.checkbox {
border-radius: 50%;
padding: 0;
width: 30px;
height: 30px;
border: none;
}
.checkbox.checked {
background-color: #0d88ce;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Homework</title>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
</head>
<body>
<div class="task">
<div class="box">
<button id="checkbox1" class="checkbox" type="button" name="button"></button>
</div>
<p> Some text</p>
</div>
<div class="task">
<div class="box">
<button id="checkbox2" class="checkbox" type="button" name="button"></button>
</div>
<p> Some text</p>
</div>
<div class="task">
<div class="box">
<button id="checkbox3" class="checkbox" type="button" name="button"></button>
</div>
<p> Some text</p>
</div>
</body>
<script type='text/javascript' src='script.js'></script>
</html>
You could also achieve the same behavior without using JavaScript, just use a hidden checkbox and use the :checked pseudo-class selector together with the for attribute from the <label> element.
* {
margin: 0;
}
body {
background-color: #0f0f0f;
}
p {
line-height: 30px;
padding-left: 15px;
}
.task {
background-color: #cbcbcb;
display: flex;
border-radius: 30px;
margin: 15px;
}
.custom-checkbox {
display: block;
position: relative;
width: 30px;
height: 30px;
border-radius: 50%;
overflow: hidden;
color: white;
}
.custom-checkbox .input {
display: none;
}
.custom-checkbox .label {
background-color: #ddd;
display: block;
width: 100%;
height: 100%;
cursor: pointer;
position: absolute;
top: 0;
left: 0;
z-index: 1;
}
.custom-checkbox .icon {
display: none;
pointer-events: none;
position: absolute;
z-index: 2;
text-align: center;
width: 100%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.custom-checkbox .input:checked ~ .label {
background-color: #0d88ce;
}
.custom-checkbox .input:checked ~ .icon {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Homework</title>
<link rel="stylesheet" href="style.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
<div class="task">
<div class="custom-checkbox">
<input id="checkbox1" class="input" type="checkbox" />
<label for="checkbox1" class="label"></label>
<i class="icon material-icons">check</i>
</div>
<p> Some text</p>
</div>
<div class="task">
<div class="custom-checkbox">
<input id="checkbox2" class="input" type="checkbox" />
<label for="checkbox2" class="label"></label>
<i class="icon material-icons">check</i>
</div>
<p> Some text</p>
</div>
<div class="task">
<div class="custom-checkbox">
<input id="checkbox3" class="input" type="checkbox" />
<label for="checkbox3" class="label"></label>
<i class="icon material-icons">check</i>
</div>
<p> Some text</p>
</div>
</body>
</html>