MultiSelect dropdown with checkbox slection using jQuery - javascript

I am trying to create a dropdown with multi-select check box manually using jQuery.
I don't want to use any built in libraries other than jQuery. I tried implementing the functionality but the issue is, when I select the check boxes, the data will be popped up in input field, if I click for the second time, I can see that checkboxes are unchecked and data is not appending to previous one.
Please tell me where i went wrong in the code.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Untitled Document</title>
<style>
.multiselect {
width: 200px;
}
.selectBox {
position: relative;
}
.selectBox select {
width: 100%;
font-weight: bold;
}
.overSelect {
position: absolute;
left: 0; right: 0; top: 0; bottom: 0;
}
#presentationTable {
display: none;
border: 1px #dadada solid;
}
#presentationTable label {
display: block;
}
#presentationTable label:hover {
background-color: #1e90ff;
}
</style>
</head>
<body>
<form>
<div class="multiselect">
<div class="selectBox" onClick="showCheckboxes()">
<input type="text" id="presentatioonTableimputValue"><img src="http://siged.sep.gob.mx/analytics/res/s_blafp/uicomponents/obips.CommonIconSets/dropdownfilled_en_choicelistmulti.png" />
<div class="overSelect"></div>
</div>
<div id="presentationTable"> </div>
</div>
</form>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
var expanded = false;
function showCheckboxes()
{
var abc = '<label><input type="checkbox" id="one" value="1"/>First1 checkbox</label> <label><input type="checkbox" id="two" value="two"/>Second checkbox </label> <label><input type="checkbox" id="three" value="three"/>Third checkbox</label>';
$('#presentationTable').html(abc);
if (!expanded) {
$('#presentationTable').show();
expanded = true;
} else {
$('#presentationTable').hide();
expanded = false;
}
}
function updateTextArea()
{
var allVals = [];
$('#presentationTable :checked').each(function () {
allVals.push($(this).val());
});
$('#presentatioonTableimputValue').val(allVals);
}
$(document).click(function(event){
var $trigger = $(".multiselect");
if($trigger !== event.target && !$trigger.has(event.target).length){
$("#presentationTable").slideUp("fast");
updateTextArea();
}
});
</script>
</body>
</html>

Try this:
JS
var expanded = false;
populateCheckbox();
function populateCheckbox(){
var abc = '<label><input type="checkbox" id="one" value="1"/>First1 checkbox</label> <label><input type="checkbox" id="two" value="two"/>Second checkbox </label> <label><input type="checkbox" id="three" value="three"/>Third checkbox</label>';
$('#presentationTable').html(abc);
}
function showCheckboxes()
{
if (!expanded) {
$('#presentationTable').show();
expanded = true;
} else {
$('#presentationTable').hide();
expanded = false;
}
}
function updateTextArea()
{
var allVals = [];
$('#presentationTable :checked').each(function () {
allVals.push($(this).val());
});
$('#presentatioonTableimputValue').val(allVals);
}
$("#presentationTable label input").click(function(){
updateTextArea();
});
$(document).click(function(event){
var $trigger = $(".multiselect");
if($trigger !== event.target && !$trigger.has(event.target).length){
$("#presentationTable").slideUp("fast");
// updateTextArea();
}
});
Each time when you click on the input field, it is creating new checkboxes, That was the issue.
hope it will solve your problem.

Related

How Can I Create Multiple Checkboxes That Stay Either Checked or Unchecked on Browser Refresh?

