JavaScript function only selects first checkbox when told to pre-select more
I have a JavaScript function that dynamically creates checkbox elements when some value from a select box is selected. To verify if a checkbox is checked or not, from PHP I send a variable.
For example: var_id=1,2,3,5
. I use jQuery.inArray
, but I have checked only first checkbox checked from list of five.
This is the function that creates the lis of checkboxes:
function outcheckboxes(_id, _text, var_id) {
(function($){
var topicContainer = jQuery('#classificationss_id');
topicContainer.append(
$('<li />')
.addClass('checkboxclassid')
.append(
$('<input />', {
id: 'classid' + _id,
name: 'classid[]',
value: _id,
type: 'checkbox',
checked: !$.inArray(_id, var_id)
}) 开发者_Python百科
)
.append(
$('<label />', {
'for': 'classid' + _id
}).text( _text)
)
)
})(jQuery)
}
I call the function outcheckboxes
from an other function :
function Classifications(obj_parent, obj_this, obj_child, var_id) {
var catalog_id = jQuery("#"+obj_parent).selectedValues()[0];
jQuery("#classificationss_id").children().remove();
jQuery("#"+obj_this).children().remove();
jQuery("#"+obj_child).children().remove();
if(catalog_id>0){
jQuery.ajax({
type : "GET",
url : "../index.php",
data : "option=com_namecat&view=lists&format=raw&list=classifications&id=" + catalog_id,
dataType : "xml",
success : function(xml) {
var _id = "";
var _text = "";
jQuery(xml).find("row").each( function() {
_id = jQuery(this).find("id").text();
_text = jQuery(this).find("text").text();
jQuery("#"+obj_this).addOption(_id, _text );
outcheckboxes(_id,_text,var_id);
});
}
});
}
}
Where am I going wrong?
Well for one, you should be writing your code like this:
EDIT:
Added shorthand
(function($) {
$('<li />')
.addClass('checkboxclassid')
.append(
$('<input />', {
id: 'classid' + _id,
name: 'classtype[]',
value: _id,
type: 'checkbox',
checked: !$.inArray(_id, var_id)
})
)
.append(
$('<label />', {
'for': 'classid' + _id
}).text( _text)
)
})(jQuery)
精彩评论