Get multiple value from dropdown multiple checked checkbox - javascript

I creating a dropdown multiple checkbox filter function for my gantt chart, but I'm having trouble getting all selected value and append it into an array. can anyone help me with this, any help is much appreciated
Below is my code :
HTML :
<label class="text-primary" for="type_2">Search Type: </label>
<dl id="type_2" class="dropdown">
<dt>
<a href="#">
<span class="hida">ALL</span>
<p class="multiSel"></p>
</a>
</dt>
<dd>
<div class="search_type_filter">
<ul>
<li><input type="checkbox" value="ALL" selected="Selected" checked="1" />ALL</li>
<li><input type="checkbox" value="Car" />Car</li>
<li><input type="checkbox" value="Bike"/>Bike</li>
<li><input type="checkbox" value="Ball"/>Ball</li>
</ul>
</div>
</dd>
</dl>
Javascript :
$('.search_type_filter input[type="checkbox"]').on('click', function() {
var title = $(this).closest('.search_type_filter').find('input[type="checkbox"]').val(),
title = $(this).val() + ",";
var values = $(this).closest('.search_type_filter').find('input[type="checkbox"]').val(),
values = $(this).val();
search_type_value = {};// put combo value into scope variable
for(var i = 0; i < values.length; i++){
search_type_value[values[i]] = true;// build hash for easy check later
}
console.log(search_type_value);
gantt.render();// and repaint gantt
if ($(this).is(':checked')) {
var html = '<span title="' + title + '">' + title + '</span>';
$('.multiSel').append(html);
$(".hida").hide();
} else {
$('span[title="' + title + '"]').remove();
var ret = $(".hida");
$('.dropdown dt a').append(ret);
}
});
gantt.attachEvent("onBeforeTaskDisplay", function (id, task) {
if(search_type_value['ALL'])
return true;
return !!search_type_value[task.search_type];
});
So the end result what I want is let say I check Car and Ball it will give me an array like this :
{Car: true, Ball: true}
but with this I'm getting by letter and its getting only one value :
{C: true, a: true, r: true}