How can I create multiple checkboxes that either stay checked or unchecked on browser refresh depending on what I choose using JavaScript? I figured out how to do one checkbox, but when I tried to add another checkbox the initial checkbox wouldn't remember that it had been checked on the refresh (if that makes sense lol). Please help. Here's my code:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
<div id="checkbox-container">
<input type="checkbox" id="name"/>
</div>
</div>
<script>
var checkboxValue = JSON.parse(localStorage.getItem('checkboxValue')) || {}
var $checkbox = $("#checkbox-container :checkbox");
$checkbox.on("change", function() {
$checkbox.each(function() {
checkboxValue[this.id] = this.checked;
});
localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
});
//on page load
$.each(checkboxValue, function(key, value) {
$("#" + key).prop('checked', value);
});
</script>
<style>
.wrap input {
position: absolute;
top: 300px;
left: 500px;
}
input[type=checkbox] {
transform: scale(2);
margin: 10px;
cursor: pointer;
}
.wrap {
filter: hue-rotate(410deg);
}
</style>
<body>
</body>
</html>
You are only storing one value in the localStorage.
localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
Any time a checkbox value changes, you store that one value. I'd recommend setting an ID, name or data-value that distinguishes your checkboxes from each other. Then use that as the key in the local storage.
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
//on page load
$(document).ready(function(){
populateCheckBoxes();
$("#checkbox-container :checkbox").on("change", function() {
// use this.id as the key for local storage
localStorage.setItem(this.id, JSON.stringify(this.checked));
});
});
function populateCheckBoxes() {
$("#checkbox-container :checkbox").each(function() {
// get just the localStorage for this checkbox by this.id
const value = localStorage.getItem(this.id) || false;
// value is stored as a string, so need to check for a boolean
this.checked = value == 'true';
});
}
</script>
<style>
input[type=checkbox] {
transform: scale(2);
margin: 10px;
cursor: pointer;
}
.wrap {
position: absolute;
top: 300px;
left: 500px;
filter: hue-rotate(410deg);
}
</style>
<body>
<!-- html should go between the <body> and </body> tags -->
<div class="wrap">
<div id="checkbox-container">
<!-- set different ids for each checkbox -->
<!-- ids must be unique over the whole document -->
<input type="checkbox" id="is-human"/><label for="is-human">Is Human</label>
<br><input type="checkbox" id="is-adult"/><label for="is-adult">Is Adult</label>
</div>
</div>
</body>
</html>

Making a button that shows a hidden image on click

I've found tutorials that make an image hidden with some css, javascript and html but I'm having trouble making the image hidden first, and then having the button be able to make it visible and then hidden if pressed again.
edit: hopefully this code should help! Again, sorry I can't figure some of this out, I don't really know how this site works and I'm pretty new to coding,,,,
edit 2: I added where the function is being called. It's suppose to be a multiple choice that shows an image when correct!
<style>
div.notdropdown {
margin-top: 100px;
margin-bottom: 100px;
border: 1px solid black;
background-color: rgb(181, 204, 180, 0.9);
}
.hide{
display:none;
}
</style>
</body>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
<div id="myDIV">
<img class= "hide" src="https://www.merriam-webster.com/assets/mw/static/art/dict/frig_bi.gif">
<br>
<a class= "hide" href="https://www.merriam-webster.com/dictionary/frigate%20bird">https://www.merriam-webster.com/dictionary/frigate%20bird </a>
<br>
</div>
<h1>What is a Frigate?</h1><br>
<form >
<input type="radio" name="choice" value="Bird"> A type of Bird
<input type="radio" name="choice" value="Mangrove"> A type of Mangrove tree
<input type="radio" name="choice" value="Sea Creature"> A type of Sea Creature
<input type="radio" name="choice" value="None"> None of These
</form>
<button onclick="submitAnswer();"> Submit Answer</button>
</body>
<script>
function submitAnswer() {
var radios = document.getElementsByName("choice");
var i = 0, len = radios.length;
var checked = false;
var userAnswer;
for( ; i < len; i++ ) {
if(radios[i].checked) {
checked = true;
userAnswer = radios[i].value;
}
}
if(!checked) {
alert("please select choice answer");
return;
}
// Correct answer
if(userAnswer === "Bird") {
myFunction();
alert("Answer is correct!");
}
// incorrect answer
else {
alert("Answer is wrong!");
}
}
</script>
</body>
</html>
in fact it's very simple, just use the toggle method, which allows you to easily enable and disable a class in an element
function toggleImage(){
document.querySelector('#image').classList.toggle('hidden');
}
.hidden{
display: none;
}
.w-100{
width: 100%;
}
.mb-10{
margin-bottom: 10px;
}
<button onClick="toggleImage()" class="w-100 mb-10">Show/Hide</button>
<img src="https://images.pexels.com/photos/462118/pexels-photo-462118.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" id="image" class="hidden w-100"/>
to work with a link to just change the tag to a and use href="#"
function toggleImage(){
document.querySelector('#image').classList.toggle('hidden');
}
.hidden{
display: none;
}
.w-100{
width: 100%;
}
.mb-10{
margin-bottom: 10px;
}
<a onClick="toggleImage()" class="w-100 mb-10" href="#">Show/Hide</a>
<img src="https://images.pexels.com/photos/462118/pexels-photo-462118.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" id="image" class="hidden w-100"/>
You just need to call your function on button tag. Add a button in your html file on which you want your div to toggle. As you are using function name myFunction, call it on that function using
onClick="myFunction()"
And your code should work fine. Don't need to add any new class or even hide your div by default.
check this code. I think this will help you.
<button id = "showhide" onclick = "showhide()">Show Hide Image</button>
<div id = "image" style="width: 100px; height : 100px;">
<h4> Image Code </h4>
</div>
<script>
$('#showhide').on('click', function(e){
$("#image").toggle();
});
</script>

