I am trying to use jquery to:
1- dynamically add a checkbox
2- position it correctly.
So far I can do 1 or 2 but not 1 and 2.
Here is my HTML code:
<!-- language: lang-html -->
<body>
<div id='myDiv'></div>
<div id='myOtherDiv'>
<button id='myButton'>my button</button>
</div>
</body>
and here is my js code:
<!-- language: lang-js -->
jQuery(document).ready(
function ($)
{
jQuery.noConflict();
function createCheckbox()
{
var $myCheckbox = $('<input id="myCheckbox" type="checkbox"></input><label for="myCheckbox">my checkbox</label>');
$('#myDiv').append($myCheckbox);
/*
The following line fixes the "button displayed as unpressed" problem
but it breaks the .position call
*/
// $myCheckbox = $('#myDiv > input');
/* myCheckbox */
$myCheckbox.button({
text: false,
icons: { primary: "ui-icon-refresh"}
});
$myCheckbox.change(
function()
{
if($myCheckbox.is(":checked"))
{ alert('checked'); }
else
{ alert('unchecked');}
}
);
var $myButton = $('#myButton');
$myCheckbox.position({my:"left", at:"right", of:$myButton });
}
createCheckbox();
});
The code above works but after clicking on the checkbox and clicking “OK” on the “checked” alert, the jquery checkbox button is displayed as unchecked even though the actual checkbox is checked.
By trial and error I fixed that problem by reselecting my checkbox after append. I am not sure why that works though.
$myCheckbox = $('#myDiv > input');
When I uncommenting the line above, then the checkbox behaves properly and is displayed as checked when it is checked. But then the call to .position does not position the checkbox button properly.
see: http://jsfiddle.net/roumbaba/uM3sS/1/
note: This problems only occurs when i dynamically add an input/checkbox. If I only add a simple button (using a plain instead of then both position and checked display satus work fine.
I am clearly missing something major here in how the whole process works. In particular I do not understand why reselecting my checkbox with the line
$myCheckbox = $('#myDiv > input');
changes the behavior of the check status button. And why does position not work after I do that.
The position problem was that I used .position on the checkbox but should have used it on the checkbox’s label instead. Apparently jqueryui uses the checkbox’s label and not the checkbox itself to display it’s button.
this fixes the position problem while still keeping the checkbox status properly working.
I am still unclear as to why I have to first append my checkbox to the dom and then select it again in order to have a properly functioning checkbox/button after calling .button though.