jQuery。在按钮单击事件上获取文本输入字段的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10791811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:46:00  来源:igfitidea点击:

jQuery. Get text input field's value on button clicking event?

jquery

提问by gilzero

html:

html:

<div id="search">
  <input id="term" type="text" value="enter your search" />
  <button id="hit" type="button" name="">Search</button>
</div>

jQuery:

jQuery:

$(document).ready(function() {
  var term = $('#term').val();
  $('#hit').click(function() {
    alert(term);
  });
});

The problem is that , no matter what I type in the input field, then hit the button, it always alert the original input value which is "enter your search".

问题是,无论我在输入字段中输入什么,然后点击按钮,它总是提醒原始输入值“输入您的搜索”。

How can I fix it?

我该如何解决?

回答by Aaron

The problem you're having is that this whole block of code gets executed on the DOM ready event.

您遇到的问题是整个代码块都在 DOM 就绪事件上执行。

var term = $('#term').val();is being evaluated only once and storing 'enter your search' in the term variable. This is why no matter what you change the value to, the variable still holds the initial value when the page was rendered.

var term = $('#term').val();仅被评估一次并将“输入您的搜索”存储在 term 变量中。这就是为什么无论您将值更改为什么,该变量在呈现页面时仍然保持初始值。

Instead what you should do is something more like the following:

相反,您应该做的是更像以下内容:

JQuery

查询

$(document).ready(function() {
  $('#hit').click(function() {
    alert($('#term').val());
  });
});

In this bit of code, the value of the element with id term is evaluated when the click event listener fires.

在这段代码中,当单击事件侦听器触发时,会评估具有 id term 的元素的值。

回答by rjmcb

Because you created the variable just when the document is ready.. try to create the variable "term" inside the click function...

因为您在文档准备就绪时创建了变量.. 尝试在点击函数中创建变量“term”...

  $(document).ready(function() {
      $('#hit').click(function(event) {
          var term = $('#term').val();
          alert(term);
      });
  });?

回答by ahren

You need to get the value on click, rather than document ready

您需要获取 上的值click,而不是document ready

$(document).ready(function() {
  $('#hit').click(function() {
    var term = $('#term').val();
    alert(term);
  });
});

回答by lilhamad

This worked for me after trouble For int

这在遇到麻烦后对我有用 For int

  function getValue(){
         $("qty").value = parseInt($("qty").value);
  }

For string

对于字符串

function getValue(){
             $("qty").value = $("qty").value;
}