How to include a input in a label in a querySelector() in javascript?

I am trying to construct a personality quiz for my school project. Everything was working fine until I decided that I want the inputs for the radio buttons to be just pictures. The problem is that I am not sure how to save the selected choice and its value, in order to calculate the result.
This is my HTML code:
<div id="simplequiz">
<h3>What's your favourite colour palette?</h3>
<p>
<input type="radio" name="colour" class="a" value="-1" />
<label for="p">
<img src="images/2.jpg" alt="Gothic colour palette" style="width: 200px">
</label>
</p>
<button type="submit" value="submit" onClick="submitSimpleQuiz()">Submit</button>
</div>
This is my CSS:
.input_hidden {
position: absolute;
left: -9999px;
}
.selected {
background-color: #ccc;
}
#simplequiz label {
display: inline-block;
cursor: pointer;
}
#simplequiz label:hover {
background-color: #efefef;
}
#simplequiz label img {
padding: 3px;
}
And this is my Javascript:
function submitSimpleQuiz() {
"use strict";
var colour = praseInt(document.querySelector('input[name = "colour"]:checked').value);
var total = colour;
if (total < 0) {
document.getElementById("answer").innerHTML = "Goth";
document.getElementById("simplequiz").style.display = "none";
} else {
document.getElementById("answer").innerHTML = "Minimalistic";
document.getElementById("simplequiz").style.display = "none";
}
}
$('#simplequiz input:radio').addClass('input_hidden');
$('#simplequiz label').click(function () {
$(this).addClass('selected').siblings().removeClass('selected');
});
This is just one question and answer but essentially all the answers should add up to an outcome which will display a personality description. I don't know why the button for submitting doesn't work anymore.
I would greatly appreciate the help.
I am only new to coding, but I tried including the label into the javascript and also changing the layout of the HTML so that the input is included in the label tag.
As I am sure you won't stop with only 1 question, here is a working snippet in which you can add more questions easily:
function submitSimpleQuiz() {
"use strict";
var total = 0;
var answer = ""; // Added, just because… (see below)
// Easy selection, now! That counts only "selected" inputs!
var inputs = document.querySelectorAll("#simplequiz .selected input");
for (var i = 0; i < inputs.length; i++) {
total += parseInt(inputs[i].value);
}
if (total < 0) {
answer = "Goth";
} else {
answer = "Minimalistic";
}
// Moved outside of the if to only have these instructions one time
document.getElementById("simplequiz").style.display = "none";
document.getElementById("answer").innerHTML = answer;
}
// Your other code, I haven't touched it. Promise.
$('#simplequiz input:radio').addClass('input_hidden');
$('#simplequiz label').click(function() {
$(this).addClass('selected').siblings().removeClass('selected');
});
.input_hidden {
position: absolute;
left: -9999px;
}
.selected {
background-color: #ccc;
}
#simplequiz label {
display: inline-block;
cursor: pointer;
}
#simplequiz label:hover {
background-color: #efefef;
}
#simplequiz label img {
padding: 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="simplequiz">
<h3>What's your favourite colour palette?</h3>
<p>
<!-- Modified order -->
<label for="p">
<input type="radio" name="colour" class="a" value="-1" />
<img src="images/2.jpg" alt="Gothic colour palette" style="width: 200px">
</label>
<!-- Added another one below -->
<label for="p">
<input type="radio" name="colour" class="a" value="1" />
<img src="images/2.jpg" alt="Minimal colour palette" style="width: 200px">
</label>
</p>
<button type="submit" value="submit" onClick="submitSimpleQuiz()">Submit</button>
</div>
<!-- Added "answer" -->
<div id="answer"></div>
Anyway, I've got a few remarks, here:
⋅ Your function submitSimpleQuiz is in JavaScript only, whereas your other code is in jQuery. You should choose what you want to use!
⋅ I moved the inputs in your labels to make it easier to select them.
⋅ Why are you using inputs if you're hiding them, and can't/don't check them?!…
Hope it helps.
You need to remove line :
$('#simplequiz input:radio').addClass('input_hidden');
Or you need to modify the line:
var colour = parseInt(document.querySelector('input[name = "colour"]:checked').value);
Because if you uncheck radiobutton you can't get the value. And You have to use parseInt not praseInt. it's an error.
First off all you need to import Jquery for using Jquery function $.
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
Second it is parseInt not praseInt.
Third:
use this piece of code instead of yours:
var colour = parseInt(document.querySelector("div#simplequiz input[name = 'colour']").value);
Fourth:
for your script to work correctly your javasScript should be -
<script type="text/javascript">
function submitSimpleQuiz(){
"use strict";
var colour = parseInt(document.querySelector("div#simplequiz input[name = 'colour']").value);
if (document.querySelector("div#simplequiz input[name = 'colour']").checked) {
colour = 0;
}
var total = colour;
if (total < 0) {
document.getElementById("answer").innerHTML = "Goth";
document.getElementById("simplequiz").style.display = "none";
}
else
{
document.getElementById("answer").innerHTML = "Minimalistic";
document.getElementById("simplequiz").style.display = "none";
}
}
$('#simplequiz input:radio').addClass('input_hidden');
$('#simplequiz label').click(function() {
$(this).addClass('selected').siblings().removeClass('selected');
});
</script>

