jquery conditional visibility
I have a scenario where I need to show a bunch of buttons only when ANY of a group of input fields contains a value and hide the buttons when ALL of the input fields are empty.
Can't come up with an elegant way to do that other than by attaching some code 开发者_如何学Pythonto the focus event of the input fields to check their content and show/hide accordingly.
Is there a better way to do this?
thanks
HTML
<form id="myForm">
<input .../>
<select .../>
<!-- etc. -->
</form>
JavaScript
$(function ()
{
var $myForm = $('#myForm'),
$inputs = $myForm.find('input, select'),
$buttons = $('select a bunch of buttons');
$myForm.change(function ()
{
$buttons.toggle(!!$inputs.filter(function ()
{
// NB, using .val() won't work for checkboxes
return !!$(this).val();
}).length);
}).change();
});
http://jsfiddle.net/mattball/BjQaZ/
$(function(){
var $fields = $('input[type=text]'),
$btn = $('#btnid'),
i;
$btn.hide();
$fields.blur(function(){
for(i = 0; i < $fields.length; i++){
if($fields[i].value != '') {
$btn.show();
return;
}
}
$btn.hide();
});
});
http://jsfiddle.net/crVeA/3/
精彩评论