Difficulty inserting variable into jquery attribute identification - javascript

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);
}
});

Related

Dynamically loop through checkboxes and get their value and isChecked

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');
}
}
});

Check checkbox based on variable value

I'm struggling with a checkbox. I want the checkbox to be checked depending on a variable coming from the database. I can see the value in my console, so it's dynamically filled, but I can't have the checkbox checked.
I tried 2 things:
$(document).ready(function() {
$('input[name="OPTIN_NEWSLETTER_STARTER_INDEPENDANT"]').each(function(index) {
if ($(this).val() ==
"%%OPTIN_NEWSLETTER_STARTER_INDEPENDANT%%")
($(this).prop('checked', true));
});
And
$(document).ready(function() {
var checkBox =
[
["OPTIN_NEWSLETTER_STARTER_INDEPENDANT",
"%%OPTIN_NEWSLETTER_STARTER_INDEPENDANT%%"],
];
for (var i = 0; i < checkBox.length; i++) {
if (checkBox[i][1] == "Yes") {
if ($('input[name="' + checkBox[i][0] + '"]'))
{
$('input[name="' + checkBox[i][0] +
'"]').prop("checked", true).change();
}
}
};
This is my html checkbox:
<label class="yesNoCheckboxLabel">
<input type="checkbox"
name="OPTIN_NEWSLETTER_STARTER_INDEPENDANT" id="control_COLUMN136"
label="OPTIN_NEWSLETTER_STARTER_INDEPENDANT"
value="%%OPTIN_NEWSLETTER_STARTER_INDEPENDANT%%"
checked="">OPTIN_NEWSLETTER_STARTER_INDEPENDANT</label>
It would be great to have someone's insights, thanks!
Kind regards,
Loren
I tested your case locally and It's working fine may be you are lacking some where else and make sure use attr in order to set value for jquery 1.5 or below
For jquery 1.5 or below
($(this).prop('checked', true));
$(document).ready(function() {
$('input[name="vehicle1"]').each(function(index) {
if ($(this).val() ==
"vehicle1")
($(this).prop('checked', true));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="checkbox" name="vehicle1" value="vehicle1"> I have a bike<br>
<input type="checkbox" name="vehicle1" value="vehicle1"> I have a car
</form>
and last thing make sure that value must be same for this condition
$(this).val() == "vehicle1"

Check number of checkboxes depending on input

I have this following checkbox on my page
<div class="col-sm-6">
<label>Product Show</label>
<input type="checkbox" name="edprodShow" value="1" >Shape<br>
<input type="checkbox" name="edprodShow" value="2" >Color<br>
<input type="checkbox" name="edprodShow" value="3" >Design<br>
</div>
I would get values like 1 or 2 or 3(Externally, like in a JSON and i would extract that data). I want to set first check box if 1 and 1st and 2nd if two check box and all three if I get 3.(i.e) Get only shape for 1 and color + shape for 2 and color+shape+design for 3
I have tried many sources and ways but not finding the appropriate output how can I do it ?
Edit :
Code I tried to do
if(split_data[7].toString() === "1"){
$('#edprodShow').prop('checked', true);
}else if(split_data[7].toString() === "2"){
}else if(split_data[7].toString() === "3"){
$('#edprodShow').prop('checked', true);
}
where split_data[7] gives me 1,2 or 3
Try this.
Sample Json from server
var json = { edprodShow: [1,2,4]};
Code
var checker = function(data){
$("[name='edprodShow']").attr('checked', false);
$.each(data.edprodShow, function(i, value){
$("[name='edprodShow'][value='"+ value +"']").attr('checked', true);
}
}
Call the function
checker(json);
I got the solution dear ☺
you can do this by javascript :
$(document).ready(function(){
var $checkboxes = $('#devel-generate-content-form td input[type="checkbox"]');
$checkboxes.change(function(){
var countCheckedCheckboxes = $checkboxes.filter(':checked').length;
// $('#count-checked-checkboxes').text(countCheckedCheckboxes);
$('#edit-count-checked-checkboxes').val(countCheckedCheckboxes);
})
Here you can see Demo

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();

Sync Selected Radio Button between 2 radio button groups - Opposites

I need to do something similar to JQuery Sync Selected Radio Button between 2 radio button groups.
I have 2 radio groups -
<input type="radio" name="radio_A" id="radio_A_1" value="1" />1st
<input type="radio" name="radio_A" id="radio_A_2" value="2" />2nd
<input type="radio" name="radio_B" id="radio_B_1" value="1" />1st
<input type="radio" name="radio_B" id="radio_B_2" value="2" />2nd
When radio_A_1 is checked, I need radio_B_2 synced/checked. The relationships would be-
radio_A_1=>radio_B_2
radio_A_2=>radio_B_1
radio_B_1=>radio_A_2
radio_B_2=>radio_A_1
Using the answer provided #8804502
$('input[name=radio_A]').change(function() {
var index = $(this).index('input[name=radio_A]');
console.log(index);
$('input[name=radio_B]:eq(' + index + ')').attr('checked','checked');
});
I get same=>same, but only when A changes-
radio_A_1=>radio_B_1
radio_A_2=>radio_B_2
So if I copy it, changing it if from A=>B to B=>A-
$('input[name=radio_A]').change(function() {
var index = $(this).index('input[name=radio_A]');
console.log(index);
$('input[name=radio_B]:eq(' + index + ')').attr('checked','checked');
});
$('input[name=radio_B]').change(function() {
var index = $(this).index('input[name=radio_B]');
console.log(index);
$('input[name=radio_A]:eq(' + index + ')').attr('checked','checked');
});
I get same=>same, when either A or B changes -
radio_A_1=>radio_B_1
radio_A_2=>radio_B_2
radio_B_1=>radio_A_1
radio_B_2=>radio_A_2
How can I sync them 1=>2/2=>1, instead of 1=>1/2=>2? And can it be done with 1 block of code, instead of 2?
You need to add some code to take the index of the element just clicked and set it to 0 if it is 1, or 1 if it is 0. The first way that came to mind is as follows:
$('input[name=radio_A]').change(function() {
var index = $(this).index('input[name=radio_A]') === 1 ? 0 : 1;
$('input[name=radio_B]:eq(' + index + ')').attr('checked', 'checked');
});
$('input[name=radio_B]').change(function() {
var index = $(this).index('input[name=radio_B]') === 1 ? 0 : 1;
$('input[name=radio_A]:eq(' + index + ')').attr('checked', 'checked');
});
Demo: http://jsfiddle.net/cTQeJ/1/
Though you could also try:
var index = 1 - $(this).index('input[name=radio_A]');
(Or the following demo uses kind of a fun hack if you like to make your code confusing: http://jsfiddle.net/cTQeJ/)
"And can it be done with 1 block of code, instead of 2?"
If you can modify the html slightly it is pretty easy with a single, short code block. Try a change like this:
<input type="radio" name="radio_A" data-sync="1" value="1" />1st
<input type="radio" name="radio_A" data-sync="2" value="2" />2nd
<input type="radio" name="radio_B" data-sync="2" value="1" />1st
<input type="radio" name="radio_B" data-sync="1" value="2" />2nd
I've added a data-sync attribute to each radio button (and removed the id attribute since it wasn't being used, but obviously you can leave that in if needed). Then you can write a simple function like this:
var $radios = $('input[data-sync]');
$radios.change(function() {
$radios.filter('[data-sync="' + $(this).attr('data-sync') + '"]')
.prop('checked', true);
});​
...that basically says whenever any of the radio buttons is checked, find all other radio buttons with a data-sync attribute of the same value and check them too.
Note that this will work with more than two groups, as shown in this demo: http://jsfiddle.net/cTQeJ/2/

Categories

Resources