简体   繁体   English

使用jQuery的互斥表单字段

[英]Mutually exclusive form fields using jQuery

I want to have some form fields mutually exclusive.It is a payment form with a lot of different categories. 我希望某些表单字段互斥。这是一种具有很多不同类别的付款表单。 Researching I got the code below 研究我得到下面的代码

$('document').ready( function() {
    $("#zero-out :input").each( function() {
        $(this).keydown( function() {
            $("#zero-out :input").not(this).val("");
        });
    });
});

This code assumes I could just wrap a div with Id zero-out on the fields I want to be exclusive - that is for those grouped fields only one can have a value. 这段代码假设我可以在我要排他的字段上包装一个ID为0的div-也就是说,对于那些分组的字段,只能有一个值。 But I have about 4 different field groups. 但是我有大约4个不同的领域组。 For example one group has textfield and textfield3. 例如,一组具有textfield和textfield3。 Another group has textfield2, textfield4 andtextfield7. 另一个组具有textfield2,textfield4和textfield7。 Another group has textfield5,textfield6 and textfield8. 另一个组具有textfield5,textfield6和textfield8。 These fields are not arranged in order(they are arranged in two columns and arranged in some order of convenience) so it is not easy to just wrap a div around a group. 这些字段不是按顺序排列的(它们按两列排列,并按某种方便顺序排列),因此仅将div包裹在一组周围并不容易。 Each textfield already has an onkeyup="javascript:PaySum() function to add up input values. 每个文本字段都已经具有onkeyup="javascript:PaySum()函数来添加输入值。

I need help to get an elegant way to achieve this goal. 我需要帮助,以一种优雅的方式实现这一目标。

I would give each grouping of mutually exclusive inputs some attribute (data-grouping=1, data-grouping=2, etc for example) and then update the code you have above to something like: 我将为互斥输入的每个分组赋予一些属性(例如,data-grouping = 1,data-grouping = 2等),然后将上面的代码更新为:

$('document').ready( function() {
  $("input").each( function() {
    $(this).keydown( function() {
      $("input").not("[data-grouping='" + this.data("grouping") + "']").val("");
    });
  });
});

Depending on your page size and usage, blur might be a better event than keydown, and you may be able to further restrict inputs to only those within a particular parent. 根据您的页面大小和使用情况, blur可能比击键效果更好,并且您可以进一步将输入限制为仅特定父级中的输入。

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

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