0

I have the following html code:

<?php foreach ($this->tags as $uri=>$tag){?>
    <input type="checkbox" name="tags[]" style="display: none;" value="<?php echo $uri;?>" id="create_<?php echo $uri;?>" <?php echo isset($args['tags']) && in_array($uri, $args['tags'])?'checked="checked"':'';?> />
    <span onclick="selectTag(this.id)" id="create_<?php echo $uri;?>" for="create_<?php echo $uri;?>" class="tag <?php echo isset($args['tags']) && in_array($uri, $args['tags'])?'selected':'';?>"><?php echo str_replace(' ', '&nbsp;', $tag);?></span>
<?php }?>

And here is my JS code:

function selectTag(id) {
    var input = '.tags input#'+id;
    var span = '.tags span#'+id;
    if ($(input).is(':checked') && $(span).hasClass('selected')) {
        $(span).removeClass('selected');
        $(input).attr('checked', false);
    }
    else {
        $(span).addClass('selected');
        $(input).attr('checked', true);
    }
}

When I click on a span box, selects the box, and when I click again on it, it unselects it. The problem is, that after the 3rd time, it just stops working.

What is wrong with my code that is not working?

felipekm
  • 2,820
  • 5
  • 32
  • 42
Monica
  • 1,524
  • 4
  • 27
  • 44

2 Answers2

2

JQuery now has a prop method that is a slightly better alternative to using the attr method.

Try replacing your calls with attr("checked", true); with calls to prop("checked", true);

See here for documentation on prop: http://api.jquery.com/prop/

Here for a discussion between the two: .prop() vs .attr()

Edit:

Also, as Ed Cottrell stated, you'll want to have UNIQUE id attributes for all your elements on your page.

Edit2:

I have created a fiddle that demonstrates this usage: http://jsfiddle.net/xDaevax/E39hc/

Community
  • 1
  • 1
xDaevax
  • 2,012
  • 2
  • 25
  • 36
1

You are giving the input and the span the same id attribute. Ids must be unique per element; you cannot have an input and a span the same id. Doing it this way will cause all sorts of problems, including the behavior you are experiencing. Give one of them a slightly different id (like create_<?php echo $uri;?>_span).

Also, as @xDaevax says, you should use .prop rather than .attr -- I have had the same problem when using .attr.

elixenide
  • 44,308
  • 16
  • 74
  • 100