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);
});
Related
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
});
}
});
I have a standard html from with a couple of radio buttons (3 of them actually).
With:
function abo_show()
{
var x = document.gms_option.gms_element1;
console.log(x.value);
if (x.value = "1") {
document.getElementById("abo").style.display="block";
document.getElementById("gms_abo1").style.display="table-row";
document.getElementById("gms_abo2").style.display="table-row";
document.getElementById("gms_abo3").style.display="table-row";
}
else {
document.getElementById("abo").style.display="block";
document.getElementById("gms_abo1").style.display="table-row";
document.getElementById("gms_abo2").style.display="none";
document.getElementById("gms_abo3").style.display="none";
}
}
I try to show a couple of extra buttons, based on the first 3. The new ones are in a div "abo", that is hidden by default (in css: "display:none").
But when I click on a radio button to select, it executes and jumps to option 1.
No idea why. Could someone explain and help?
x.value = "1" because of this.
you use a single = doing an assignment not a comparison. This causes the if to always succeed. just use == or even ===instead.
You have an easy = in an if statement. Its not compared, it is set.
Your code sets x.value to "1" instead of comparing it.
Use:
if(x.value=="1") {
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') {
//
}
})
The function below allows users to filter products by data-attributes, and accommodates filtering by multiple values simultaneously. It does this by creating an array of the values selected, and when any of the values are clicked (in this case checked/unchecked) it hides all the items and then re-shows those that match the values in the updated array.
It works correctly when filtering for one data-attribute, but when combined to filter by more than one attribute it no longer shows all results matching any of the values and instead only shows results matching all the specified values.
I've posted a fiddle which demonstrates the problem here: http://jsfiddle.net/chayacooper/WZpMh/94/ All but one of the items have the values of both data-style="V-Neck" and data-color="Black" and they should therefore remain visible if either of the filters are selected, but if another value from a different data-attribute some of the items are hidden.
$(document).ready(function () {
var selected = [];
$('#attributes-Colors *').click(function () {
var attrColor = $(this).data('color');
var $this = $(this);
if ($this.parent().hasClass("active")) {
$this.parent().removeClass("active");
selected.splice(selected.indexOf(attrColor),1);
}
else {
$this.parent().addClass("active");
selected.push(attrColor);
}
$("#content").find("*").hide();
$.each(selected, function(index,item) {
$('#content').find('[data-color *="' + item + '"]').show();
});
return false;
});
$('#attributes-Silhouettes *').click(function () {
var attrStyle = $(this).data('style');
var $this = $(this);
if ($this.parent().hasClass("active")) {
$this.parent().removeClass("active");
selected.splice(selected.indexOf(attrStyle),1);
}
else {
$this.parent().addClass("active");
selected.push(attrStyle);
}
$("#content").find("*").hide();
$.each(selected, function(index,item) {
$('#content').find('[data-style *="' + item + '"]').show();
});
return false;
});
});
Both of your handlers are updating the selected array, but only one handler executes on a click. The first one if a color was (de)selected, the second if a style. Let's say you've clicked on "Black" and "Crew Neck". At that time your selected array would look like this: [ "Black", "Crew_Neck" ]. The next time you make a selection, let's say you click "Short Sleeves", the second (style) handler executes. Here's what is happening:
Short_Sleeves gets added to the selected array.
All of the items are hidden using $("#content").find("*").hide();
The selected array is iterated and items are shown again based on a dynamic selector.
Number 3 is the problem. In the above example, a style was clicked so the style handler is executing. Any items in the selected array that are colors will fail because, for example, no elements will be found with a selector such as $('#content').find('[data-style *="Black"]').show();.
I would suggest 2 things.
Keep 2 arrays of selections, one for color, one for style.
Combine your code to use only a single handler for both groups.
Here's a (mostly) working example.
Note that I added a data-type="color|style" to your .filterOptions containers to allow for combining to use a single handler and still know which group was changed.
Here's the full script:
$(document).ready(function () {
// use 2 arrays so the combined handler uses correct group
var selected = { color: [], style: [] };
// code was similar enough to combine to 1 handler for both groups
$('.filterOptions').on("click", "a", function (e) {
// figure out which group...
var type = $(e.delegateTarget).data("type");
var $this = $(this);
// ...and the value of the checkbox checked
var attrValue = $this.data(type);
// same as before but using 'type' to access the correct array
if ($this.parent().hasClass("active")) {
$this.parent().removeClass("active");
selected[type].splice(selected[type].indexOf(attrValue),1);
}
else {
$this.parent().addClass("active");
selected[type].push(attrValue);
}
// also showing all again if no more boxes are checked
if (attrValue == 'All' || $(".active", ".filterOptions").length == 0) {
$('#content').find('*').show();
}
else {
// hide 'em all
$("#content").find("*").hide();
// go through both style and color arrays
for (var key in selected) {
// and show any that have been checked
$.each(selected[key], function(index,item) {
$('#content').find('[data-' + key + ' *="' + item + '"]').show();
});
}
}
});
});
UPDATE: incorporating suggestions from comments
To make the handler work with checkboxes instead of links was a small change to the event binding code. It now uses the change method instead of click and listens for :checkbox elements instead of a:
$('.filterOptions').on("change", ":checkbox", function (e) {
// handler code
});
The "All" options "hiccup" was a little harder to fix than I thought it would be. Here's what I ended up with:
// get a jQuery object with all the options the user selected
var checked = $(":checked", ".filterOptions");
// show all of the available options if...
if (checked.length == 0 // ...no boxes are checked
|| // ...or...
checked.filter(".all").length > 0) // ...at least one "All" box is checked...
{
// remainder of code, including else block, unchanged
}
I also added an all class to the appropriate checkbox elements to simplify the above conditional.
Updated Fiddle
I currently am using this JavaScript code snippet to select 3 checkboxes at a time
$(document).ready(function() {
var $cbs = $('input:checkbox[name="select[]"]'),
$links = $('a[name="check"]');
$links.click(function() {
var start = $links.index(this) * 3,
end = start + 3;
$cbs.slice(start,end).prop("checked",true);
});
});
Currently this code only selects the checkboxes, however I was wondering if anyone knew how to modify it so that it toggles the checkbox selection on and off?
Here's an example of my current code: "jsfiddle" - click the 1-3, 4-6 links etc to check the checkboxes.
Make the second argument to the prop("checked", ...) call depend on the "checked" status of the first (or other) checkbox in the slice:
// ...
$cbs.slice(start,end).prop("checked", !$cbs.slice(start).prop("checked"));
Here's an updated jsFiddle.
[Edit] Or to update each checkbox in the slice individually:
// ...
$cbs.slice(start,end).each(function() {
var $this = $(this);
$this.prop("checked", !$this.prop("checked"));
});
http://jsfiddle.net/ShZNF/3/
$cbs.slice(start,end).each(function() {
if ($(this).is(":checked")) {
$(this).removeProp("checked");
} else {
$(this).prop("checked",true);
}
});
http://jsfiddle.net/ShZNF/1/
Edit: Maeric's solution is better. I wasn't aware removeProp had this gotcha:
Note: Do not use this method to remove native properties such as
checked, disabled, or selected. This will remove the property
completely and, once removed, cannot be added again to element. Use
.prop() to set these properties to false instead.