简体   繁体   中英

jQuery input value not working

Have looked for a solution to this but not found one.

$(document).ready(function() {
    if ($("input").value()) {
        $("h1").hide();
    }
}

So this does not seem to be working ( $("h1").hide() is just a placeholder action... that part is not important, the problem is that the if statement is not working).

There is one form on the page, <input type=text> . I want to make it so that at all times, if there is any text in the input box a certain state is applied. If the input box returns to empty then the state is removed.

There are quite a few other functions inside the $(document).ready function which I omitted due to clarity... but as far as the scope of where the if statement lies it is directly inside of the document.ready function. PS The form is shown and hidden dynamically, but it is hard coded -- it is not being created dynamically.

What is wrong with where I have this if statement located?

Try with .val() like

$(document).ready(function(){
    if ($("input").val()) {
        $("h1").hide();
    }
});

Better you use either name or id or class names as selectors .Because input can be of any number and they also includes checkboxes , radio buttons and button types

In jQuery you have to use .val() method and not .value() . Your check should be as follows:

if ($("input").val()) {
 $("h1").hide();
}

.value() is invalid. You should use .val() instead of .value() . Hope it will make it work?

Unlike .value() in JS , ther's .val() in JQuery .

$(document).ready(function() {
    if ($("input").value()) {
      $("h1").hide();
    }
});

You should use keyup to know when a key is added/removed from the textbox

$(document).ready(function() {
    $("#input_data").keyup(function() {
        var dInput = $(this).val();
        alert(dInput);

    });
});

DEMO

NOTE : Since input can be of any number and checkboxes, radio buttons and button types all are included within the HTML input tag, You should use either name or id or class names as **selectors** .

input[type=text]

or, to restrict to text inputs inside forms

form input[type=text]

or, to restrict further to a certain form, assuming it has id myForm

#myForm input[type=text]

If You want a multiple attribute selector

$("input[type='checkbox'][name='ProductCode']")
//assuming input type as checkbox and name of that input being ProductCode

You should use val at the place of value and the solution is :

$(document).ready(function() {
    if ($("input").val()) {
      $("h1").hide();
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM