I have suppose say 'X' check-boxes(any input elements) in a Form and "M" option selectio开发者_运维问答n indexes ("M" less than equal to "X"). then how do i select the "M" option indexes/values and deselect the rest of check-boxes optimally?
i.e.Suppose I have 10 Checkboxes and 5 Option Indices(eg: 1,2,4,5,8) then i have to select checkboxes with given index .
I could come up with the following code:
HTML:
<div id="Options">
<input id="choice_1" type="checkbox" name="choice_1" value="Option1"><label for="choice_1">Option1</label>
<input id="choice_2" type="checkbox" name="choice_2" value="Option2"><label for="choice_2">Option2</label>
<input id="choice_3" type="checkbox" name="choice_3" value="Option3"><label for="choice_3">Option3</label>
..
..till choice_10
</div>
IN JS:
//Have to select checkboxes with "Value" in choicesToSelect and give a selection
//effect to its label
var choicesToSelect={"Option1","Option9","Option3","Option4","Option2"};
selectHighlightCheckBoxes(choicesToSelect);
function selectHighlightCheckBoxes(choices){
$.each(
choices, function(intIndex, objValue) {
//select based on id or value or some criteria
var option = $("#Options :input[value=" + objValue + "]") ;
if ($(option).is("input[type='radio']") || $(option).is("input[type='checkbox']")) {
$(option).attr('checked', true);
$(option).next('label:first').css({ 'border': '1px solid #FF0000', 'background-color': '#BEF781', 'font-weight': 'bolder' });
} else if ($(option).is("input[type='text']")) {
$(option).css({ 'border': '1px solid #FF0000', 'background-color': '#BEF781', 'font-weight': 'bolder' });
} else {
}
}
);
}
But i want to also add effect to the rest (not in choicesToSelect array) also. (may be red color to those not in choiceToSelect) Can this be done in the one traversal/loop? Optimally? or Better way?
You can trim your code down to this, a bit faster:
var choicesToSelect = ["Option1","Option9","Option3","Option4","Option2"];
selectHighlightCheckBoxes(choicesToSelect);
function selectHighlightCheckBoxes(choices){
$("#Options :input, label").removeAttr('checked').css({'border':'none', 'background-color':'none', 'font-weight':'normal'});
$.each(choices, function(intIndex, objValue) {
var option = $("#Options :input[value=" + objValue + "]"), toStyle = null;
if (option.is(":radio, :checkbox")) {
toStyle = option.attr('checked', true).next('label');
} else if ($(option).is(":text")) {
toStyle = option;
}
toStyle.css({ 'border': '1px solid #FF0000', 'background-color': '#BEF781', 'font-weight': 'bolder' });
});
}
On the first line of the function, it unchecks and removes whatever styling you're applying. Add anything you want the "off" elements to have as well.
On the toStyle
line at the end, I consolidated your CSS to be defined in one spot. In that .css()
call you can set what you want the "on" elements to be, and change or remove styling that the "off" elements have. Here's a page you can play with to see it working :)
精彩评论