比较keyup函数的表单输入和跨度值 [英] Comparing form input and span value for keyup function

查看:9
本文介绍了比较keyup函数的表单输入和跨度值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格,其中列出了产品的剩余数量,在表格下方有一个输入字段,您可以在表格中输入数量以提交购买.

I have a form that lists a remaining quantity of a product and below it an input field that lets you put a quantity into the form to submit for purchase.

我将剩余数量包裹在带有 ID 的跨度中.在 keyup 上,我想将 span 的值与输入到字段中的输入进行比较.

I have the remaining quantity wrapped in a span with an ID. On keyup, I want to compare the value of the span with the input entered into the field.

如果输入大于span中的值,在keyup上,我想把输入的值改为0或者等价于span ID值.

If the input is greater than the value in the span, on keyup, I want to change the value of the input to 0 or the equivalent of the span ID value.

这是我尝试使用的 javascript:

Here is my javascript I am trying to use to accomplish this:

<script>
$(document).ready(function () {
   document.getElementById('one_and_done_stool_QTY_check').keyup(Qty_check);

    function Qty_check(){
        var QTY1check = document.getElementById('one_and_done_stool_QTY_check').value;
        var QTY1remain = document.getElementById('one_and_done_stool_QTY_remain').innerHTML;

        if (QTY1check.value > QTY1remain.innerHTML)
            alert("NOPE");
            {document.getElementById("one_and_done_stool_QTY_check").value = 0;}
    };}
</script>

这是html:

<span id="one_and_done_stool_QTY_remain">2</span>
<input id="one_and_done_stool_QTY_check" type="text" name="one_and_done_stool">

推荐答案

您的主要问题在这一行:

Your main issue is in this line:

document.getElementById('one_and_done_stool_QTY_check').keyup(Qty_check);

你可以重写:

document.getElementById('one_and_done_stool_QTY_check').onkeyup = Qty_check;

或者您可以直接使用输入事件:

document.getElementById('one_and_done_stool_QTY_check').addEventListener('input', Qty_check);

或jQuery方式:

$('#one_and_done_stool_QTY_check').on('input', Qty_check);

片段:

document.getElementById('one_and_done_stool_QTY_check').addEventListener('input', Qty_check);


function Qty_check(e) {
    var QTY1check = +document.getElementById('one_and_done_stool_QTY_check').value;
    var QTY1remain = +document.getElementById('one_and_done_stool_QTY_remain').textContent;

    if (QTY1check > QTY1remain) {
        console.log("NOPE");
        document.getElementById("one_and_done_stool_QTY_check").value = 0;
    }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<span id="one_and_done_stool_QTY_remain">2</span>
<input id="one_and_done_stool_QTY_check" type="text" name="one_and_done_stool">

这篇关于比较keyup函数的表单输入和跨度值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