Dynamically loop through checkboxes and get their value and isChecked - javascript

I am dynamically printing out checkboxes depending on list from database, called in the code 'coachProperties'. Each coachProperty will get their own checkbox appended with the text which is unique.
I want to add this to another object 'properties'. Something like 'properties{text1 : "false, text2 : "true"} to then later on take it to server-side to do some filtering. I dont want any sumbit button since i want it to dynimcally update which i have js code for. All values in 'properties' will start with "false" which should update when checkbox is clicked. The problem is, sometimes when I uncheck a box it still displays as true and vice versa.
<div data-id="coachPropertiesCheckbox">
<% coachProperties.get('coachProperties').forEach(function (coachProperty) { %>
<div class="checkboxes">
<label>
<input type="checkbox" data-id="test" value="<%= coachProperty.text %>"> <%= coachProperty.text %>
</label>
</label>
</div>
<% }); %>
</div>
Js code:
function setProp(obj,prop,value){
obj[prop] = value;
};
var properties = {};
coachProperties.get('coachProperties').forEach(function (coachProperty) {
properties[coachProperty.text] = "false";
});
view.$el.find('[data-id="coachPropertiesCheckbox"] div.checkboxes input').change(function () {
var isCheckboxedChecked = view.$el.find('[data-id="test"]').is(':checked');
var valueCheckbox = $(this).attr("value");
setProp(properties, valueCheckbox, isCheckboxedChecked );
$.each( properties, function( key, value ) {
console.log( key + ": " + value );
});
});

