-1

I have the following query code:

function selectTag(id) {
    var input = 'input#tag_' + id;
    var span = '#span_' + id;

    if ($(input).is(':checked') && $(span).hasClass('selected')) {
        $(span).removeClass('selected');
        $(input).prop('checked', false);
    }
    else {
        $(span).addClass('selected');
        $(input).prop('checked', true);
    }
}

and the last part of the conditional is not executing. The check boxes are not being checked or unchecked.

Here is the html.

<?php foreach ($this->tags as $uri=>$tag){?>
     <input type="checkbox" name="tags[]" style="display: none;" value="<?php echo $uri;?>" id="tag_<?php echo $uri;?>" <?php echo isset($args['tags']) && in_array($uri, $args['tags'])?'checked="checked"':'';?> />
     <span onclick="selectTag(<?php echo $uri;?>)" id="span_<?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 }?>
Monica
  • 1,524
  • 4
  • 27
  • 44

1 Answers1

1

You can do it like this: Live Demo

  • There is no need to use onClick attribute when you are using jQuery. You can do it by click event instead. So there is no need to pass element id to the function. $(this) holds the element object and you can access the id attribute by attr('id').

jQuery

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

html

<input type="checkbox" name="tags[]"  value="" id="tag_1" />
<span id="1" for="" class="tag selected">siamak 1</span>

<input type="checkbox" name="tags[]" value="" id="tag_2" />
<span id="2" for="" class="tag selected">siamak 12</span>


<input type="checkbox" name="tags[]" value="" id="tag_3" />
<span id="3" for="" class="tag selected">siamak 3</span>

Also you can get it done another way without id attribute: Live Demo

jQuery

$('span').click(function(){
    var span = $(this);
    var input = $(this).prev();
    if (input.is(':checked') && span.hasClass('selected')) {
        span.removeClass('selected');
        input.prop('checked', false);
    } else {
       span.addClass('selected');
        input.prop('checked', true);
    } 
});

html

<input type="checkbox" name="tags[]"  value=""  />
<span  for="" class="tag selected">siamak 1</span>

<input type="checkbox" name="tags[]" value="" />
<span  for="" class="tag selected">siamak 2</span>


<input type="checkbox" name="tags[]" value="" />
<span  for="" class="tag selected">siamak 3</span>
Siamak Motlagh
  • 5,028
  • 7
  • 41
  • 65