Hello I have a problem that I am not able to figure out the best way to do it
Currently I have 3 checkbox groups (A, B, C). There is a textbox that is populated based on a dropdown value. This textbox values drives the checkboxes. Some will be enabled and some will be disabled. Sample code below
$('input[type=checkbox]').each(function () {
if ($(this).attr("id").indexOf("cblA") >= 0) {
if ($(this).val() == TextBoxValue) {
$(this).prop('disabled', false);
}
}
if ($(this).attr("id").indexOf("cblB") >= 0) {
if ($(this).val() == TextBoxValue) {
$(this).prop('disabled', false);
}
}
if ($(this).attr("id").indexOf("cblC") >= 0) {
if ($(this).val() == TextBoxValue) {
$(this).prop('disabled', false);
}
}
});
Now the problem is that the validation needs to check all 3 groups. Sometimes it can be that we need to select one from any group or sometimes it could be one from only B. In my database we have a field that contains the validation logic for these checkboxes. They are split by | for an AND condition and a , for an OR condition.
Ex:
A,B,C - select one from any group
A - select one from only A
A|C - select one from A and select one from B
A,C|B - select one from either A or C AND select one from B
I am thinking of first splitting on the | and loop the array. Then an inner loop splitting on ,
var andCond = chkCat.split('|');
$.each(andCond, function (index, value) {
//console.log('value: ' + value);
$.each(value.split(','), function (i, v) {
//console.log('value(' + i + '): ' + v);
});
});
Do I have to dynamically create some boolean variables? Can someone help me with the algorithm? Thanks
Related
I am getting data in an array which I need to bind to the label below is my code. When the array is empty I need to bind no records found which are working but I need to bind the data in the array to the label. Suppose if I have 2 items in the array I need to bind two items i.e slider 1 should have one item and again after sliding to the right I need to bind the second item.
If more than 1 item is there then the right slider should be enabled and if it has only 1 item right slider should be disabled if there are no items both the sliders should be disabled
success: function (response) {
var json = response.d;
if (json.length == 0) {
$('.swiper-wrapper').append('<div class="swiper-slide">No rocords found</div>');
} else {
$.each(json, function (index, item) {
$('.swiper-wrapper').append('<div class="swiper-slide">Name : ' + item.Name + '<br />Number: ' + item.Number + '</div>');
});
}
You could throw a bunch of if else statements
if(length > 1) {
// there is more than one item
} else if(length < 1) {
// there is less than one item
else {
//there is exactly one item
}
I have a bit complex form (includes inputs, textareas, custom selects, etc). I want to perform validation (just to check whether all fields are empty or not). Nothing more.
But I find it difficult to validate whether a radio button was selected or not. I'm using Twitter Bootstrap and I have styled the radio buttons through their javascript and css (btn-group).
I want whenever a user types or clicks something to run the script which checks whether the field is empty or not.
I will post a jsFiddle link below which reproduces my problem. The javascript I use is a bit different, because I want to perform the check only to inputs in the current tab.
$('body').on('keyup mouseup ', 'li, label, input, textarea, select', function (e) {
var tabId = $(this).closest('.tab-pane').attr('id');
var inputs = $('#' + tabId + ' :input');
var errors = {};
inputs.each(function (i, element) {
if ($(element).attr('name') !== undefined) {
if ($(element).attr('type') !== 'radio') {
if ($.trim($(element).val()) === '') {
errors[i] = $(element).attr('name');
}
} else {
if ($('.active', $("input[name='" + $(element).attr('name') + "']").closest('.btn-group')).length <= 0) {
errors[i] = $(element).attr('name');
}
}
}
});
console.log(errors);
if (!$.isEmptyObject(errors)) {
$('a[href="#' + tabId + '"]')
.html("<i class='red ace-icon fa fa-times bigger-120'></i> " + $('a[href="#' + tabId + '"]').text());
} else {
$('a[href="#' + tabId + '"]')
.html("<i class='green ace-icon fa fa-check bigger-120'></i> " + $('a[href="#' + tabId + '"]').text());
}
});
http://jsfiddle.net/gzwyddrc/
To reproduce the problem:
Click on the text field (An alert will tell you that the form is not valid) - OK
Close the alert and type one letter (otherwise you will be annoyed by the alert). The alert will pop out again telling you that the form is still invalid. - OK
Now click on one of the radio buttons. The alert will still tell you that the form is invalid. - NOT OK
If you click on either the text field or one of the radio buttons the alert has something else to say: THE FORM IS VALID! - NOT OK
I believe I've misused the events that I binded to the elements I want to fire that validation.
Ok, I've looked into this, but there were quite a lot of changes I had to make.
This is the code:
$("form").on("keyup mouseup", function (ev) {
var selected, errors = [];
setTimeout(function () {
$("input,select").each(function (i, v) {
var e;
e = $(v);
if (e.attr("name") === undefined) return;
switch (e.attr("type"))
{
case "radio":
selected = false;
e.closest(".btn-group").find("input[type=radio]").each(function (i, v) {
if ($(v).closest("label").hasClass("active"))
{
selected = true;
}
});
if (!selected) {
errors.push(e.attr("id"));
}
break;
default:
if ($.trim(e.val()) === "")
{
errors.push(e.attr("name")); // should be id?
}
break;
}
});
if (errors.length > 0) {
alert("ERRORS: " + errors);
}
}, 10);
});
The changes I made are:
event handlers are attached to the form, this is more convenient especially for multi-form pages (imagine a separate form on the top for login);
the selector also considers select (dropdowns) a possible input field;
minor name/order changes to make it more readable;
the switch replaces the if, because you will encounter more input types further along (switch scales better than if..else);
replaced the error object with an error array on which to push() errors;
when a radio group is unselected, the whole group is invalid, not any single one of the radio buttons nested, so the check should be based on the group as a whole (see use of selected flag);
for radio buttons the active class is toggled on the label not on the input;
finally, the most important feature you'll already have noticed:
Bootstrap itself uses events and JS to toggle the active class, so if you check it right away the label will never have the active class -- to counter this, I inserted a setTimeout() that will fire validation 10 ms later (which still is instantly for humans) so that Bootstrap has all the time to make an update pass over the form before we go in and validate.
I checked it thoroughly in a fiddle, so I'm quite confident it works well and opens up many possibilities you've probably envisioned.
I have 8 check boxes, split into groups of 2. in the first group, I have one checkbox labeled checkbox1 and one labeled checkbox2. I want a JavaScript code that will allow me to be able to check on the form submit whether at least one of 2 of these checkboxes has been checked for each group.
I do not want a script that simply checks to see if you have checked only one checkbox as this will mean the user would not have to check at least one of the other checkboxes in the other group of checkboxes.
Does anyone know of a way of how I can do this please and am I going along the right lines?
$('#form_check').on('submit', function (e) {
if ($("input[id=box1]:checked").length === 0) {
if ($("input[id=box2]:checked").length === 1) {
} else {
if ($("input[id=box2]:checked").length === 0) {
if ($("input[id=box1]:checked").length === 1) {
e.preventDefault();
alert('no way you submit it without checking a box');
return false;
}
}
}
}
});
Do it like this:
$("button").click(function(){
var length = 0; // initial length
$(".group").each(function(){
// if box is checked, add 1, else 0
length += ($(this).find("input:checked").length === 1);
});
// if there are as many box's checked as many groups, i.e. one checked box per group
if(length === $(".group").length){
alert("y");
}else{
alert("no");
}
});
DEMO
What i'm trying to do here is if the selection is equal to value 10 the click function to be available only if selection is equal to 10. But when i change to other ex. category with different value the radio click function is still available. ?
I have 6 radio boxes with value 1,2,3,4,5,6 so what i want to do if value == 4 to slidedown another div while i'm in category with value 10.(selection).
How can i fix this problem ? Here is my sample code.
$('#category').on('change', function () {
var selection = $(this).val();
$('#slidedown'+selection).slideDown(200);
if(selection == '10'){
$("input:radio[name='checkbox']").click(function() {
var radio = $(this).val();
if(radio == '4' && selection == '10') {
$('#slidedown'+selection).slideUp();
} else {
$('#slidedown'+selection).slideDown();
}
});
});
Thanks, any help will be appreciated.
EDIT : I want to slideUp the currect div which is slided down by the category value if radio box with value 4 is checked.
You should have another selection var inside the click callback:
$('#category').on('change', function () {
var selection = $(this).val();
$('#slidedown'+selection).slideDown(200);
});
$("input:radio[name='checkbox']").click(function() {
var selection = $('#category').val(); //This does the trick
var radio = $(this).val();
if(radio == '4' && selection == '10') {
$('#slidedown_another').slideUp();
} else {
$('#slidedown_another').slideDown();
}
});
Also, callbacks must be separated for not binding a new listener each time
Hope this helps. Cheers
Use the disabled property to enable and disable the radio buttons.
$('#category').change(function() {
var selection = $(this).val();
$('#slidedown'+selection).slideDown(200);
$('input:radio[name=checkbox]').prop('disabled', selection != '10');
});
$("input:radio[name='checkbox']").click(function() {
var radio = $(this).val();
if(radio == '4') {
$('#slidedown_another').slideUp();
} else {
$('#slidedown_another').slideDown();
}
});
Your code is adding a handler when the select has the correct value, but it never removes the handler when the select changes to a different value. Also, every time they select 10 it was adding another handler, so the handler would then run multiple times.
I have listview with two checkboxes in itemtemplate.
I want to validate that user can only select only one checkbox in each row.
The behaviour you're describing is accomplished using standard HTML radiobuttons. If you change your design to use these you'll get the benefit that
The user can only select a single item, no extra javascript needed
Users expect to be able to choose multiple checkboxes but only a single radiobutton IE you're working with their expectations
If you're still sure you want to use jQuery then something like this should do it.
$(':checkbox').change(function(){
if($(this).attr('checked')) {
$(this).siblings(':checkbox').attr('checked',false);
}
});
#vinit,
just a little change, you forgot the else part,
$('input:checkbox[id*=EmailCheckBox]').click(uncheckOthercheckbox);
$('input:checkbox[id*=SMSCheckBox]').click(uncheckOthercheckbox);
function uncheckOthercheckbox() {
if (this.id.indexOf("EmailCheckBox") != -1) {
var otherCheckBoxId = this.id.substring(0, this.id.indexOf("EmailCheckBox")) + "SMSCheckBox";
}
else {
var otherCheckBoxId = this.id.substring(0, this.id.indexOf("SMSCheckBox")) + "EmailCheckBox";
}
var i = "#" + otherCheckBoxId;
if (this.checked) {
$(i).removeAttr('checked');
}
else {
if ($(i).attr('checked') === false) {
$(i).attr('checked', 'checked');
}
}
}
Thanks for the reply. had also asked one of my friend and he gave me the following solution which is working fine. Posting it, if anybody needs it.-
say ur checkboxes in the 2 clumns are named EmailCheckBox and SMSCheckBox
then use this code to toggle the checkboxes in each single row:
$('input:checkbox[id*=EmailCheckBox]').click(uncheckOthercheckbox);
$('input:checkbox[id*=SMSCheckBox]').click(uncheckOthercheckbox);
function uncheckOthercheckbox() {
if (this.id.indexOf("EmailCheckBox") != -1) {
var otherCheckBoxId = this.id.substring(0, this.id.indexOf("EmailCheckBox")) + "SMSCheckBox";
}
else {
var otherCheckBoxId = this.id.substring(0, this.id.indexOf("SMSCheckBox")) + "EmailCheckBox";
}
var i = "#" + otherCheckBoxId;
if (this.checked) {
$(i).removeAttr('checked');
}
}