javascript not seeing first click? - javascript

I have a table that the user can select certain rows by checkboxes. I have some javascript that let's them select each checkbox and Select All. I also have some javascript written to let the user check a box then shift-click another checkbox and all the boxes between should become checked.
All this is working the only problem is that the first checkbox isn't being recognized. Thus when the user holds shift and selects another checkbox, only that checkbox is checked. But if the user holds shift and selects a third checkbox, THEN all the boxes between the 2nd and 3rd become checked.
Javascript
$(document).ready(function () {
$(this).click(function () {
//shift-click checkboxes
var lastChecked = null;
var handleChecked = function (e) {
//alert(lastChecked);
if (lastChecked && e.shiftKey) {
var i = $('input[type="checkbox"]').index(lastChecked);
var j = $('input[type="checkbox"]').index(e.target);
var checkboxes = [];
if (j > i) {
checkboxes = $('input[type="checkbox"]:gt(' + (i - 1) + '):lt(' + (j - i) + ')');
} else {
checkboxes = $('input[type="checkbox"]:gt(' + j + '):lt(' + (i - j) + ')');
}
if (!$(e.target).is(':checked')) {
$(checkboxes).removeAttr('checked');
} else {
$(checkboxes).attr('checked', 'checked');
}
}
lastChecked = e.target;
} //handleChecked
$('input[type=checkbox]').click(handleChecked);
}); //$(this).click(function())
//select all checkboxes
$('#selectall').click(function (i, v) {
$('.selectedId').prop('checked', this.checked);
});
var checkCount = $('.selectedId').length;
$('.selectedId').click(function (i, v) {
$('#selectall').prop('checked', $('.selectedId:checked').length == checkCount)
});
}); //ready function
I made a fiddle that replicates the problem.
http://jsfiddle.net/tihg7947/JXnNK/
To replicate my issue, check a box (other than Select All) and then hold shift and select another box.
I'm new to web design and have no idea how to diagnose this issue (event handling?).
I would appreciate any help or guidance.

