dqcuq4138 2016-06-27 01:12
浏览 35
已采纳

检查多个输入是否具有相同值的最佳方法

I have some inputs (random number > 0) and each is inside a div with same class so I have this structure:

<div class="myclass"> <!-- div #1 -->
    <input name="name" class="input">
    <!-- other inputs that don't take care -->
</div>
...
<div class="myclass"> <!-- div #n -->
    <input name="name" class="input">
    <!-- other inputs that don't take care -->
</div>

I need to check that the value of every input doesn't match with other, so if I have in the first input myname as value in the input n I can't have myname.

I have the next JQuery code to iterate over all divs to extract the info about every div.

$('.myclass').each(function() {
    input = $(this).find('input[name="name"]').val();
});

And then, it sends all info (JSON parsed before) through jQuery ajax to PHP scripts which MUST revalidate that input values don't be equal.

So, the question is: what's the best way to go over all divs and know if value is repeated? I thought about making a $.each inside the each I have to iterate over all elements but I don't know about its performance.

And what about with PHP script, what's the best way to afford it? Thank you.

NOTE: JSON parsed array, now have this structure:

{"user_info":{"app_id":0,"user_id":0},"contact":{"has_contact":0},"menu_items":[{"position":0,"name":"Nosotros","icon_id":"ic_delete_black_48dp.png","content":"nosotros"},{"position":1,"name":"Precios","icon_id":"ic_help_black_48dp.png","content":"nosotros"}]}

Don't worry about "user_info" and "has_contact" they are irrelevant, the name for which I was talking is the menu_items[index]['name'] value.

  • 写回答

3条回答 默认 最新

  • douyu1656 2016-06-27 01:22
    关注

    You can use $.map(), .slice(), $.unique(), .length

    // return `input` values
    var inputs = $.map($(".myclass input"), function(el) {return el.value});
    // check if `unique` array `.length` is equal to `unique` array `.length`
    var unique = $.unique(inputs.slice(0)).length === inputs.length;
    
    console.log(inputs, unique);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="myclass"> <!-- div #1 -->
        <input name="name" class="input" value="abc">
        <!-- other inputs that don't take care -->
    </div>
    ...
    <div class="myclass"> <!-- div #n -->
        <input name="name" class="input" value="abc">
        <!-- other inputs that don't take care -->
    </div>

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献