1

and when a user re-clicks the element that was already checked, the checkbox will change back to unchecked if it is already checked. how do i do this?

http://jsfiddle.net/DZtwq/

<div class="demo" style="width:520px; height:300px;">


<ol id="selectable">
  <li id="1" class="ui-state-default">1</li>
  <li id="2" class="ui-state-default">2</li>
  <li id="3" class="ui-state-default">3</li>
  <li id="4" class="ui-state-default">4</li>
  <li id="5" class="ui-state-default">5</li>
  <li id="6" class="ui-state-default">6</li>
  <li id="7" class="ui-state-default">7</li>
  <li id="8" class="ui-state-default">8</li>
  <li id="9" class="ui-state-default">9</li>
</ol>


<input id="1" type="checkbox">
<input id="2" type="checkbox">
<input id="3" type="checkbox">
<input id="4" type="checkbox">
<input id="5" type="checkbox">
<input id="6" type="checkbox">
<input id="7" type="checkbox">
<input id="8" type="checkbox">
<input id="9" type="checkbox">


<p id="feedback">
<span>Youve selected:</span> 
<span id="select-result">none</span>.
</p>
</div>

​
arboles
  • 1,321
  • 4
  • 20
  • 39

3 Answers3

1

This will do it:

$('#selectable li').click(function(){
   var id = $(this).attr('id');
    $('input[type=checkbox]').each(function(){
        if ($(this).attr('id')==id) {
           if (this.checked) $(this).removeAttr('checked');
           else              $(this).attr('checked','checked');
        }
    });
});

But please note that your html is not valid. Id values must be unique, and they may not start with a number.

iddo
  • 749
  • 3
  • 11
0

Try this:

http://www.electrictoolbox.com/check-uncheck-checkbox-jquery/

$('input[name=foo]').attr('checked', true);

Also there is this plugin http://archive.plugins.jquery.com/project/checkboxes which you might find interesting

yunzen
  • 32,854
  • 11
  • 73
  • 106
0

This solution will work with the drag-select functionality of selectable()

        $("li", this).each(function() {
            var check = $("#c"+$(this).attr("id"));
            console.log($(check).html());
            if ( $(this).hasClass("ui-selected") ) {
                $(check).attr("checked", true);
            } else {
                $(check).attr("checked", false);
            }
        });

You should avoid using the same id for different elements

a working example : http://jsfiddle.net/Z2s2B/

Matthieu
  • 563
  • 1
  • 7
  • 25
  • when i copy this code onto my local host, i get an error. 'illegal token' in the js on the last line. any idea what could be causing this? its weird because the jquery ui is working on my example, but it wont select anything with your code. – arboles May 18 '12 at 14:07
  • did you remove the console.log() I left ? Depending on your browser, it can throw an error. – Matthieu May 20 '12 at 08:44