Exactly the same javascript but one isn't working? - javascript

I wanted to create a checklist that would move a slider as the user ticked boxes. I found the following 2 pieces of code:
http://jsfiddle.net/t2nvft7q/
$(document).on('click', '.checkBoxLeft', function () {
if ($(this).find('input[type="checkbox"]').is(':checked')) {
$(this).removeClass('checked').addClass('not-checked');
$(this).find('input[type="checkbox"]').attr('checked', false);
} else {
$(this).removeClass('not-checked').addClass('checked');
$(this).find('input[type="checkbox"]').attr('checked', true);
}
});
And then I found this which is more like what I want to do and based on the first one:
http://jsfiddle.net/ezanker/UznQe/
But on the second one if you click one of the boxes, untick it and then tick it again it stops working?
As far as I can tell it's because of that bit of code above. I've commented out things and moving them around to see what runs first, I've tried replacing parts of the second fiddle with the first and as far as I can tell the only difference between the html / css is the second has a value field on the checkboxes but editing this doesn't have any effect.
Could someone point out what I'm missing?

You shouldn't use .attr to set the checked property, use .prop instead. .attr is for setting attribute on the element, and .prop is for settings properties.
Example (JSFiddle):
if ($(this).find('input[type="checkbox"]').is(':checked')) {
$(this).removeClass('checked').addClass('not-checked');
$(this).find('input[type="checkbox"]').prop('checked', false);
} else {
$(this).removeClass('not-checked').addClass('checked');
$(this).find('input[type="checkbox"]').prop('checked', true);
}

You should use .prop, but for the check itself I would just use .hasClass()
Since the code already gives the clicked element the class of checked, there's really no reason to look any deeper than the clicked element which you already have as $(this).
See this working example:
$(document).on('click', '.checkBoxLeft', function () {
if ($(this).hasClass('checked')) { // here use `.hasClass()` for the check
$(this).removeClass('checked').addClass('not-checked');
$(this).find('input[type="checkbox"]').prop('checked', false);
} else {
$(this).removeClass('not-checked').addClass('checked');
$(this).find('input[type="checkbox"]').prop('checked', true);
}
// .....
});

Related

Toggling one thing with two different elements

In my previous question I asked about how can I toggle a textarea with a paragraph. I got the answer. Now I want to do the opposite of it. First I was showing the already hidden textarea + 2 buttons by a click of a hyperlink. Now on the click of one of the buttons I want to hide the text + 2 buttons and show the paragraph that was first already shown.
I have tried this JS so far but it's not working:
$(document).ready(function () {
$(".no_link").click(function (e) {
e.preventDefault();
});
$(".edit_offer").on('click', function () {
toggleEditPanel($(this));
});
$("#cancel_edits").on('click', function () {
$(this).closest("button").hide();
$(this).closest("textarea").hide();
$(this).closest("p.content").show();
});
});
function toggleEditPanel(link) {
link.parent().parent().parent().find("textarea").toggle();
link.parent().parent().parent().find("button").toggle();
link.parent().parent().parent().find("p.content").toggle();
}
But its not working. How can I solve this error?
If I am trying to call the function toggleEditPanel() again. Its not working then aswell.
You can find the markup in the fiddle. Here's the fiddle.
UPDATE 1:
Just came up with a solution. I can use the $.siblings() function to toggle the elements beside the button. Still, is there any better solution?
Here's the code that I came up with:
$("#cancel_edits").on('click', function () {
$(this).hide();
$(this).siblings("button").hide();
$(this).siblings("textarea").hide();
$(this).siblings("p.content").show();
});
UPDATE 2:
The problem in the above code is that if there are more than one panels like this then the code is not working. How can I solve that issue aswell?
You are using Id for selector $("#cancel_edits") .
Id selectors returns only first element , so if there are multiple pannel it will work only for first.
Instead give some class name and use it for selector. Further you can use chaining and caching in your code for better performance.
$(".cancel_edits").on('click', function () {
var elm=$(this);
elm.add(elm.siblings("button,textarea")).hide();
elm.siblings("p.content").show();
});
I would recommend referencing your elements by ID:
$("#cancel_edits").on('click', function () {
$('#save_edits').hide();
$('#edited_content').hide();
$(this).hide();
$("p.content").show();
});
JSFiddle
The great thing about using IDs is that you are guaranteed they are unique - no need to use closest() to find the element you want. If, however, you're using classes instead, closest() might be necessary or helpful.

checkbox running script onclick before actually setting the checked flag