Here is an example. I added comments that explain whats going on in the code but essentially you just want to create a JSON array based on the checkbox elements on your form.
I also included an alternative to this that uses multi-dimensional arrays but I highly recommend you go down the JSON path instead.
//on button click
$("#click").click(function()
{
//create variable to hold the array
var yourArray = [];
//for each checkbox within the group
$("input[name='group']").each(function()
{
//return if its checked or not
var isChecked = $(this).is(":checked");
//get the value of the checkbox i.e. Bike etc.
var value = $(this).val();
//Create a new object using above variables
var myObject = new Object();
myObject.value = value;
myObject.isChecked = isChecked;
//push the object onto the array
yourArray.push(myObject);
});
//Now you have a dynamic object you can use to select what you need
console.log("Using JSON Array (recommended)");
console.log(yourArray[0].value);
console.log(yourArray[0].isChecked);
console.log(yourArray[1].value);
console.log(yourArray[2].value);
//showing everything in the array
console.log(yourArray);
//if you really need to have the output as Ball:true, Bike:false etc you can break up the array you already have like this:
//Create 2d array
var multiArray = [];
//foreach index in your json array
$.each(yourArray, function(key, value)
{
//create a new array
var newArray = [];
//push the values into it
newArray.push(value.value);
newArray.push(value.isChecked);
//push the array onto the 2d array
multiArray.push(newArray);
});
//output the results
console.log("Using 2D Array");
console.log(multiArray);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="text-primary" for="type_2">Search Type: </label>
<dl id="type_2" class="dropdown">
<dt>
<a href="#">
<span class="hida">ALL</span>
<p class="multiSel"></p>
</a>
</dt>
<dd>
<div class="search_type_filter">
<ul>
<li><input type="checkbox" name="group" value="ALL" selected="Selected" checked="1" />ALL</li>
<li><input type="checkbox" name="group" value="Car" />Car</li>
<li><input type="checkbox" name="group" value="Bike" />Bike</li>
<li><input type="checkbox" name="group" value="Ball" />Ball</li>
</ul>
</div>
</dd>
</dl>
<button type="button" id="click"> check </button>

Related

I want to catch all labels of checked checkbox in javascript

Is there a way to catch all the label texts of a checked checkbox in Javascript (not JQuery).
My HTML is:
<div class="wpgu-onboarding-answer-container">
<div class="wpgu-onboarding-answer" data-bc-answer-post="Firstitem">
<input id="post-3-0" class="wpgu-onboarding-answer-checkbox" type="checkbox" name="posts_stijlen[]" value="670" checked="checked">
<label for="post-3-0" class="wpgu-onboarding-answer-label">
<span class="wpgu-onboarding-answer-title">Firstitem</span>
</label>
</div>
<div class="wpgu-onboarding-answer" data-bc-answer-post="SecondItem">
<input id="post-3-8" class="wpgu-onboarding-answer-checkbox" type="checkbox" name="posts_stijlen[]" value="681">
<label for="post-3-8" class="wpgu-onboarding-answer-label">
<span class="wpgu-onboarding-answer-title">SecondItem</span>
</label>
</div>
</div>
I want to catch the label of the checked checkbox in Javascript in order to use it as Javascript Variable in Google Tagmanager.
Currently I've got this code (from www.simoahava.com) to catch the values of the checked checkboxes.
function () {
var inputs = document.querySelectorAll('.wpgu-onboarding-answer-containter input'),
selectedCheckboxes = [];
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type === "checkbox" && inputs[i].checked) {
selectedCheckboxes.push(inputs[i].value);
}
}
return selectedCheckboxes;
}
This script gives me all the values, but these are none-descriptive values. But I want the descriptive labels.
Is there a way to catch the text within the span with class .wpgu-onboarding-answer-title of all checked checkboxes ?
Thanks in Advance
Erik.
Apart from the previous solution, would like to share one more simple solution based on the code mentioned in the question. The solution can be as simple as fetching all the labels with class as wpgu-onboarding-answer-title and based on which input element is selected, fetch the respective label index and use it.
Please note that I have added an extra button for testing the function easily.
function abc() {
var labels = document.querySelectorAll('.wpgu-onboarding-answer-title');
var inputs = document.querySelectorAll('.wpgu-onboarding-answer-container input'),
selectedCheckboxes = [];
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type === "checkbox" && inputs[i].checked) {
selectedCheckboxes.push(labels[i].textContent);
//selectedCheckboxes.push(inputs[i].value);
}
}
console.log(selectedCheckboxes);
return selectedCheckboxes;
}
<div class="wpgu-onboarding-answer-container">
<div class="wpgu-onboarding-answer" data-bc-answer-post="Firstitem">
<input id="post-3-0" class="wpgu-onboarding-answer-checkbox" type="checkbox" name="posts_stijlen[]" value="670" checked="checked">
<label for="post-3-0" class="wpgu-onboarding-answer-label">
<span class="wpgu-onboarding-answer-title">Firstitem</span>
</label>
</div>
<div class="wpgu-onboarding-answer" data-bc-answer-post="SecondItem">
<input id="post-3-8" class="wpgu-onboarding-answer-checkbox" type="checkbox" name="posts_stijlen[]" value="681">
<label for="post-3-8" class="wpgu-onboarding-answer-label">
<span class="wpgu-onboarding-answer-title">SecondItem</span>
</label>
</div>
</div>
<button onclick="abc()">
Fetch All Chkbox Values
</button>
Please note that this solution would only work if you have wpgu-onboarding-answer-title class being used for only this purpose and not anywhere else in the page before.
Based on this answer using jQuery, you can use an attribute selector and the ID of the element you want to get the label for, e.g. document.querySelector('label[for=' + button.id + ']'), then get its textContent to get the actual label:
document.querySelectorAll('input.wpgu-onboarding-answer-checkbox').forEach(input => {
console.log(input.id + ' ' +
document.querySelector('label[for=' + input.id + ']').textContent.trim() + ' ' +
(input.checked? '' : 'not ') + 'checked'
)
});
<div class="wpgu-onboarding-answer-container">
<div class="wpgu-onboarding-answer" data-bc-answer-post="Firstitem">
<input id="post-3-0" class="wpgu-onboarding-answer-checkbox" type="checkbox" name="posts_stijlen[]" value="670" checked="checked">
<label for="post-3-0" class="wpgu-onboarding-answer-label">
<span class="wpgu-onboarding-answer-title">Firstitem</span>
</label>
</div>
<div class="wpgu-onboarding-answer" data-bc-answer-post="SecondItem">
<input id="post-3-8" class="wpgu-onboarding-answer-checkbox" type="checkbox" name="posts_stijlen[]" value="681">
<label for="post-3-8" class="wpgu-onboarding-answer-label">
<span class="wpgu-onboarding-answer-title">SecondItem</span>
</label>
</div>
</div>
This could help you.
var inputs = document.querySelectorAll(".wpgu-onboarding-answer-container input:checked+label>span");
var checkbox = [];
inputs.forEach(input=>{
checkbox.push(input.textContent);
console.log(input.textContent)
});
Good lucky!

