I am trying to add javascript validation to a bunch of check boxes, basically what I want is as soon as the user has selected 3 tickboxes, it should disable all of the tickboxes except the three that were ticked.
How could I go about doing that?
Thanx in advance!
The following will disable the rest of the checkboxes if you select 3 of them, and also enable them once you uncheck one of the three selected..
$(':checkbox').click(
function(){
var selected = $(':checkbox:checked').length;
if (selected == 3)
{
$(':checkbox:not(:checked)').attr('disabled',true);
}
else
{
$(':checkbox:not(:checked)').attr('disabled',false);
}
}
);
Live demo
Have on onclick handler that when a checkbox is clicked it ups a counter by one if it is unchecked it decreases the count. After raising the count, test to see if it is three. Then probably the easiest method is to either save the ids of the three checked boxes or save them in the previous step. Then change the click event to return true only if the ids match the saved ids.
Sorry I don't have time right now to actually write up any code. Hopefully this will get you started.
jQuery
$("#container :checkbox").click(function(){
if ($("#container :checkbox").length >= 3) {
$("#container :checkbox").attr("disabled", "disabled");
}
});
Related
Here, I've three radio group in a single page. But in the entire page I want to select only one radio option. Like if I'm selecting Monday then Tuesday selection should be unchecked automatically. How can I proceed with the logic, below logic is not working as expected.
sample JSON :
{
report:[
{
day:'Monday',
slot:[
'9-10am',
'10-11am',
'11-12am'
]
},{
day:'Tuesday',
slot:[
'9-10am',
'10-11am',
'11-12am'
]
},{
day:'Wednesday',
slot:[
'9-10am',
'10-11am',
'11-12am'
]
}
]}
JS code
for(var I=0; I<reports.length; I++){
var radios = document.getElementsByTagName('input')
if(radios[I].type === 'radio' && radios[I].checked){
document.getElementById(radios[I].id).checked = false
}
If you're able to create radio buttons in SurveyJS, you should be able to give the button group a name, so there would be no need for any additional JavaScript. Check out their documentation for an example.
Looks like the sort of nested structure you have for the buttons could be achieved with something like a dynamic panel or cascading conditions in SurveyJS. You should be able to render the available time slots dynamically with "visibleIf" based on the selected day.
I would definitely dig around the documentation of SurveyJS to find a solution there rather than hacking your way around it. But solely as an exercise, the problem in your current code could be that you're selecting a button by ID, which will not work correctly if you have tried to give the same ID to multiple buttons. After all, you already have the target button as radios[I], so you could just use radios[I].checked = false. Or the issue could be that you're unchecking the selected button AFTER the new selection has been made, which might actually uncheck the button you just clicked. Hard to say without additional information, but in any case, looping your inputs based on a value that might be something else than the actual number of inputs (you're using reports.length) is probably not the best idea, since that value might be different from the number of inputs in your form, which would mean that not all of them are included in the loop. Here are a couple of examples of what you could do instead:
// Get all radio buttons
const radioButtons = document.querySelectorAll('input[type="radio"]')
// If you need to uncheck the previously selected one (don't do this if you can avoid it!)
radioButtons.forEach(radioButton => {
// Use a mousedown event instead of click
// This gives you time to uncheck the previous one before the new one gets checked
radioButton.addEventListener('mousedown', () => {
// Get the currently selected button and uncheck it
const currentlySelected = document.querySelector('input[type="radio"]:checked')
if (currentlySelected) currentlySelected.checked = false
})
})
// You can add further options to the querySelector, such as [name]
// This gets the currently selected button in the specified group
const checkedRadioButton = document.querySelector('input[type="radio"][name="group-name"]:checked')
Here's a fiddle demonstrating this sort of "fake" radio button functionality (without a "name" attribute).
You can give all these radio buttons the same name, then one radio only will be checked.
I need to validate the selection of at least one check box on a table. I am not using an alert because I already have a class on CSS that highlights in red the inputs, selects and other elements if they are not filled out.
This is my JS:
var btnRegister= document.querySelector('#btnRegisterRegObr');
btnRegister.addEventListener('click', function () {
var bError= false;
//I am initializing this boolean variable so that it also shows an error
//message on the screen if the user has not selected any option at all...
var elementCheckRegObr = document.querySelector('#checkRegObr');
if (elementCheckRegObr.checked==false){
bError=true;
elementCheckRegObr.classList.add('error');
//This part of the code brings the error I have
//previously created on CSs if the checkbox is not checked
}
else{
elementCheckRegObr.classList.remove('error');
}
});
The button on HTML has the right id on the HTML: id="btnRegisterRegObr.
I was looking at some codes here and people were validating using the .checked==false
However this does not seem to work for mine.
As a matter of fact, I first thought I needed to use the syntax of if (elementCheckRegObr.checked=="") but that one does not seem to work either.
I dont have problems validating inputs, selects nor radio buttons, but I am not sure if I am doing it on the right way with the check boxes. Any help or advice would be greatly apprecciate it :)
I suggest that you use getElementById to get your elements, and test if the checkbox is checked this way:
if(document.getElementById('idOfTheCheckBox').checked){
alert('hey, im checked!');
}
At the moment my code clones 3 dropdowns everytime you click the add button.
I managed to get it to copy the row exactly because before, the first dropdown would reset by itself but the other two would not so I was just wondering how to reset all 3 dropdowns?
It is easiest to see in this JSFiddle:
http://jsfiddle.net/jydqK/7/
So, if you change the first dropdown to agent and then click the + you will see the second row appears duplicated whereas I would like it to reset to tags, operands and values.
Any help greatly appreciated.
You can use removeAttr to remove selected attribute and then fire a change() event.
In your case:
dropdownclone.find('select.tags option:selected').removeAttr('selected');
dropdownclone.find('select.tags option:first').attr('selected','selected');
dropdownclone.find('select.tags').trigger('change');
Modified example: http://jsfiddle.net/ZF3mc/2/
If I understood your question, you want the duplicated row of selects to reset their values.
In this case you can just remove this:
dropdownclone.find('select').each(function(index, item) {
//set new select to value of old select
$(item).val( $dropdownSelects.eq(index).val() );
});
and replace it with:
dropdownclone.find('option').attr('selected', false);
Find all dropdowns in your clone. For each dropdown, check every option tags for a selected attribute and remove it. Something like this:
clone.find('select').each(function() {
$(this).find('option').each(function() {
$(this).removeAttr('selected');
});
});
Or better yet, find only the selected option tags using :selected filter before removing.
I need to collect the values of the checked radio buttons on page load (they are checked on page load) and add them and not only when the user clicks a radio button.
Here's the javascript:
$(function ()
{
updateDivResult();
$('input:radio').live('click',updateDivResult);
$('#1').click();
})
function updateDivResult(){
if ($("input:radio:checked"))
{
price = parseFloat($(this).val());
$('#price').html(roundNumber(price,2));
}
};
roundNumber() is a function defined by me.
Now it only updates the #price div when the user clicks a radio button.
Also, there are a few groups of radio buttons - how do I only add the value of one radio button from the group to the total price?
Thank you for assistance.
I think you need to loop through the checked values rather than just getting the val() of that selector because it seems like there could be more than one checked.
function updateDivResult(){
var price = 0;
$(":radio:checked").each(function(){
price += parseFloat($(this).val());
});
$('#price').html(roundNumber(price,2));
};
Can you provide more details?
I can see you are using jQuery.
You could use
$(document).ready(function() {...});
to run some methods when the document is read.
Moreover you could put a specific class to your html elements and use the "each" function to traverse them.
e.g.
$('.your_el').each(function() {...});
In that case the handler will be executed on each object with the class "your_el".
Hope this help, even if the problem is not so clear to me.
Che
I am trying to bring up a menu when any of the checkbox is selected, as you can see in screenshot below, it shows the number of selections and the menu also disappears when none is select.
I am able to bring up the menu with this code
$("input[name='id[]']").focus(function(){
$("#menu").fadeIn();
});
However, i dont know how to hide it when the checkboxes are unselected and how to count number of selections.
Thank You.
When you check a checkbox, the focus or click event will be triggered. You can count the checked checkboxes with
$("input:checked").length;
If you use that number to hide your menu it should be possible:
$("input[name='id[]']").click(function(){
if($("input:checked").length > 0) { //checked boxes?
if($("#menu:visible").length == 0) { //menu not visible?
$("#menu").fadeIn();
}
} else {
$("#menu").fadeOut();
}
});
To count the number of selections you can use:
$("input[type='checkbox']:checked").length;
So..
$("input[type='checkbox']").click(function(){
if ($("input[type='checkbox']:checked").length < 1)
$("#menu").hide();
});
$("input[name='id[]']").focus(function(){
if ($(this).is(':checked')){
$("#menu").fadeIn();
}else{
$("#menu").fadeOut();
}
});
This should do what you need,
EDIT:
Your selector doesn't seem alright though. You should make it more specific.
for example:
if it starts with id[ you can do it in this way:
$("input[name^=id\\[]")
this will include all input fields their names starting with 'id[' and '\' this is for escaping this '['.
Hope it helps, Sinan.