简体   繁体   中英

How to pass a value from textbox into a jQuery function?

I'm trying to figur out how I can set the var number and then use it in my other function Custom.init(number); and make it stay on the page.

//Set number onclick
function setVar() {
    var number = document.getElementById("textbox").value;


    //Pass in number
    jQuery(document).ready(function() {
        Custom.init(number);
    });
};

If you're using jQuery, the ready function should wrap all other functions as it will be invoked first and foremost.

$(document).ready(function(){
   var number = document.getElementById("textbox").value;

   //Then do your validation here
   var setVar = function(){
      Custom.init(number);
      //whatever else is involved with this
    }

})

If that doesn't work I'd check the console for a specific error and ensure your Custom.init function is working as expected.

It doesn't make sense to hide the ready handler inside a function. The comments in your code do also suggest that you wish to call Custom.init in response to a mouse click on some element. You would register an event handler to this end.

A suggested streamlining:

//Set number onclick
$(document).ready(function() {
    $(<selector for clickable elements>).on (
          "click"
        , function (eve) {
              Custom.init(parseInt($("#textbox").val()));
              1;
          }
    );
});

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