【问题标题】:keypress function using name, where more than one same names exists使用名称的按键功能,其中存在多个相同的名称
【发布时间】:2012-06-13 04:11:08
【问题描述】:

HTML

<input name="pm" type="text" value="0"/>
<input name="pm" type="text" value="0"/>
<input name="pm" type="text" value="0"/>

<input name="total" type="text" value="0" disabled="disabled"/>

Javascript

$('[name="pm"]').keypress(function() {

//implementation ?

});

我有三个文本框,默认值=0,当用户写这三个文本框中的任何一个时,总数必须显示在总数文本框中。 所有三个文本框的按键事件都可以正常工作。

【问题讨论】:

    标签: javascript jquery html duplicates


    【解决方案1】:

    简单演示 http://jsfiddle.net/mZBtg/

    请注意:我使用了keyup api,但它会为您提供与您想要的相同的结果。

    http://api.jquery.com/keyup/

    http://api.jquery.com/keypress/

    你也可以做isNumericisNan检查;好链接:$.isNumeric vs. isNaN 另请参阅下面的 cmets。 B-)

    随意玩耍,希望对您有所帮助。

    代码

    $('input[name="pm"]').keyup(function() {
        var sum = 0;
        $('input[name="pm"]').each(function(){
            sum += parseInt(this.value);
        });
       $('input[name="total"]').val(sum);
    });​
    

    【讨论】:

    • http://jsfiddle.net/mZBtg/2/ 小幅改动以避免 NAN 异常
    • @khaled_webdev 非常棒,感谢 bruv,这将为 OP 提供更多的东西 :) 感谢您的评论 B-)
    【解决方案2】:
    $('[name="pm"]').keypress(function() {
      var total = $('[name="total"]');
      total.val(parseInt(total.val(), 10) + parseInt($(this).val(), 10));
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-29
      • 2016-05-03
      • 1970-01-01
      • 2020-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-25
      相关资源
      最近更新 更多