views:

367

answers:

2

Hi Guys,

I am trying to add a class when a checkbox is "checked" in Safari and remove it when it is unchecked [in other browsers I am using.bind("focus", function() { but in Safari it doesnt work?]

I am currently using

jQuery('.top_class input').bind("focus", function(){
jQuery(this).parents('.row').addClass("add_over"); 
   })
            .bind("blur", function() { 
jQuery(this).parents('.row').removeClass("add_over"); 
   });

This doesnt work in Safari - how to get the code to work in safari ?

A: 

If you are working with a traditional input[type=checkbox] then I think you are looking for the click event, something like this:

jQuery('.top_class').click(function(){
    jQuery(this).closest('.row').toggleClass("add_over", jQuery(this).is(':checked') );
});

To be clear, this will work if this is your checkbox HTML (more or less):

<input type="checkbox" class="top_class" name="whatever" />

UPDATE: Safari may or may not accept focus on a checkbox depending on settings. Since there is no way to test this, I would handle it this way:

var $rows = jQuery('.row'); // Cache all rows
jQuery('.top_class').click(function(){
    var $row = jQuery(this).closest('.row');
    $rows.filter(".add_over").not($row).removeClass("add_over"); // Remove class from other rows
    $row.addClass('add_over');
});

That should do what you want. You can see a DEMO of it working in Safari here: http://jsbin.com/ohuxe/

Doug Neiner
hey I think this works :) but how to do it for "unchecked" ?
Thomas
This should do both if you are using a normal `input` checkbox. Every-time the element is clicked it checks and unchecks. This turns the parent elements class on or off based on checked status.
Doug Neiner
yeah thanks :) is it possible to use something similar - when a user checks the box, then "add over" remains on while it is focused on ".top_class" - if user moves onto another element it removes ? [checkbox is within top_class]
Thomas
Hey, I have an idea, edit your original question and include the HTML from `.top_class` down to the actual `input[checked]` element. I probably can give better advice then.
Doug Neiner
hey updated the code I am using in other browsers - this doesnt work in safari ?
Thomas
yeah thanks but I think there is some problem with .focus() in safari - something about needing to use .change() ?
Thomas
Legend!! Thanks so much :)
Thomas
Haha, glad to help. Good luck on your project.
Doug Neiner
A: 

Have you tried using .bind("click") and checking the checked attribute?

jQuery("input.top_class").bind(
     "click", 
      function() { alert(jQuery(this).attr("checked")) }
     )
Levi Hackwith
@Levi, anything indented one tab or four spaces will be considered a `pre` + `code` block and will retain formatting and indentation.
Doug Neiner