How to do multiple selection with javaScript

Iam trying to do multiple select with JavaScript. but can't working.how can i fix this?
Iam done it in following way
var expanded = false;
function showCheckboxes() {
var checkboxes = document.getElementById("checkboxes");
if (!expanded) {
checkboxes.style.display = "block";
expanded = true;
} else {
checkboxes.style.display = "none";
expanded = false;
}
}
.multiselect {
width: 200px;
}
.selectBox {
position: relative;
}
.selectBox select {
width: 100%;
font-weight: bold;
}
.overSelect {
position: absolute;
left: 0; right: 0; top: 0; bottom: 0;
}
#checkboxes {
display: none;
border: 1px #dadada solid;
}
#checkboxes label {
display: block;
}
#checkboxes label:hover {
background-color: #1e90ff;
}
<div class="multiselect">
<div class="selectBox" onclick="showCheckboxes()">
<select>
<option>check box1</option>
</select>
<div class="overSelect"></div>
</div>
<div id="checkboxes">
<label for="one"><input type="checkbox" id="one" />First checkbox</label>
</div>
</div>
<div class="multiselect">
<div class="selectBox" onclick="showCheckboxes()">
<select>
<option>check box2</option>
</select>
<div class="overSelect"></div>
</div>
<div id="checkboxes">
<label for="one"><input type="checkbox" id="one" />First checkbox</label>
</div>
</div>
<div class="multiselect">
<div class="selectBox" onclick="showCheckboxes()">
<select>
<option>check box3</option>
</select>
<div class="overSelect"></div>
</div>
<div id="checkboxes">
<label for="one"><input type="checkbox" id="one" />First checkbox</label>
</div>
</div>
you cannot have same id for multiple elements .it's invalid . however when you call getElementById() 1st element is taken .that's why in your example only 1st element expand and collapse .
here is example .
in this example i pass a parameter to showCheckboxes methods.so we can select correct checkboxes .also we have to store state of 3 elements individually.
https://jsfiddle.net/93894gbs/5/
js
var expanded = [false, false, false];
var checkboxes;
function showCheckboxes(i) {
checkboxes = checkboxes || document.getElementsByClassName("checkboxes");
if (!expanded[i]) {
checkboxes[i].style.display = "block";
expanded[i] = true;
} else {
checkboxes[i].style.display = "none";
expanded[i] = false;
}
}
Also you can pass "event" attribute while calling the handler like :
div class="selectBox" onclick="showCheckboxes(event)"
and change javascript like :
var expanded = false;
function showCheckboxes(ev) {
console.log("ev", ev);
var checkboxes = ev.currentTarget.parentElement.lastElementChild;
if (!expanded) {
checkboxes.style.display = "block";
expanded = true;
} else {
checkboxes.style.display = "none";
expanded = false;
}
}

