简体   繁体   English

在其他输入字段中查找输入值

[英]Find input value in other input fields

I need to check and find if a value of the current input field is found in other input fields on the page.我需要检查并查找当前输入字段的值是否在页面上的其他输入字段中找到。

$(document).on("keyup", "input.card-label", function(){

    var ths = $(this),
    par = ths.closest(".inputContainer"),
    val = ths.val();

    if (ths.closest(".allInput").find("input.card-label").val() != val) {
        par.removeClass("dupe");
    } else {
        par.addClass("dupe");
        fle.prop("disabled", true);
    }
});

I seem to have a partial success.我似乎取得了部分成功。 When I edit a value that's a duplicate, the "dupe" class is removed, but when I intentionally enter a duplicate value, the "dupe" class is not added.当我编辑一个重复的值时,“dupe”类被删除,但当我故意输入重复值时,“dupe”类不会被添加。 What am I missing?我错过了什么?

If I understand correctly, you want a class added when the value of an input is the same as the value of another input.如果我理解正确,当输入的值与另一个输入的值相同时,您希望添加一个类。 The following code adds the keyup event to any input, then loops over all other inputs to determine if the current input's value is a duplicate, in which case it adds a CSS class.以下代码将 keyup 事件添加到任何输入,然后遍历所有其他输入以确定当前输入的值是否重复,在这种情况下,它添加一个 CSS 类。

I have gone for simplicity and just used the input selector.为了简单起见,我只使用了input选择器。 You should be able to tailor this to your needs.您应该能够根据自己的需要进行调整。

 $(function () { $('input').on('keyup', function (e) { // reference to this input var input = $(e.currentTarget) // get all inputs which are not this input var allInputs = $('input').not(this) // loop through all other inputs for (var i = 0; i < allInputs.length; ++i) { // if another input's value is the same as this, add the class if ($(allInputs[i]).val() == input.val()) { input.addClass('dup') } else { // otherwise remove it (if it exists) input.removeClass('dup') } } }) })
 .dup { border-color: red }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" /> <input type="text" />

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

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