I have a combobox with checkboxes. I am using jQuery to add a Click event to all of the checkboxes. When the checkbox is checked, a script is supposed to run and check an attribute of the checked box to determine it's type and then perform functions accordingly:
function () {
$('.RcbTag').find('input[type="checkbox"]').click(function () {
var evtCB = $(this);
var id = $(this).closest(".rcbSlide").siblings(".RcbTag").attr("id");
var rcbObject = $find(id);
rcbObject.get_items().forEach(
function (item, index) {
if (item.get_attributes().getAttribute('GUIDType') == 'group' &&
item.get_checked()) {
alert("Checked");
}
});
});
The problem right now is that it appears that the script is running before the checkbox is actually flipped to "checked". So in this example, it looks to see if the item attribute is 'group' and if it's checked. This always returns false, but will return true when I uncheck it. So I'm missing some order of events here. How do I fix this?
I think you're mixing jQuery click handlers and the Telerik code. Let's try and just stick with the Telerik-sanctioned events and I think everything will work like you're expecting.
On your RadComboBox, add an event handler declaritively like this:
OnClientItemChecked = "ComboBoxRowClick"
Then declare the JS function as you have it now (except we want to name it and not keep it anonymous):
function ComboBoxRowClick(sender, args) {
if (args.get_item().get_attributes().getAttribute('GUIDType') == 'group' &&
args.get_item().get_checked()) {
alert("Checked");
}
}
For more info on the client side functions from Telerik, you can check this link: http://www.telerik.com/help/aspnet-ajax/listboxitem-client-api.html
Also, you might run into this small annoyance where you have to click in the little checkbox itself, and not anywhere on the row (as one might expect). You can find a workaround for that one here: http://www.msigman.com/2010/07/telerik-radlistbox-fix/
try using change instead of click? that way you will catch changes made via keybord as well. and it will solve ypur problem.

jQuery slideUp() content when clicked for a second time

How would I slideUp() the content only when '.areaCodeList' is clicked a second time?
$(".areaCodeList").on('click', function() {
$(this).next('.churchList').slideDown();
($this.die());
$('.churchList').slideUp();
});
You should use slideToggle()
$(".areaCodeList").on('click', function() {
$(this).next('.churchList').slideToggle();
});
Example
You may use some class to indicate it already clicked before running the code
$(".areaCodeList").on('click', function() {
if (!$(this).is('.clicked')){
$(this).addClass('clicked');
return false;
}
$(this).next('.churchList').slideDown();
$(this).die();
$('.churchList').slideUp();
});
You also may consider using attributes ($(el).attr('clicked')) instead of class and check for it later in a similar way.
Update:
The question title is really confusing and it seems that only many of us (answering the question) don't got it from the start:
Initially I got it like this:
Slide the element up if it clicked for the second time.
If it's the case than the sample I've provided is correct.
But it looks like the question is more like this:
Slide the element down on every even click and slide it up on every odd click.
If this is the case that slideToggle is the solution (as explained in epascarello's answer)
You can check if the .churchList is visible (slided down):
$(".areaCodeList").on('click', function() {
if( $(this).next('.churchList').is(':visible') === true){
$(this).next('.churchList').slideUp();
}else{
$(this).next('.churchList').slideDown();
}
});

If Mouseover Div Equals False - JQuery / Javascript

I'm trying to get this to work:
if($('#myDiv').hover() == false) {
myFunction();
}
Not getting much in the way of errors in Chrome or Firebug consoles. I've had a look at some other posts, and there was an answer that used something like:
if($('#myDiv').is(':hover') == false) {
myFunction();
}
However this also doesn't work.
Here's a jsfiddle if that helps: http://jsfiddle.net/yuwPR/2/
Any ideas greatly appreciated.
Thanks
EDIT:
Thanks for the answers, I wasn't able to get anything working. I'm thinking it might not be possible. Oh well, I'll try something else!
Thanks again
p.s. Most inventive answer marked as right and upvotes all round.
Without knowing your ultimate intent, you could wire up a hover on the document and check the current target.id
$(document).mouseover(function(event) {
if (event.target.id == "myDiv") {
$("body").css("background-color", "red"); //over the div so change the color
return;
}
$("body").css("background-color", "green"); //no on the div
});
code example on jsfiddle.
This code sample sets up a global js variable to store the hover state of the div. Then I use jquery hover to toggle that between true / false. Then, we just fire off a function every 10ms that checks the hover state. Currently I am just setting the window status telling you if you're hovered or not.
var _MOUSEOVER_IN_PROGRESS = false; //stores the hover state
function isover(){
if(_MOUSEOVER_IN_PROGRESS){
window.status = 'Still over!';
} else {
window.status = 'You are not hovering on me!';
}
setTimeout("isover()",10); //checking every 10ms!
}
$(document).ready(function(){
isover();
$('#mydiv').hover(
function(){ _MOUSEOVER_IN_PROGRESS = true; },
function(){ _MOUSEOVER_IN_PROGRESS = false; }
);
});
Edited my code! My mydiv hover catch was not wrapped in a document ready
The hover function takes 2 callback functions:
('#myDiv').hover(function () {
// function to call when hovering
},
function () {
myFunction();
}
);
So, when hovering is "false", ie, on mouse out, the second function will be called.
If you're only interested in doing something when the hover stops, you can use the mouseout() function:
$('#myDiv').mouseout(function() {
myFunction();
}
);
Your first call could never work:
$('#myDiv').hover()
This actually says "trigger the hover event on the element". It does not check to see if your user is currently hovering over the element.
Your second formulation should work:
$('#myDiv').is(':hover')
This checks to see if the element currently has the mouse hovering over it. However, it doesn't seem to work on document load. An example that works can be seen here. If you can clarify what you're trying to do, it might be possible to find some working code in this style.

How can I remove an attribute with jQuery?

I can't seem to get removeAttr to work, I'm using the example I saw on the jQuery site. Basically onclick I add the attribute to disable a field (which works just fine) but when the user clicks again it should enable the field in question. I used alerts to make sure the else block is being fired, so I know that's not it.
Code:
$('#WindowOpen').click(function (event) {
event.preventDefault();
$('#forgot_pw').slideToggle(600);
if('#forgot_pw') {
$('#login_uname, #login_pass').attr('disabled','disabled');
} else {
$('#login_uname, #login_pass').removeAttr('disabled');
}
});
Thanks.
All good used this:
$('#WindowOpen').toggle(
function()
{
$('#login_uname, #login_pass').attr("disabled","disabled");
},
function()
{
$('#login_uname, #login_pass').removeAttr("disabled");
});
Your problem is that the following line of code will always evaluate to true.
if('#forgot_pw')
try replacing with
if($('#forgot_pw').attr('disabled'))
$('#forgot_pw').attr('disabled', false);
should work for you.

Categories

Resources