Use value property to hold data that you would like to associate with the checkbox and do not use it to toggle true and false. Whether checkbox is checked or not, you can know from the checked property.
A piece of advice, most probably, you'll NOT want to use checkbox label same as value because values are for internal purpose, for any data manipulation, and labels have sole purpose of display in the UI.
Please try the following solution direction:
$('.checkboxes input').on('change', (event) => {
const checked = $(event.target).prop('checked')
const value = $(event.target).prop('value')
console.log(checked, ':', value)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="checkboxes">
<input type="checkbox" id="checkbox1-id" value="checkbox-1" /><label for="checkbox1-id">Checkbox 1</label>
<input type="checkbox" id="checkbox2-id" value="checkbox-2" /><label for="checkbox2-id">Checkbox 2</label>
<input type="checkbox" id="checkbox3-id" value="checkbox-3" /><label for="checkbox3-id">Checkbox 3</label>
</div>

view.$el.find('div.checkboxes input').change(function (event) {
var id = $(event.target).attr('data-id');
if ($(event.target).prop('checked')) {
resultSetParameters.get('filter').coachProperties.push(id);
resultSetParameters.trigger('change');
} else {
var index = resultSetParameters.get('filter').coachProperties.indexOf(id);
if (index > -1) {
resultSetParameters.get('filter').coachProperties.splice(index, 1);
resultSetParameters.trigger('change');
}
}
});

Related

selected checkbox even after reload the page

I need checkbox selected after page reload I am trying this code.
Here my check box
<tr>
<td class="label" style="text-align:right">Company:</td>
<td class="bodyBlack">
<%=c B.getCompanyName() %>
</td>
<td>
<input type="checkbox" class="bodyBlack" id="check" name="all" value='all' onClick="checkBox12()" style="margin-left:-691px">> Show all paid and unpaid transactions
<br>
</td>
</tr>
//here java script code
<script type="text/javascript">
function checkBox12() {
var jagdi = document.getElementById("check").value;
if (jagdi != "") {
document.getElementById("check").checked = true;
}
console.log("jagdi is " + jagdi);
//here my url
window.location.replace("/reports/buyers/statementAccount.jsp?all=" + jagdi);
return $('#check').is(':checked');
}
</script>
Add attribute checked=checked in your html input tag:
<input checked="checked" type="checkbox" class="bodyBlack" id="check" name="all" value='all' onClick="checkBox12()" style="margin-left:-691px"/>
Why don't you use only jQuery ?
function checkBox12()
{
var jagdi = false;
if($("#check").length != 0) // use this if you wanted to verify if the element #check is present
jagdi = $("#check").prop("checked");
//here my url
window.location.replace("/reports/buyers/statementAccount.jsp?all="+jagdi);
}
For answer your question, you can check your checkbox when the document is ready
$(document).ready(function() {
$("check").prop("checked", true");
});
But the better way is to add checked="checked" in your HTML. The checkbox will be checked by default. /!\ input need "/" in close tag
<input type="checkbox" class="bodyBlack" id="check" name="all" value='all' onClick="checkBox12()" style="margin-left:-691px" checked="checked" />
It looks like you are using some other base language. I use php , and it overs POST, GET and SESSION to store values globally and for time you need.
Better find a equivalent function in your language. worth it in long term and on project expansion.
You can store state of checkbox on cookie and repopulate it after page reload.
also there is an example in here HERE!
$(":checkbox").on("change", function(){
var checkboxValues = {};
$(":checkbox").each(function(){
checkboxValues[this.id] = this.checked;
});
$.cookie('checkboxValues', checkboxValues, { expires: 7, path: '/' })
});
function repopulateCheckboxes(){
var checkboxValues = $.cookie('checkboxValues');
if(checkboxValues){
Object.keys(checkboxValues).forEach(function(element) {
var checked = checkboxValues[element];
$("#" + element).prop('checked', checked);
});
}
}
$.cookie.json = true;
repopulateCheckboxes();

How to make jQuery output only one value at a time from .each iteration

I have the following jQuery conditional code which I forked from CodePen. I have extended the code to use a select field as well and everything works fine except that when I use multiple values in data-cond-val jQuery outputs all of the values and only the last value is executed.
For example in the code provided below, when I use data-cond-val="no, maybe", only maybe value is used/executed on event change whether its used on a select option, input check or input radio.
Here's the HTML code
<div id="demo">
<select name="" data-cond="example1">
<option name="example1" data-cond="example1" value="yes">Yes</option>
<option name="example1" data-cond="example1" value="no">No</option>
<option name="example1" data-cond="example1" value="maybe">Maybe</option>
</select>
<div class="conditional" data-cond-opt="example1" data-cond-val="yes">
<label><input type="checkbox" name="example2" data-cond="example2"><span></span> Are you sure?</label>
<label><input type="checkbox" name="example3" data-cond="example3"><span></span> Really super sure?</label>
<div class="conditional" data-cond-opt="example2" data-cond-val="on">
Hooray!
</div>
<div class="conditional" data-cond-opt="example3" data-cond-val="on">
Don't get cocky!
</div>
</div>
<div class="conditional" data-cond-opt="example1" data-cond-val="no, maybe">
<p>
That's a shame. Will you change your mind?
</p>
<label><input type="radio" name="example4" data-cond="example4" value="yes"><span></span> Yes</label>
<label><input type="radio" name="example4" data-cond="example4" value="no"><span></span> No</label>
<label><input type="radio" name="example4" data-cond="example4" value="maybe"><span></span> Maybe</label>
<div class="conditional" data-cond-opt="example4" data-cond-val="yes">
Great!
</div>
<div class="conditional" data-cond-opt="example4" data-cond-val="no, maybe">
Maybe
</div>
</div>
</div>
<script>
$('.conditional').conditionize();
</script>
Here's the jQuery code
(function($) {
$.fn.conditionize = function(options){
var settings = $.extend({
hideJS: true
}, options );
$.fn.showOrHide = function(listenTo, listenFor, $section) {
//checkbox and radio input types
if ($(listenTo + ":checked").val() == listenFor) {
$section.slideDown();
}
// select box
else if ($(listenTo + "option:selected").val() == listenFor) {
$section.slideDown();
} else {
$section.slideUp();
}
}
return this.each( function() {
var listenTo = "[data-cond=" + $(this).data('cond-opt') + "]";
// check if data att has multiple values
var multiVals = $(this).data('cond-val').split(' ').join(',');
var len = multiVals.indexOf(',');
// if data att has multiple values
if ( len > 0 ) {
// create an array from the values
var dataVals = $(this).data('cond-val').split(' ');
var listenFor;
$.each(dataVals, function (i, dataVal) {
listenFor = dataVals[i];
});
} else {
var listenFor = $(this).data('cond-val');
}
var $section = $(this);
//Set up event listener
$(listenTo).change(function() {
$.fn.showOrHide(listenTo, listenFor, $section);
});
//If setting was chosen, hide everything first...
if (settings.hideJS) {
$(this).hide();
}
//Show based on current value on page load
$.fn.showOrHide(listenTo, listenFor, $section);
});
}
}(jQuery));
The Question: How do I make jQuery to take each of the multiple values separately on each event change?
I'm not sure what am messing up in my syntax! I'll be glad if someone can help by showing me how to make it work.
Here is my CodePen forked DEMO - http://codepen.io/peter2015/pen/ZGoJom
In my demo above, When you select No and Maybe, they should both output the same section, but only Maybe option shows the section and No doesn't show anything when selected.
Not sure about this:var multiVals = $(this).data('cond-val').split(' ').join(',');.
A single split should be enough var multiVals = $(this).data('cond-val').split(',');
Or var multiVals = $(this).data('cond-val').replace(/ /g,'').split(','); if you wanna get rid of spaces in the attribute.
http://jsfiddle.net/pwjrev9v/

javascript modify variable

I have this:
var category = "3%2C16%2C6%2C10%2C1%2C19";
in witch category id are 3 16 6 10 1 19 and the %2C is the space between category.
What i want is here:
if (document.getElementById("3").checked = false) {
category = "16%2C6%2C10%2C1%2C19";
}
else {
category = "3%2C16%2C6%2C10%2C1%2C19";
}
I want to make this for all the checkbox that i have, but you can't deselect all the checkbox because the servers don't send you back any data.
This is for filtering the results
It would be easier to use an array, then convert it to this string representation, when needed.
var categories = [];
$('#category-form input').change(function () {
var id = $(this).attr('data-id'),
index = categories.indexOf(id);
if (this.checked && index === -1) {
categories.push(id);
} else if (!this.checked && index !== -1) {
categories.splice(index, 1);
}
});
You can see my working code in this fiddle.
(with multiple checkboxes, string representation, and at least one check)
Try
if (document.getElementById("3").checked === false) {
notice the extra double equals to do a typesafe check
or better still
if (!document.getElementById("3").checked) {
However, as you're using jQuery and you appear to be munging a string together from checked states, which is going to be really brittle with hardcoded strings so maybe something like:
var category = "";
$( "input:checked" ).each(function() {
category = $(this).id + "%2C";
};
Only calling that when you need the output e.g. button press.
As you are using jquery, you can listen to the change event for the checkboxes, then build the list each time one is checked or unchecked. To store the values you can either use the value attribute for the checkbox or add data- attributes.
Getting an array of values and joining them will avoid the trailing %2C.
var category = '';
(function($) {
// cache collection of checkboxes
var cboxes = $('input[type=checkbox]');
cboxes.on('change', function() {
// find the ticked boxes only, and make an array of their category values, then join the values by a space
category = $.makeArray(cboxes.filter(':checked').map(function() {
return $(this).data('category');
//return $(this).val(); // if you store them in value="3"
})).join('%2C');
// output for debug purpose
$('#categoryOutput').html("'" + category + "'");
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<input type="checkbox" id="c1" data-category="3" />
<input type="checkbox" id="c2" data-category="16" />
<input type="checkbox" id="c3" data-category="6" />
<input type="checkbox" id="c4" data-category="10" />
<input type="checkbox" id="c5" data-category="1" />
<input type="checkbox" id="c6" data-category="19" />
</form>
<div id="categoryOutput"></div>
Side Note: try to avoid starting element ids with numbers - it is technically invalid and can break things in some scenarios.

How can to show more than one form value in a alert?

I'm submitting a form which its deleting record.
It's a simple checkbox, if the user check the box then
that record will be deleted from the table , which works.
What I would like to do its have a alert box which shows
the name of the person(s) they are deleting before and then they confirm it which then it will be deleted.
Right now im using ajax to show the alert but its only showing the first record I check ,
It still deleting all the records but I would like it to show all all the names before the user confirm it.
How would I be able to accomplish this?
function sub_keys()
{
alert_string='Are you sure you want to delete ';
var con=confirm( alert_string + document.getElementById("name_id").value + '?');
if(con)
{
var formData = $("#confrm_key").serializeArray();
var URL = 'quality_time_delete_table2.cfc?method=getkeyDetail';
more code.....
}
form:
<input type="hidden" name="name_Id" id="name_id" value="#emp_namefirst# #emp_namelast# ">
You can add a class in your checkboxes and use js querySelectorAll and Array.prototype.map():
var text = document.querySelectorAll('.name');
var values = [].map.call(text, function(obj) {
return obj.innerHTML;
});
confirm(values);
<div class="name">test1</div>
<div class="name">test2</div>
<div class="name">test3</div>
<div class="name">test4</div>
And one example close to your needs:
function deletePeople() {
var text = document.querySelectorAll('input[type=checkbox]:checked');
var values = [].map.call(text, function (obj) {
return obj.value;
});
var res = confirm(values);
res ? alert("records deleted") : alert("no action");
}
<input type="checkbox" value="test1" />
<input type="checkbox" value="test2" />
<input type="checkbox" value="test3" />
<input type="checkbox" value="test4" />
<input type="button" onclick="deletePeople();return false;" value="Delete" />
Also keep in mind that id must be unique.
References:
Array.prototype.map()
document.querySelectorAll

Difficulty inserting variable into jquery attribute identification

I'm trying to us jquery to detect if another text box in the same group is checked. The code below is shows how I'm trying to retrieve the group name when the advanced box is checked and use it to see if the accompanying Basic box is checked. The problem is that "basicTrue" is always assigned "undefined", regardless of the condition of the basic checkbox.
<div id="boxes">
<input style="text-align:center;" type="checkbox" name="group1" value="Basic">
<input style="text-align:center;" type="checkbox" name="group1" value="Advanced">
<input style="text-align:center;" type="checkbox" name="group2" value="Basic">
<input style="text-align:center;" type="checkbox" name="group2" value="Advanced">
</div>
$("#boxes").contents().find(":checkbox").bind('change', function(){
val = this.checked;
var $obj = $(this);
if($obj.val()=="Advanced"){
var group = $obj.attr("name");
var basicTrue = $('input[name=group][value="Basic"]').prop("checked");
if(basicTrue)
{
//Do stuff
}
else
{
$obj.attr('checked', false);
}
}
This code is a proof of concept I used to prove that code formatted this way works, it does return the status of the "Basic" checkbox in "group1".
var basicTrue = $('input[name="group1"][value="Basic"]').prop("checked");
I know the variable "group" is being given the right name: group1 for example. Is there a reason why using this variable in the code wouldn't work?
Those are variables, and they need to be concentenated into the string in the selector, like so:
$('input[name="' + group + '"][value="Basic"]').prop("checked");
A simplified version:
$("#boxes input[type='checkbox']").on('change', function(){
var bT = $('input[name="'+ this.name +'"][value="Basic"]').prop("checked");
if( this.value == "Advanced" && bT) {
//Do stuff
} else {
$(this).prop('checked', false);
}
});

Categories

Resources