I'm new to JavaScript.
I have a webpage that the users can search the document ID and add it to their favourite. after submitting the search criteria, it shows a list ID and a checkbox next to it. so the user can check the checkbox or uncheck it to add and remove them from their list.
My issue is my code can't get the value of the checkbox generated. for example, there are three checkbox generated, chk1,chk2,chk3. when none of them are checked, my code is working I can get the value of the checkbox. but when one of them is checked for example, chk3 is checked, when I check chk1, it still shows the value of chk3 rather than chk1. I want to get the value of that checkbox just checked. I'm struggled to make it right.
<tr><%do until results_rs.EOF%>
<td class="tdid"><%Response.Write results_rs("id")%></td>
<td><input type="checkbox" id="myCheckbox" name ="myf[]" value="<%=results_rs("id")%>" onchange="myfc()">
<script>
function myfc(){
var selchb = getSelectedChbox(this.form);
alert(selchb)
}
function getSelectedChbox(frm) {
var selchbox = null;
var chk_arr=document.getElementsByName("myf[]")
var chklength=chk_arr.length
for (k = 0; k < chklength; k++) {
if (chk_arr[k].checked == true)
selchbox=chk_arr[k].value
}
return selchbox
**strong text**// rs.close;
// connection.close
}
</script></td>
<%results_rs.MoveNext%>
</tr>
The minimal change would be to pass this into myfc:
onchange="myfc(this)"
...and then use that in myfc:
function myfc(cb){
alert(cb.value);
}
But you might look into more modern event handling with addEventListener and such.
Note that there's no need to put an id on the checkbox, and in fact, it's invalid to have more than one checkbox with the same id, so probably best to just remove the id="myCheckbox" part entirely.
IDs in JS must be unique. Use a class class="myCheckbox"
Then you can do
window.addEventListener("load",function() {
var checks = document.querySelectorAll(".myCheckbox");
for (var i=0;i<checks.length;i++) { // all .myCheckbox
checks[i].addEventListener("click",function() {
console.log(this.checked,this.value); // this specific box
var checks = document.querySelectorAll(".myCheckbox:checked");
for (var i=0;i<checks.length;i++) { // all CHECKED .myCheckbox
console.log(checks[i].value); // only checked checkboxes are shown
}
});
}
});
In your case for example
window.addEventListener("load",function() {
var checks = document.querySelectorAll(".myCheckbox");
for (var i=0;i<checks.length;i++) { // all .myCheckbox
checks[i].addEventListener("click",function() {
if (this.checked) myfc(this.value); // this specific box
});
}
});
Related
I wrote a code, that make the button not disabled when you check at least one checkbox with class "sum".
I want to change the code, so I have to classes for and you can check only one checkbox (or two of them) to make the button not disabled.
This is what I have and it works with only one class:
var checkBoxes = $('.sum');
checkBoxes.change(function () {
$('#dashboardbuttonpay').prop('disabled', checkBoxes.filter(':checked').length < 1);
});
$('.sum').change();
});
This is what I tried to do, but OR op does not work:
var checkBoxes = $('.sum' || **'.checkAll'**);
checkBoxes.change(function () {
$('#dashboardbuttonpay').prop('disabled', checkBoxes.filter(':checked').length < 1);
});
$('.sum' || **'.checkAll'**).change();
});
The code works with && operator, but I do not need this.
Using the OR operation on strings this way does not make sense. If you do this with two non-empty strings, you always get the first operand:
console.log('a' || 'b')
In order to select multiple elements, you just separate them by comma:
var checkBoxes = $('.sum, .checkAll');
The code works with && operator, but I do not need this.
Not really. 'a' && 'b' always returns 'b'.
You could check for the amount of checked inputs then add/remove the disabled property in the change event handler.
var checkBoxes = $('.sum','.checkAll');
checkBoxes.change(function () {
if (checkBoxes.filter(':checked').length > 0) {
$('#dashboardbuttonpay').prop('disabled', null);
} else {
$('#dashboardbuttonpay').prop('disabled');
}
});
This way you capture if one or more checkboxes are checked before remove the disabled attribute of the button. Which lets you enable the button with either one or both checkboxes selected.
var checkBoxes = $('.sum','.checkAll');
checkBoxes.change(function () {
if(checkBoxes.filter(':checked').length > 1)
$('#dashboardbuttonpay').prop('disabled',true);
else
$('#dashboardbuttonpay').prop('disabled',false);
});
Here's the JSFiddle of my work: https://jsfiddle.net/pb23Ljd8/5/
I use Bootstrap nav-pills to show all products and categorized too like this:
And I based my checkboxes from here: http://bootsnipp.com/snippets/featured/fancy-bootstrap-checkboxes
I count the number of products checked in between the tabs like this:
jQuery(document).ready(function($) {
jQuery(".select-product").change(function() {
jQuery(".counter").text(jQuery("[type='checkbox']:checked").length);
});
});
But the glyphicon check icons doesn't appear on the second and third tabs for some reason. But when I click the products on the second and third, it increases the counter and also when I view it on the first tab, it is checked.
I just need the products to also be visibly checked on the second and third tabs and not only on the first one so it's not confusing for the user.
Ideas, anyone?
Edit: I fetch the list of products from CMS so it's dynamic. I now understand that the duplication of IDs is causing the problem.
Before we try and resolve this issues, we should break it down and see what the actual problem is.
First, let's check if we remove the content from tab 1b is the issue still present?
Nope, if we remove the checkboxes from the first tab, the checkboxes function normally on the second and third.
Fiddle #1
What if we change the id of the checkboxes (remember ids should be unique).
Notice how Book #1 now works if we change the first checkbox's id to 1a.
Fiddle #2
So now we "know" the issue is likely due to the fact that we are using checkboxes with the same id value (ref). The "issue" is now:
How do we check multiple checkboxes if one is checked
(or something like that)
Here's what I would do:
assign all "like" checkboxes the same class (ex. Book #1 checkboxes will have class b1)
use jQuery/javascript to make sure all that all "like" checkboxes, check and uncheck in unison
Working Example
EDIT
Dynamic values for the classes can be achieved by putting the IDs as classes so the similar products would match. These can be passed to JS like this assuming that $products_id_array is a PHP array that contains all the classes needed.
var productIDs = <?php echo json_encode($products_id_array) ?>;
and then creating the snippet of jQuery code on the fiddle like this
productIDs.forEach(function(val, key) {
jQuery('.' + val).on('change', function(){
jQuery('.' + val).prop('checked',this.checked);
});
})
Try this JS, This will work
jQuery(".select-product").change(function() {
var checkValue = jQuery(this).prop('checked');
$('.select-product#' + jQuery(this)[0].id).each(function() {
if (checkValue == true) {
jQuery(this).prop('checked', true)
} else {
jQuery(this).prop('checked', false);
}
});
var uniqueId = [];
jQuery("[type='checkbox']:checked").each(function() {
uniqueId.push(jQuery(this)[0].id);
});
Array.prototype.getUnique = function() {
var u = {},
a = [];
for (var i = 0, l = this.length; i < l; ++i) {
if (u.hasOwnProperty(this[i])) {
continue;
}
a.push(this[i]);
u[this[i]] = 1;
}
return a;
}
jQuery(".counter").text(uniqueId.getUnique().length);
});
How can I get a value of a checked radio button of a group of related radio buttons without using their ids? I can try something like this, but it is not generic enough.
var boxes = $('input[name=BankAccountTypeGroup]:checked');
$(boxes).each(function () {
if ($(this).val() == 'Savings') {
//
}
})
Radio buttons are grouped by the name attribute, so your current selector should work fine (without even looping) -- if you have multiple groups of common named groups, you can use the ^= (starts with) inside attribute selector to get all the groups.
Example, you have multiple radio groups starting with "BankAccount"
var groups = $(":radio[name^=BankAccount]:checked").map(function() {
return this.value;
}).get();
.map() returns a nice array of all your checked values for radio groups starting with "BankAccount"
var boxes = $('input[name=BankAccountTypeGroup]:checked');
if (boxes.length==1) //test it, maybe there is no radio checked
{
alert(boxes[0].value); //boxes[0] is the first and only-checked element,
}
Try this....
var $boxes = $('#yourcontaineridOfAllCheckboxes').find('input[type=radio]:checked'));
$($boxes).each(function () {
if ($(this).val() == 'Savings') {
//
}
})
I have a series of checkboxes that I populate using a foreach loop (php). The code looks like this:
<input type="checkbox" name="artist_group[]" id="{{$fb_data['fbid']}}" class="input-hidden" data-name="{{$fb_data['name']}}" value="{{$fb_data['fbid']}}" style="display:none;" />
<label for="{{$fb_data['fbid']}}">
<img src="https://graph.facebook.com/{{$fb_data['fbid']}}/picture?width=200&height=200" width="140" height="140" alt="{{$fb_data['name']}}"/>
<article class="artistName">{{$fb_data['name']}}</article>
</label>
What I would like to do is check if any of the checkboxes are checked using javascript. However, I can't do this using the "getElementById" because I want each checkbox to have a unique id (so I can pull the data). I have the name of the checkbox group as an array, so I can send all of the checked boxes to my backend. Can I do the following?:
if (document.getElementByName('artist_group').checked) {
alert("checked");
}
Thank you for your help.
You have iterate over the checkboxes and test whether any of them is checked or not. Note that the method name is getElementsByName (Elements with s):
var boxes = document.getElementsByName('artist_group[]');
var checked = false;
for (var i = 0, l = boxes.length; i < l; i++) {
if (boxes[i].checked) {
checked = true;
break;
}
}
If you are not opposed to newer JavaScript methods, you can also use Array#some:
var checked = Array.prototype.some.call(boxes, function(input) {
return input.checked;
});
With jQuery, it's even simpler:
var checked = $('input[name="artist_group[]"]:checked').length > 0;
Since you tagged jQuery in your question as well, you can use jQuery's $.each.
Just select the elements by the class and not id.
$('.input-hidden').each(function() {
//this will iterate through all checkboxes
if ($(this).is(':checked')) {//Per #Felix's comment, this.checked is a more native way of doing it, I personally just prefer to use $(this) when I'm in jQuery context, to be consistent. Using this.checked is quicker though.
//this will apply just to the checked checkboxes
}
});
You can also get ONLY the selected checkboxes by:
$('input:checked').each(function() {
//this will only apply to selected checkboxes
});
Hope this helps!
As you also used the jQuery tag for your question: IF you're using jQuery anyway (don't just add it only for this task, that's an overkill!):
if ( ! $('input[name="artist_group"]').is(':not(:checked)') ) {
// all are selected
}
each checkbox that i check, i fill the input with it's id
now, how can i retrieve this id that i put inside the input if the user uncheck the checkbox?
exp:
estate SC,SP was checked;
input recieve SC,SP value in this format = SC,SP
but the user uncheck the checkbox with SC value, then SC should be removed from the input.
this is what i'm doing to fill the input with the checkboxes.
var separador = ",";
var estadosS = "";
$(".checkboxEstados").live("click", function(){
if($(this).is(":checked")){
estadosS += (estadosS == "") ? "" : separador;
estadosS += $(this).attr("id");
$("#holdEstados").val(estadosS);
}else{
// now i'm just cleaning all the input,
// but i need to clean only the checkbox that was unchecked
$("#holdEstados").val("");
}
});
dont know if i was clear, any question, be my guest.
Thanks.
An easy way to solve this is to avoid parsing and removing parts of the data. Instead of trying to remove 'SC', instead regenerate the entire contents of the text field each time any checkbox is selected.
When a checkbox click event is detected, deleted the contents of the text input field, scan all of the selected checkboxes, and include their IDs in the text input field.
You're logic can be greatly simplified. Simply grab each checkbox that is checked when the click event fires:
$(".checkboxEstados").live("click", function() {
var aryIds = new Array();
$(".checkboxEstados:checked").each(function() {
aryIds.push($(this).attr("id"));
});
$("#holdEstados").val(aryIds.toString());
});
Here's a working fiddle.
I would store the value in an array and add and remove values from it and then write the array to the output instead of trying to parse the text each time:
var estadosS = [];
$(".checkboxEstados").live("click", function(){
var index;
if($(this).is(":checked")){
// append the id to the list
estadosS.push($(this).attr("id"));
}else{
index = estadosS.indexOf($(this).attr("id"));
if(index > -1) {
estadosS.splice(index, 1);
}
}
$("#holdEstados").val(estadosS.join(separador));
});
If all you are aiming to do is get a list of the checked values from all the check boxes, you could do:
$('.checkboxEstados:checked').each(function(){
alert($(this).val());
});
And that should return all the check box items that have been checked. Then you don't have to worry about adding and removing data from a text box. I'm just alerting the value, you would want to store them into an object or something more useful.