Conditional jquery visibility

I have a scenario where I need to show a bunch of buttons only when ANY of the group of input fields contains a value and hide the buttons when ALL input fields are empty.

It is impossible to come up with an elegant way to do this, except to attach some code to the focus event of the input fields to check their contents and show / hide accordingly.

Is there a better way to do this?

thanks

+4
source share
2 answers

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/

+2
source
 $(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/

+2
source

Source: https://habr.com/ru/post/1346847/


All Articles