You are binding $('input[type=checkbox]') inside $(this).click(function () { function thus its not working first time
You bind event inside $(document).ready(function () {
As my understanding remove $(this).click(function () {
Fiddle Demo

You install the handleChecked listener from within $(this).click(function () {. This means that:
The event handler is not installed until the user clicks once.
Multiple copies of the event handler will be installed.
I think you want to just set the event handler once inside $(document).ready(function () {.
So, just delete the lines
$(this).click(function () {
and
}); //$(this).click(function())

Related

How to hide the values in jquery choosen dropdownlistbox?

Hi I am developing one jquery application where I have one choosen dropdownlistbox and gridview. The first column of gridview contains checkboxes and at the top it also contains check all button. For example if I check 3 rows inside the gridview then corresponding values in dropdownlistbox i need to disable. I am trying as below.
This is the code to get all the cheked values from gridview.
var checkedValues = [];
$("#<%=gdvRegretletter.ClientID %> tr").each(function () {
if($(this).closest('tr').find('input[type="checkbox"]').prop('checked', true))
{
checkedValues += $(this).val();
}
});
Once i get values in array and when i go to dropdown i have below code.
$('.limitedNumbSelect').change(function (e) {
$("#limitedNumbSelect > option").each(function () {
//if (this.value == checkedValues) If this.value is equal to any value from checkedValues then i want to hide that value inside dropdownlistbox.
// Here i want to hide all values of checkedValues array(values will be same in dropdownlistbox)
});
});
I tried as below.
$('.limitedNumbSelect').change(function (e) {
var checkedValues = [];
$("#<%=gdvRegretletter.ClientID %> tr").each(function () {
if ($(this).closest('tr').find('input[type="checkbox"]').prop('checked', true)) {
checkedValues.push($(this).closest('tr').find('td:eq(2)').text().trim());
}
});
$(".limitedNumbSelect > option").each(function () {
var val = $(this).val();
alert(val);
var display = checkedValues.indexOf(val) === -1;
$(this).toggle(display);
$('.limitedNumbSelect option[value=' + display + ']').hide();
$(".limitedNumbSelect").find('option:contains(' + display + ')').remove().end().chosen();
});
});
In above code there is one bug. For example if i select one value from gridview then if i click on dropdown i am able to select that value(on first click). On second click required value will hide.
Above code does not work. Array checkedValues doesnt catch values.
I am unable to figure out what to write inside. Any help would be appreciated. Thank you.
Try something like this:
$('.limitedNumbSelect').change(function (e) {
$("#limitedNumbSelect > option").each(function () {
var val = $(this).val();
var display = checkedValues.indexOf(val) === -1;
$(this).toggle(display);
});
});
Replace the line:
checkedValues += $(this).val();
In this line:
checkedValues.push($(this).val());

JavaScript/jQuery: Select on change event not firing

I have this problem trying to getting one single function attach multiple individual functions on "Change" event of a dropdown list using for ... in loop. The $('select') object top has no method 'on' is the Type error detected by Chrome Debugger.
Here is my code: (I don't have much JavaScript / jQuery knowledge so please be bear up with my coding)
function AKaizerDropdown(HiddenFeild) { //#id of hidden field passed as parameter
var select = $('select'); // select object assigned to variable
var selectcount = 0;
var Selecthold=new Array();
for (select in this) {
select.on('change', function() {
var SelectedIndex = this.attr('selectedIndex');
selecthold[selectcount] = [select.attr('id'), selectedindex];
//Select ID and Selected index assigned as an array into Selecthold Array element
});
selectcount +=1;
}
var item= new array();
//Elements in selecthold array printed onto hidden field
for (item in selecthold) {
$(HiddenFeild).val += item[0] + item[1]; //Assigns values to element Hiddenfield in DOM
}
}
Edited Code :
$.fn.AKaizerDropdown = function (HiddenFeild) {
var select_ = $(this).find('select');
var selectcount = 0;
var Selecthold=new Array();
select_.each(function () {
$(this).on('change', function () { //everything runs fine except dropdownlist doesn't enter into this event when an item is chosen
var SelectedIndex = this.selectedIndex;
Selecthold[selectcount] = [this.id, Selectedindex];
});
});
var button_ = $(this).find('input')
button_.on('click', function () {
for (item in Selecthold) {
$(HiddenFeild).val += item[0] + item[1]+','; //Assigns values to element Hiddenfeild in DOM seperated by ","
}
});
}
Somewhat fixed code still doesn't work
Here is the part where i attach it to popover Bootstrap(twitter 2.3.2) .
//think the problem lies here where the pop up seems to re-render the same same html found in ($#KaizerDragon") where all JavaScript is probably discarded?
$("#ContentPlaceHolder1_ADragonTreeviewt41").popover({
html: true, container: 'body',
trigger: 'click',
content: function () {
$(function () {
$("#KaizerDragon").AKaizerDropdown();
});
return $("#KaizerDragon").html();
}
});
So my question is how can I correct the above code to get the intended output(as in comments within code) ?
You are declaring
var select = $('select'); // select object assigned to variable
But then overriding the value in your for loop
for (select in this) ...
That is to say, the select inside the loop isn't the same as you declared above.
try something like this
select.each(function(){
$(this).on('change', function() {
var SelectedIndex = this.selectedIndex;
Selecthold[selectcount] = [this.id, SelectedIndex];
//Select ID and Selected index assigned as an array into Selecthold Array element
});
})

JavaScript while loop get select option and hide option from other select boxes

I'm trying to develop a football teamline function that will store up to 18 players (11 starting players and 7 subs) using a select box for each player.
When a player is selected from one select box they should then be hidden in all the other select boxes to stop the user from being able to select the same player again.
I've written a javascript/jquery function that does this but it is VERY long winded and I'm guessing that the best option to make it a lot more manageable would be to write a while loop but I'm getting myself confused trying to code it.
The current code (for the starting XI) can be seen at http://jsfiddle.net/aFDjS/
Am I right in thinking that what I need to do is probably have a while loop nested inside another while loop to ignore when the count is the same as the player number kind of like this...
i = 1;
playerNo = 1;
while (i < 19) {
while (playerNo < 19 && i != playerNo) {
playerID = $("#player" + i + "Name option:selected").val();
$("select#player" + playerNo + "Name >option" ).filter( "[class='"+ playerID +"']" ).hide();
$("select#player" + playerNo + "Name >option" ).filter( "[class!='"+ playerID +"']" ).show();
playerNo++;
}
i++;
}
Is this along the right lines?
No, you should be using for loops.
The standard is to use for loops when counting something and while loops when you're waiting for an event or value to change.
The logic in those for loops is hard to follow and looks wrong anyway.
But regardless of this, the easiest way to do this is using the power of jquery:
$(function() {
$("select").on("change", function() {
//reset to showing all the options
$("select option").show();
//for each selected option
$("select option:selected").each(function() {
var optionSelected = this;
var playerID = $(this).attr("class");
//hide the option in all the other dropdowns
$("option." + playerID).each(function() {
if(this != optionSelected) {
$(this).hide();
}
});
});
});
});
Working example here:
http://jsfiddle.net/4avwm/1/
Well, don't know what is complete concept of the program, but I think your solution is a bit of overkill.
I would give each checkbox a name (eg.: "plr"+ID) and I would append an onclick event to it. When event is trigered, the checkbox would search for all checkboxes of the same name and disable them.
function selectPlr(event) {
var other = document.getElementsByName(this.name); //Get element collection
for(var i=0; i<other.length; i++) {
if(other[i]!=this) { //Ignore itself
other[i].disabled = this.checked; //Disable if the player is picked, enable if unpicked
}
}
}
Of course, class name can be used instead:
var other = $("input."+this.className);
Here is the active code.
May be this would give you the idea to implement: http://jsfiddle.net/2jGDU/
$('#players').change(function () {
$('#pl_11').prepend($('option:selected', this).clone());
$('option:selected', this).remove();
if ($('option', this).length <= 8) {
$('option:first', this).remove();
$('#sub').prepend($(this).html());
$('option', this).remove();
}
});

clearing radio input using jQuery

I have a bunch of radio buttons that are below. These radio buttons are part of a larger form and are optional, so If a user clicks on one, then decides he/she doesn't want the option selected, there is no way to undo this.
I was wondering if there was any jQuery etc, that, when clicking a link for example, clear any radio selection, based on the group name in the HTML?
Thanks
var group_name = "the_group_name";
// if jquery 1.6++
$(":radio[name='" + group_name + "']").prop('checked', false);
// prev than 1.6
// $(":radio[name='" + group_name + "']").attr('checked', false);
Working demo: http://jsfiddle.net/roberkules/66FYL/
var Custom = {
init: function() {
checkAllPrettyCheckboxes = function(caller, container){
// Find the label corresponding to each checkbox and click it
$(container).find('input[type=checkbox]:not(:checked)').each(function(){
if($.browser.msie){
$(this).attr('checked','checked');
}else{
$(this).trigger('click');
};
});
};
uncheckAllPrettyCheckboxes = function(caller, container){
// Find the label corresponding to each checkbox and unselect them
$(container).find('input[type=checkbox]:checked').each(function(){
$('label[for="'+$(this).attr('id')+'"]').trigger('click');
if($.browser.msie){
$(this).attr('checked','');
}else{
$(this).trigger('click');
};
});
};
I have created it in an init function, and adter then i called the init.
}
window.onload = Custom.init;
I have created a solution like roberkules' solution, except mine clears the radiobutton if you click the radiobutton itself while it's checked. Use this if you don't want to add an extra "Clear" button to your layout.
http://jsfiddle.net/P9zZQ/6/
// Requires JQuery 1.4+ (possibly earlier)
$(function () {
// Turn off a radiobutton if clicked again while on
var checkOff = function (event) {
var target = $(event.target);
if (target.is('label')) {
// deal with clicked label
if (target.attr('for')) {
// label has 'for' attribute
target = $('#' + target.attr('for'));
} else {
// label contains a radiobutton as a child
target = target.find('input[type=radio]');
}
}
if (target.is('input:checked[type=radio]')) {
event.preventDefault();
window.setTimeout(function () {
target.attr('checked', false);
}, 200);
}
}
// Find all radiobuttons and labels inside .radio-clearable containers
$(
'.radio-clearable input[type=radio], ' +
'.radio-clearable label').mousedown(function (event) {
// When clicked -- clear if it was checked
checkOff(event);
}).keydown(function (event) {
// When receiving space, escape, enter, del, or bksp -- clear if it was checked
if (event.which == 32 || event.which == 27 || event.which == 13 || which == 46 || which == 8) {
checkOff(event);
}
});
});
Usage: For any radiobutton you want to be clearable in this manner, wrap it in a container with class "radio-clearable".
The code is triggered by clicking or sending a key (Space, Escape, Enter, Del, BkSp) to the radiobutton element or to its label.

How to uncheck a radio button by clicking on it a second time

I have been searching in a lot of topics but I haven't found anything that really correspond to my problem :
I want to make radio buttons uncheckable (i.e. uncheck a radio button by clicking on it when it's already checked).
I found some solutions using a hidden radio button as a temporary comparison object but this doesn't fits to my existing context, so I would like to do the same without another radio button.
I tried to simply test and change the status/value of the radio button on "onclick" event but it hasn't been very successfull...
Thanks in advance,
Clem.
That's not what radio buttons are. If you try to make this work, you will just confuse your users.
If you want something that can be checked and then unchecked, use a checkbox. Radio buttons are for selecting exactly one of some set of options.
better so:
onclick="
var isChecked = $(this).attr('is_che');
if (isChecked) {
$(this).removeAttr('checked');
$(this).removeAttr('is_che');
}
else {
$(this).attr('checked', 'checked');
$(this).attr('is_che', 'true');
}"
I know this sort of action is non-standard for radio buttons, but the poster requested the functionality. The following is code that I've used in the past. I've found it not to be the most optimized (assuming a large # of radio buttons), but I also haven't taken the time to do that optimization.
// Allow for radio button unchecking
$(function(){
var allRadios = $('input[type=radio]')
var radioChecked;
var setCurrent = function(e) {
var obj = e.target;
radioChecked = $(obj).attr('checked');
}
var setCheck = function(e) {
if (e.type == 'keypress' && e.charCode != 32) {
return false;
}
var obj = e.target;
if (radioChecked) {
$(obj).attr('checked', false);
} else {
$(obj).attr('checked', true);
}
}
$.each(allRadios, function(i, val) {
var label = $('label[for=' + $(this).attr("id") + ']');
$(this).bind('mousedown keydown', function(e){
setCurrent(e);
});
label.bind('mousedown keydown', function(e){
e.target = $('#' + $(this).attr("for"));
setCurrent(e);
});
$(this).bind('click', function(e){
setCheck(e);
});
});
});

Categories