change background image of a div when checkbox is checked

I hide the default checkbox and use a div with custom checkbox image instead:
<aui:form>
<c:if
test="<%=company.isAutoLogin() && !PropsValues.SESSION_DISABLED%>">
<div class="rememberImage ftr" id="rememberImg">
<aui:input checked="<%=rememberMe%>" name="rememberMe" id="rememberMe"
type="checkbox" cssClass="remember"/>
</div>
</c:if>
</form>
//omiited
<aui:script use="aui-base">
function changeBG() {
if (this.checked) {
document.getElementById('rememberImg').style.backgroundImage = 'url(../img/chk_none.png)';
} else {
document.getElementById('rememberImg').style.backgroundImage = 'url(../img/chk_check.png)';
}
}
document.getElementById('_58_rememberMe').addEventListener('change', changeBG);
var password = A.one('#<portlet:namespace />password');
if (password) {
password.on(
'keypress',
function(event) {
Liferay.Util.showCapsLock(event, '<portlet:namespace />passwordCapsLockSpan');
}
);
}
</aui:script>
This does not work at all. Any suggestions?? Much appreciated!
UPDATE: add more lines of code that I think maybe have problems
I saw a proper answer already above, but to avoid intruding HTML tags with JS listeners, what considered as not the best practice, I will offer you this solution...
function changeBG() {
if (this.checked) {
document.getElementById('myElement').style.backgroundImage = 'url(.....)';
} else {
document.getElementById('myElement').style.backgroundImage = 'url(.....)';
}
}
document.getElementById('myInput').addEventListener('change', changeBG);
Hope it will help you :)
You can do it like this: Add an onclick attribute to the checkbox that triggers a toggle function. As I cant test it with your code (missing the rest) I can only provide you an enxample where the body background gets changed
<input id="check" type="checkbox" onclick="toggle();"> Click me
<script>
function toggle() {
if( document.getElementById("check").checked ) {
document.getElementsByTagName("body")[0].style.backgroundColor="red";
}
}
</script>
div{
margin: 20px 0;
}
input[type=checkbox] {
display: none
}
input[type=checkbox]+label {
background: url(http://s17.postimg.org/phsoii5vf/check.png) no-repeat;
padding-left: 30px;
padding-bottom: 5px;
padding-top: 2.5px;
height: 18px;
}
input[type=checkbox]:checked+label {
background: url(http://s2.postimg.org/zbjg138np/check_tick.jpg) no-repeat;
}
<div>
<input type="checkbox" id="chk1">
<label for="chk1">Custom Checkbox1</label>
</div>
<div>
<input type="checkbox" id="chk2">
<label for="chk2">Custom Checkbox2</label>
</div>
<div>
<input type="checkbox" id="chk3">
<label for="chk3">Custom Checkbox3</label>
</div>
<div>
<input type="checkbox" id="chk4">
<label for="chk4">Custom Checkbox4</label>
</div>
not required javascript.you can do it from css.
<div>
<input type="checkbox" id="chk">
<label for="chk">Custom Checkbox1</label>
</div>
input[type=checkbox] {
display: none
}
input[type=checkbox]+label {
background: url(../images/check.png) no-repeat;
padding-left: 30px;
padding-bottom: 5px;
padding-top: 2.5px;
height: 18px;
}
input[type=checkbox]:checked+label {
background: url(../images/check_tick.png) no-repeat;
}
you can try this one:
document.getElementById('rememberImage').style.background = 'url(../img/chk_check.png)';
function SetBackground(elm){
if($(elm).is(":checked"))
{
$("#rememberImage").css({"background-color":"gray"});
}
else
{
$("#rememberImage").css({"background-color":"white"});
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="rememberImage ftr" id="rememberImage">
<input checked="<%=rememberMe%>" name="rememberMe" id="rememberMe" type="checkbox" onchange="SetBackground(this)"/>
</div>
I don't know how your custom checkbox works but, you can add onchange event and check if checkbox is checked then change the background of div.
Best regards

Categories