【问题标题】:press button and value increases in text box按下按钮,文本框中的值增加
【发布时间】:2013-03-12 16:32:10
【问题描述】:

因此,当页面加载时,文本框将包含一个存储值。我希望用户按下“+”按钮,文本框中的值将增加一。我猜这是用 JQuery 完成的......到目前为止我有任何关于从哪里开始的想法......

<input type="text" name="BoqTextBox" id="BoqTextBox" value="0" />  
    <input type="Button" value="+" onclick="AddOne(document.getElementById('BoqTextBox').value)" />

    <script>
        function Add(data) {
            //so the current digit is passed to here, where I need to do some funky code
            //where it increments the current digit by one and stores it in BoqTextBox - replacing the old digit.

            //Also to note if the text box contains 124.54 for example and + is pressed
            //then new value will be 125.54
        }
    </script>

在这方面的任何帮助都会很棒。

谢谢

...类似于 data = data + 1,但是如何将值返回到文本框中?

【问题讨论】:

    标签: javascript jquery asp.net html


    【解决方案1】:

    您可以使用 jQuery 的 val() 来获取和设置值。在这种情况下,您需要的代码可能如下所示 (demo):

    <input type="text" name="BoqTextBox" id="BoqTextBox" value="0" />
    <input type="Button" id='AddButton' value="+" />
    <script>
    $('#AddButton').on('click', function () {
        var input = $('#BoqTextBox');
        input.val(parseFloat(input.val()) + 1);
    })
    </script>
    

    【讨论】:

    • 被调用的函数是 AddOne 而你的函数是 Add.. 你真的认为这会起作用吗???
    • 是的,我在尝试设置 JSFiddle 时发现了这一点。应该修复:)
    • @JasonSperske 唯一的问题是,如果我将文本框中的值设置为十进制数。 1.14,然后按+按钮,值跳到2。我需要把它改成2.14,谢谢你的回复。关于这个有什么想法吗?
    • 你可以用parseFloat替换parseInt
    • @Mick,请注意,与 parseFloat() 打交道的工作远不止眼前:stackoverflow.com/questions/15578841/…
    【解决方案2】:
    $('input[type="button"]').on('click', function() {  // bind click event to button
       $('#BoqTextBox').val(function() {      // change input value using callback
          return ++parseFloat( this.value, 10); // make value integer and increment 1
       })
    });
    

    【讨论】:

    • 我喜欢++parseInt() 的做法
    【解决方案3】:

    你正在调用 Addone 函数内联,这意味着你的函数应该是 AddOne()

    试试这个

    function AddOne(obj){
        var value=parseFloat(obj) + 1;
        $('#BoqTextBox').val(value);  
    }
    

    【讨论】:

      【解决方案4】:
       $("#buttonId").click(function()
       {        
          var txtBox = $("#boqtextbox"); 
      
          if(!isNaN(txtBox.val()))
          {
             txtBox.val(parsFloat(txtBox.val())+1) ;
      
          }else 
          {
             //do validation or set it to 0
             txtBox.val(0);
          }|
      
       });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-10-13
        • 2023-03-05
        • 2011-12-17
        • 1970-01-01
        • 1970-01-01
        • 2016-03-06
        • 1970-01-01
        相关资源
        最近更新 更多