I am working on a project where I am creating a series of jQuery checkboxes dynamically within a loop. Here is how I am doing it:
var checkbox = $('<input>').attr({type: 'checkbox', id: checkbox_id);
panel.append(checkbox);
panel.append($('<label>').attr({for: checkbox_id}).html(checkbox_name);
checkbox.button();
In order to customize the styling of these checkboxes, I have a CSS class named my-style
which tweaks attributes such as border-radius
, padding
, and line-height
. My goal is to apply this custom style only to the checkboxes created by my script, without affecting other elements.
I attempted to use checkbox.addClass("my-style");
and
panel.find(".ui-button-text").addClass("my-style")
, however, these methods did not achieve the desired result. Some CSS properties like border-radius
were overridden successfully, while others like line-height
and padding
proved difficult to overwrite. Even directly setting attributes using panel.find(".ui-button-text").css("line-height", 1.0);
did not produce the expected outcome.
One approach I tried was directly specifying the styles within the style
attribute in the HTML markup itself. This solution worked for me but felt somewhat unconventional as it involves mixing JavaScript and CSS code together.
Here is an updated version of the code implementing this method:
var checkbox = $('<input>').attr({type: 'checkbox',
id: checkbox_id});
panel.append(checkbox);
var label = $('<label>').attr({for: checkbox_id,
style: "font-size: 0.6em; border-radius: 0px; margin-right: 0.3em;"}).text(checkbox_name);
panel.append(label);
checkbox.button();
label.children().attr("style", "padding: 0.2em 0.4em;");
While this workaround works, it is not the most elegant solution due to the mixing of JavaScript and CSS. Exploring more specific CSS selectors that can override jQuery UI's default styles has been suggested, but since the checkboxes are generated dynamically with unique IDs, it is challenging to implement more targeted selectors effectively.