繁体   English   中英

表单提交时如何调用函数

[英]How to I call a function when form submit

以下是我在html页面中的部分,该部分将获取阈值并使用该值调用函数

<form id="distance_input" onSubmit="return false;" >  


    <p>Enter a  threshold</p>

    <div class="col-md-8" style="display: inline-block; left:-30px">
    <div class="col-md-4">
    <div class="input-group"> 

      <input type="text" class="form-control" id="usr" class="search" onkeydown="search(this)"> </input>
    <span class="input-group-addon" style="width: 50px">km</span>
    </div> 
    </div>
    <div class="col-md-4" style="padding-left:0px; margin-left:-10px">

     <input type="button" class="btn btn-success" value="Submit" id="myButton"> </input>

    </div>
    </div>
    <p>&nbsp;</p>
     </form> 
<script type="text/javascript">
$('#myButton').click(function(){
        var value = $("input[type=text]").val();
            console.log(value+ " from the submit button");
            set_to_threshold(value);


        });

    function search(ele) {
        if(event.keyCode == 13) {
            console.log(ele.value+" from enter button");   
            set_tothreshold(ele.value);

        }
    } 
</script>

但是当我这样做时,我不会刷新图(set_tothreshold函数在值传递到函数中时获取图的新数据)并显示

Uncaught ReferenceError: search is not defined
    at HTMLInputElement.onkeydown

当我尝试

 <script type="text/javascript">
    $('#myButton').click(function(){
            var value = $("input[type=text]").val();
                console.log(value+ " from the submit button");
                set_to_threshold(value);


            });


    </script>

当我按下提交按钮时也没有发生任何变化(即使在控制台中也不打印值)。但是为什么不打印该值。感谢您的帮助。

这就是你想要的。 表单提交时的yourFunction调用

<form id="distance_input" onSubmit="yourFunction(); return false;" >

  $('#myButton').click(function(){ var value = $("input[type=text]").val(); console.log(value); set_to_threshold(value); }); function set_to_threshold(val){ console.log('do something here with val ', val); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <input type="text" value="input something"/> <button id="myButton">click</button> </body> </html> 

请在文件中包含jquery。 工作正常。

<script
  src="https://code.jquery.com/jquery-2.2.4.min.js"
  integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
  crossorigin="anonymous"></script>

将其包括在html页面的开头部分。 此外,您还引用了未定义的函数set_to_threshold() 因此,只有您遇到了错误。 请为此编写一个函数。 会的!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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