Check if textbox is empty before executing jQuery

This may be a very simple question, but I find it confusing.

How do I run myFunc () if textField_1

not empty?

Excicute .on('click', '#openButton', myFunc)

if ($('#textField_1').val()!="")

?

+3


source to share


3 answers


Check inside the handler:



.on('click', '#openButton', function() {
    if( !$('#textField_1').val().trim().length ) myFunc(); //thanks to @Mike for the suggestion on trim and length, see comments
})

      

+5


source


See below code



 <div>
     <div>
         <input type="text" id="text"/>
         <input type="button" value="click" id="click"/>
     </div>
 </div>

 <script type="text/javascript">
 $(document).ready(function () {
    $("#click").click(function () {
        if ($("#text").val() != '') {
            myfunction();
        }
    });
 });
 function myfunction() {
    alert($("#text").val());
 }
 </script>

      

0


source


You can check $('#textField_1').val()

in the instructions if

. If empty, it will be treated as false

, otherwise, it will be treated as true

.

JS (jQuery):

$('#openButton').on('click', function () {
    if ($('#textField_1').val()) {
        myFunc();
    }
});

      

Here's a fiddle .

0


source







All Articles