3

This might be a very easy question, but I find it confusing.

How do I run myFunc() if textField_1 is not empty?

Excicute .on('click', '#openButton', myFunc) if ($('#textField_1').val()!="") ?

2
  • what's the definition of myFunc? Commented Sep 10, 2014 at 13:30
  • 2
    I agree, most jQuery is excruciating. Commented Sep 10, 2014 at 13:33

3 Answers 3

5

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
})
Sign up to request clarification or add additional context in comments.

4 Comments

@Mike -- Always open to suggestions.
User trim, that way we're ensuring that it isn't a useless string. Also, you don't need to check if val != "", the length property is easier to check (it will be a boolean test without having to compare strings)
if(!$('#textField_1').val().trim().length) myFunc();
Np, that's what SO is for, improving all of our code :)
0

Refer 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>

Comments

0

You can test $('#textField_1').val() in an if statement. If it's empty, it'll be treated as false, otherwise it's treated as true.

JS (jQuery):

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

Here's a fiddle.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.