Shopping Cart Question using radio buttons to retrieve values

I'm building a shopping cart using javascript and html with the goal of merging this into a database after more progress. I have the following HTML for radio buttons:
<!--------------------------------HTML START---------------------------------->
<div class="shop-item">
<span class="shop-item-title">Steak</span>
<div class="shop-item-details">
<span class="shop-item-price">$12.99</span>
<button class="modalbtn-primary shop-item-button-header" type="button" data-modal-target="#modal">ADD TO CART</button> <!--btn btn-primary shop-item-button--->
<div class="modal" id="modal">
<div class="title">How would you like it cooked?
<div class="shop-items">
<div class="shop-item">
<div data-toggle="buttons">
<div class="row">
<input type="radio" class="shop-item-temp" id="temp" name = "temp" value="Wrong">Rare
<input type="radio" class="shop-item-temp" id="temp" name = "temp" value="Medium Rare">Medium Rare
<input type="radio" class="shop-item-temp" id="temp" name = "temp" value="Medium" checked>Medium
<input type="radio" class="shop-item-temp" id="temp" name = "temp" value="Medium Well">Medium Well
<input type="radio" class="shop-item-temp" id="temp" name = "temp" value="Well">Well
</div>
</div>
<!--------------------------------HTML END---------------------------------->
//Then I have the following Javascript to try to get the values
//start javascript for click event to add items to cart. Popup for selecting temperature of meat
function addToCartClicked(event) {
var button = event.target
var shopItem = button.parentElement.parentElement
var title = shopItem.getElementsByClassName('shop-item-title')[0].innerText
//var temp = shopItem.getElementsByClassName('shop-item-temp')[0].checked -- this works but only adds the 1st value Rare
document.getElementById('temp').innerHTML = "";
var temp = document.getElementsByTagName("input");
for(i = 0; i < temp.length; i++) {
if(temp[i].type="radio") {
if(temp[i].checked)
document.getElementById("temp").innerHTML
+= temp[i].name +
+ temp[i].value + "<br>";
}
}
var price = shopItem.getElementsByClassName('shop-item-price')[0].innerText
addItemToCart(title,temp, price)
updateCartTotal()
}
function addItemToCart(title, temp, price) {//temp, , , imageSrc
var cartRow = document.createElement('div')
cartRow.classList.add('cart-row')
var cartItems = document.getElementsByClassName('cart-items')[0]
var cartItemNames = cartItems.getElementsByClassName('cart-item-title')
for (var i = 0; i < cartItemNames.length; i++) {
if (cartItemNames[i].innerText == title) {
alert('This item is already added to the cart')
return
}
}
//end javascript
I get the Steak, price and quantity but I get [object HTMLCollection] instead of the temperature of the steak.
Any help would be appreciated. Thanks!
The "temperature" is the attribute "value" of your radio items.
<input type="radio" class="shop-item-temp" id="temp" name = "temp" value="Medium Rare">Medium Rare
Right after checking that the attribute is "checked" if (temp[i].checked) you can have your temperature like this:
temperature = temp[i].getAttribute("value");
Extra remark, on my code I would prefer using forEach for this kind of for loop.

How to grab values of checkboxes in an array

I have a div as follows:
<div class="questionholder" id="question5" style="display:none">
<div>
<h5>Select all that apply</h5>
<input class="input5" type="checkbox" id="ID1elementColor" name="ID1element" value="color"><label for="ID1elementColor"><p class="radioChoice">Color</p></label>
<input class="input5" type="checkbox" id="ID1elementHeight" name="ID1element" value="height"><label for="ID1elementHeight"><p class="radioChoice">Height</p></label>
<input class="input5" type="checkbox" id="ID1elementWeight" name="ID1element" value="weight"><label for="ID1elementWeight"><p class="radioChoice">Weight</p></label>
</div>
</div>
<div class="holdButtons">
<a class="text2button" onclick="displayquestion(6);">Next</a>
</div>
The user is expected to select all the checkboxes that apply to his situation. Let's assume he selects all 3.
When he clicks "Next", the function displayquestion(); will fire.
function displayquestion(a) {
var Elements = '';
var b = a - 1;
Elements = document.querySelector("#question" + b + " input[name=ID1element]").value;
}
Basically, the function is meant to store all the checked values into var Elements, which is meant to be an array.
However, I'm only getting the value of the first selected answer instead of an array of all selected answers.
How do I grab all the selected answers into an array?
No jQuery please.
Use querySelectorAll to get an array-like NodeList instead of querySelector, and then you can use Array.from to transform that NodeList into an array containing only the .value of the selected inputs:
function displayquestion(a) {
const b = a - 1;
const elements = Array.from(
document.querySelectorAll('#question' + b + ' input:checked'),
input => input.value
);
console.log(elements);
}
<div class="questionholder" id="question5">
<div>
<h5>Select all that apply</h5>
<input class="input5" type="checkbox" id="ID1elementColor" name="ID1element" value="color"><label for="ID1elementColor"><p class="radioChoice">Color</p></label>
<input class="input5" type="checkbox" id="ID1elementHeight" name="ID1element" value="height"><label for="ID1elementHeight"><p class="radioChoice">Height</p></label>
<input class="input5" type="checkbox" id="ID1elementWeight" name="ID1element" value="weight"><label for="ID1elementWeight"><p class="radioChoice">Weight</p></label>
</div>
</div>
<div class="holdButtons">
<a class="text2button" onclick="displayquestion(6);">Next</a>
</div>
Here is the script that you can use for that:
I haven't changed anything in your HTML structure. Except I have removed the display: none; from the style attribute of the class questionholder.
<script>
function displayquestion(b) {
let checkboxList = document.querySelectorAll("#question" + b + " input:checked");
let obj = [];
if (checkboxList.length > 0) { //Code works only if some checbox is checked
checkboxList.forEach(function(item) {
obj.push(item.value); //Contains the value of all the selected checkboxes.
});
}
console.log(obj); //array list containing all the selected values
}
</script>
<div class="questionholder" id="question5" style="">
<div>
<h5>Select all that apply</h5>
<input class="input5" type="checkbox" id="ID1elementColor" name="ID1element" value="color"><label for="ID1elementColor"><p class="radioChoice">Color</p></label>
<input class="input5" type="checkbox" id="ID1elementHeight" name="ID1element" value="height"><label for="ID1elementHeight"><p class="radioChoice">Height</p></label>
<input class="input5" type="checkbox" id="ID1elementWeight" name="ID1element" value="weight"><label for="ID1elementWeight"><p class="radioChoice">Weight</p></label>
</div>
</div>
<div class="holdButtons">
<a class="text2button" onclick="displayquestion(5);">Next</a>
</div>
Here is a JSFiddle link for that.
I hope this is helpful.
So first of I would make a variable for your
<a class="text2button">Next</a>. And I have removed the
onclick="displayquestion(6)" from your html.
Here is the variable.
var text2button = document.getElementsByClassName("text2button")[0];
text2button.addEventListener("click", displayquestion);
Here we have the function, so what I've done is.
I have created a variable var elements = []; Which is a empty array.
Then I create this variable var inputs = document.getElementsByClassName("input5");
This variable gets all the inputs with class input5.
Next I would loop through each of the inputs from the var inputs. Like this.
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
elements.push(inputs[i].value);
}
}
So what I do here is loop through each input for (var i = 0; i < inputs.length; i++) and then I check if any of the inputs are checked if (inputs[i].checked), then I push them to the array var elements with elements.push(inputs[i].value);.
And then I use console.log(elements); so show it in the console.
Check out the snippet below to see it in effect.
Hope this helps.
var text2button = document.getElementsByClassName("text2button")[0];
text2button.addEventListener("click", displayquestion);
function displayquestion() {
var elements = [];
var inputs = document.getElementsByClassName("input5");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
elements.push(inputs[i].value);
}
}
console.log(elements);
}
<div class="questionholder" id="question5">
<div>
<h5>Select all that apply</h5>
<input class="input5" type="checkbox" id="ID1elementColor" name="ID1element" value="color"><label for="ID1elementColor"><p class="radioChoice">Color</p></label>
<input class="input5" type="checkbox" id="ID1elementHeight" name="ID1element" value="height"><label for="ID1elementHeight"><p class="radioChoice">Height</p></label>
<input class="input5" type="checkbox" id="ID1elementWeight" name="ID1element" value="weight"><label for="ID1elementWeight"><p class="radioChoice">Weight</p></label>
</div>
</div>
<div class="holdButtons">
<a class="text2button">Next</a>
</div>

