Domanda

I'm trying to achieve this but it doesn't work.

Here it is the CSS sheet:

.input_hidden {
    position: absolute;
    left: -9999px;
}

.selected {
    background-color: #000000;
}

#carte label {
    border: inline-block;
    cursor: pointer;
}

#carte label img {
    padding: 3px;
}

the HTML part:

<div id="carte">
    Select a card:<BR>
    <input type=radio name="carte" id="cart1" class='input_hidden' />
    <label for="cart1">
       <img src="cart1.jpg" alt="carte1" />
    </label>
    <input type=radio name="carte" id="cart2" class='input_hidden' />
    <label for="cart2">
       <img src="cart1.jpg" alt="carte2" />
    </label>
    <input type=radio name="carte" id="cart3" class='input_hidden' />
    <label for="cart3">
       <img src="cart3.jpg" alt="carte3" />
    </label>
</div>

and the javascript:

$('#carte label').click(function(){
    $(this).addClass('selected').siblings().removeClass('selected');
});

When I assign the selected class to an image it is ok, I see it with the black border. but it seems the javascript part to assign the class doesn't work. I there any other way to assign the correct classes to the images? Thanks for your support.

È stato utile?

Soluzione

Are you sure you want to use jQuery?

With sane browsers you can solve it with pure css: http://jsfiddle.net/VSR86/4/

HTML:

<div id="carte">

    <label>
        <input type="radio" name="carte" value="cart1" >
        <img src="http://placekitten.com/100/100">
    </label>
    ...

CSS:

label input + img {
  border: 10px solid transparent;
}

label input:checked + img {
  border: 10px solid blue;
}

Of course some javascript fallback will be necessary for IE8 and older.

https://developer.mozilla.org/en-US/docs/Web/CSS/:checked

IE8 fix

Updated CSS:

label input.checked + img,
label input:checked + img {
  border: 10px solid blue;
}

JS fallback:

if(/* this browser is IE8 or worse */){

  $(document).on('click','label:has(input[type="radio"])',function(){
      var $r = $(this).find('input');
      adjustRadio( $r.attr('name'), $r.val(), 'checked');
  });

}


function adjustRadio( name, value, className ){
  // wait for other event handlers to run
  setTimeout( function(){
    $('input[type="radio"][name="'+name+'"]').each( function(){
      var $r = $(this);
      $r.toggleClass( className, $r.val() === value );
    });
  },1);
}

Altri suggerimenti

You could use the toggleClass function for some simplicity :)

http://api.jquery.com/toggleClass/

Since people are picky, here's a fiddle for you sir

http://jsfiddle.net/8B3SW/1/

$('#carte label').click(function(){
    $(this).toggleClass('selected').siblings().removeClass('selected');;
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top