Jquery Checkbox
I have four check boxes and when I click more than two of them then under the last clicked checkbox one I should get a <div><a href="#">Compare</a> </div>
contains a compare link. It may be randomly. I tried to do this using JQuery and below is my code.I need improve one. The issue is I need when two of check box will check under the last one I should get visible the hidden div.
$(document).ready(function() {
$('input[type=checkbox]').change(function(){
if($('input[name=checkbox1]').size() == 1){
$('#checkbox1_compare').show();
}
else {
$('#checkbox1_compare').hide(); 开发者_运维问答
}
})
});
You can check the .length
and use .toggle()
to show/hide based on how many are checked, like this should work:
$(function() {
$('input[type=checkbox]').change(function(){
$('#checkbox1_compare').toggle($('input[name=checkbox1]').length > 1);
});
})
If you need to move the div/link elements to be after the last checked one, something like this would work:
$(function() {
$('input[type=checkbox]').change(function(){
var checked = $('input[name=checkbox1]:checked');
$('#checkbox1_compare').toggle(checked.length > 1)
.insertAfter(checked.last());
});
})
try this: (taken based on the source of @Nick Craver)
html:
<div id="link-compare"><a href="#">Compare</a></div>
js:
$(document).ready(function() {
var refInputCheckbox = $('input[type="checkbox"]');
$(refInputCheckbox).change(function(){
$('#link-compare')
.toggle(
$(refInputCheckbox).filter(':checked').length > 1
);
});
});
精彩评论