Get the values of column if checkbox/radio box is checked

I was wondering how to get the values in a certain column if the checkbox or radio button on that particular row is checked. I've already started and came up with this:
<script>
var Step = <?php echo $_SESSION['Step'] ?>;
if(Step == 3 || Step == 4 ) { setInterval(ScriptUpdate, 1000); }
function ScriptUpdate()
{
if(Step == 3)
{
var checked = $("input:checkbox:checked").length;
var radioButtonSelectedCount = $(document.querySelectorAll('input[type=radio]:checked')).parent().filter(function() {return $(this).text().trim()=="Yes"}).length;
var Counter = checked + radioButtonSelectedCount;
$('#ES3I').text(Counter + ' Items');
var price = 0;
$("#TextBookTB tr:gt(0) td:nth-child(6)").each(function(td){
var content = $(this).text();
if($.isNumeric(content)) {
price = price + Number(content);
console.log(price);
}
});
$("#ES3P").text(price);
}
}
</script>
The goal is that: when user checks the check box or answered 'yes' in the radio button it is the only time it will count the value. Apologies, I am really bad at jquery/javascript.
EDIT: html code as requested. The current output of the timer takes all of the values in all rows of that particular column.
<label class="radio-inline">
<input form="ES3S" type="radio" name="Textbook'.$i.'" value="'.$Result[$i]['ID'].'"> Yes
</label>
<label class="radio-inline">
<input form="ES3S" type="radio" name="Textbook'.$i.'" value="-1">No
</label>
<span class="d-inline-block" data-toggle="popover" title="Error" data-content="This book is required by the school. If you want to cancel this out, proceed to the principals office with the book for review." data-trigger="hover">
<input form="ES3S" required checked onclick="return false;" type="checkbox" value="'.$Result[$i]['ID'].'" name="Textbook'.$i.'">
</span>
try this if you are using table
var count = 0;
$('#TABLEID').find('tr').each(function () {
var tableRow = $(this);
if (tableRow.find('input[type="checkbox"]').is(':checked')) {
count += 1;
}
});
when user checks the check box or answered 'yes' in the radio button it is the only time it will count the value
$(function() {
var selector = 'input[name^="Textbook"]';
$(selector).on('click', function() {
var checked = $(selector + ':checked').map(function() {
return {
'type': this.type,
'value': this.value
};
}).get().filter(function(o) {
return '-1' !== o.value; // skip if value = -1(No)
});
console.log('checked inputs', checked);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label><input type="radio" name="Textbook1" value="1"/>Yes</label>
<label><input type="radio" name="Textbook1" value="-1"/>No</label>
<input type="checkbox" name="Textbook1" value="1" />
</div>
<div>
<label><input type="radio" name="Textbook2" value="2"/>Yes</label>
<label><input type="radio" name="Textbook2" value="-1"/>No</label>
<input type="checkbox" name="Textbook2" value="2" />
</div>

jQuery - Getting values of text input and checkboxes into one string (or array)

I have three types of items I'm trying to get into a comma-separated string (or array), which I want to display and use to form a URL later.
How can I get these three types of data into the same string or array?
An existing POST string
Free input from a text field with an Add button
The values of a series of checkbokes
Currently, with the code I'm using, adding the form input values overrides the string, and I can't figure out how to remove a checkbox value from the string when its box is unchecked.
Here's the fiddle.
I'm using this HTML:
<div class="srs-display">existingPostString</div>
<ul id="srs" class="srs">
<!-- START TEXT INPUT FIELD -->
<li class="sr">
<div class="masonry-well">
<input id="sr-custom" type="text" placeholder="Add your own">
<a class="add-sr-custom">Add</a>
</div>
</li>
<!-- END TEXT INPUT FIELD -->
<!-- START CHECKBOXES -->
<li class="sr">
<div class="masonry-well">
<input id="srPredefined1" type="checkbox" name="srPredefined1" value="srPredefined1">
<label for="srPredefined1" class="ts-helper">srPredefined1</label>
</div>
</li>
<li class="sr masonry-item">
<div class="masonry-well">
<input id="srPredefined2" type="checkbox" name="srPredefined2" value="srPredefined2">
<label for="srPredefined2" class="ts-helper">srPredefined2</label>
</div>
</li>
<li class="sr masonry-item">
<div class="masonry-well">
<input id="srPredefined3" type="checkbox" name="srPredefined3" value="srPredefined3">
<label for="srPredefined3" class="ts-helper">srPredefined3</label>
</div>
</li>
<!-- END CHECKBOXES -->
</ul>
And here's the JS I tried so far:
$('input[type="checkbox"]').bind('change', function() {
var srs = 'existingPostString';
$('input[type="checkbox"]').each(function(index, value) {
if (this.checked) {
/*add*/ /*get label text associated with checkbox*/
srs += ($(this).val() + ', ');
}
});
if (srs.length > 0) {
srs = srs.substring(0,srs.length-2);
} else {
srs = 'No checks';
}
$('.srs-display').html(srs);
});
$(".add-sr-custom").on('click', function() {
var srs = 'existingPostString';
srs += ',' + $('#sr-custom').val();
$('.srs-display').text(srs);
})
I would push your string elements to an array, and then call array.join(',') on it. Like this:
var srs = [];
//each checkbox
srs.push($(this).val());
//later
var new_string = srs.join(',');
Hi man check this solution:https://jsfiddle.net/leojavier/onwkaLet/6/
var srs = [];
$('input[type="checkbox"]').bind('change', function() {
srs=[]
$('input[type="checkbox"]').each(function(index, value) {
if (this.checked) {
srs.push($(this).val());
}
});
$('.srs-display').html(srs);
});
$(".add-sr-custom").on('click', function() {
$('#sr-custom').val(srs);
})

Categories