简体   繁体   中英

how to get value out of input text in javascript

I'm trying to get the value of the userinput, but my code isn't working properly.

html

<body>
<button id="test">test</button>
<form>
    <input type="text" id="test1">
</form>
</body>

javascript:

var text = null;

$(document).ready(function(){
    text = $("#test1").value;
    $("#test").on("click", testing);

});

function testing(){
    console.log("something");
    if(text == "top"){
        console.log("top");
    }
}

in jQuery it's val() , not value , which works on native DOM nodes only

text = $("#test1").val();

And there's really no need for globals here, and you should make sure the value is updated when clicking the button, right now it's only stored on DOM ready

$(document).ready(function(){
    $("#test").on("click", testing);
});

function testing(){
    var text = $("#test1").val();

    if(text == "top"){
        console.log("top");
    }
}

You can use val() :

text = $("#test1").val();

Also you need to move above line inside your testing function to make it check the value of your input when the button clicked. So final code look like:

var text = null;

$(document).ready(function(){
    $("#test").on("click", testing);
});

function testing(){
    console.log("something");
    text = $("#test1").val();
    if(text == "top"){
        console.log("top");
    }
}

Fiddle Demo

Just this will work

$("#test").click(function(){
     var value = $("#test1").val();
     alert(value); check value by alert
});

You can use .val() method in jQuery

See DEMO

 text = $("#test1").val();

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