简体   繁体   English

Javascript:在数组/对象中查找值以确定表单显示

[英]Javascript: Finding values in array/object to determine Form display

Let me set up the situation: 让我来设置情况:

I have a form. 我有一个表格。 This form has several fields which are dependent upon a single drop-down, lets call it Art Kind . 此表单具有多个字段,这些字段取决于单个下拉菜单,我们称其为Art Kind Based on the value of this Art Kind, several other fields are to be hidden/shown. 根据此Art Kind的值,其他几个字段将被隐藏/显示。 Multiple values within this Art Kind dropdown can trigger the same set of fields being shown. 此Art Kind下拉菜单中的多个值可以触发所显示的同一组字段。 For example. 例如。

User selects "Awesome", or "Cool", from the Art Kind dropdown:
     - URL and Name fields are shown
 User selects "Rainbow", or "Double Rainbow", from the Art Kind dropdown: - URL and Name fields are hidden - Color and Size fields are shown 

I think you get the idea. 我想你应该已经明白了。

I'm trying to come up with a better solution than something like this: 我正在尝试提供一个比这样更好的解决方案:

if (selected == "Awesome" || selected == "Cool")
{
    url.show();
    name.show();
}

Because there are a ton of fields, and a ton of different options that need be shown/hidden depending on selection. 因为存在大量字段,并且根据选择需要显示/隐藏大量不同的选项。 I've dabbled in an array, but I'm lost on how to get what I need accomplished. 我已经涉足数组,但是我迷失在如何完成我需要的东西上。

I was thinking about storing the options in a multidimensional array, or an object, something like: 我正在考虑将选项存储在多维数组或对象中,例如:

var values = [
     ['Awesome', 'Cool'], ['url', 'name']
]

But I'm not sure how to implement such a thing. 但是我不确定如何实现这样的事情。

Any ideas? 有任何想法吗? I'm open to answers that involve jQuery for simplification, but I'd rather keep other libraries out of it. 我愿意回答涉及jQuery的简化问题,但我宁愿不要使用其他库。

It'd be better to use an object, with the <select> values being the keys. 最好使用以<select>值为键的对象。 Now as to the values, it's hard to say without knowing more details. 现在,关于价值,很难不知道更多细节就说。

If there are only a few different overall page setups — that is, combinations of things shown and things hidden — then it might be easiest to encapsulate those in a few functions, and have the map go from selected value to function: 如果只有几个不同的整体页面设置(即显示的事物和隐藏的事物的组合),那么将那些封装在几个函数中并使映射从选定的值转换为函数可能是最简单的:

function rainbowMode() {
  // show color and size, hide url and name ...
}

function awesomeMode() {
  // show url and name, hide color and size ...
}

var actionMap = {
  'Rainbow': rainbowMode,
  'DoubleRainbow': rainbowMode,
  'Awesome': awesomeMode,
  // ...
};

An entirely different approach would be to tie the selection to the addition/removal of one or more CSS classes to the form container, coupled with CSS rules to hide/show portions of the form. 一种完全不同的方法是将选择与在表单容器中添加/删除一个或多个CSS类相关联,再加上CSS规则来隐藏/显示表单的某些部分。 The only catch with this is that you can't make form fields be disabled via CSS alone, so if you need the form posts to not include inappropriate fields that won't really help. 唯一的问题是您不能仅通过CSS来禁用表单字段,因此,如果您需要表单帖子中不包含不起作用的不适当字段。

I've been thinking of writing a jQuery plugin to service this very need :-) If I do I'll update the answer in a couple of months. 我一直在考虑编写一个jQuery插件来满足这一需求:-)如果可以,我会在几个月后更新答案。 (I've already got the code; I just need to yank it out of its current context.) (我已经有了代码;只需要从当前上下文中删除它即可。)

A similar idea to @Pointy's, somewhat different execution. 与@Pointy类似的想法,执行方式有所不同。

function hideAllFormElements()
{
    // snip...
}

function showElements(ids)
{
    for (var i=0; i<ids.length; i++)
    {
        document.getElementById(ids[i]).style.display = 'none';
    }
}

var mapping = {
    Awesome: ['url', 'name'],
    Cool: ['url', 'name'],
    Rainbow: ['color', 'size'],
    'Double Rainbow': ['color', 'size']
};

// later...
hideAllFormElements();
showElements(mapping[selected]);

Edit 编辑

Because jQuery is the bee's knees, instead of separate hide/show functions this will suffice, given just var mapping = {...} as above: 因为jQuery是蜜蜂的膝盖,所以不需要单独的hide / show函数,就可以了,因为上面的var mapping = {...}

$('#mySelect').change(function ()
{
    var selected = $(this).val();

    $('#myForm :input').hide();
    $.each(mapping[selected], function ()
    {
        $('#' + this).show();
    });

    // or if you want to get really fancy,
    $($.map(mapping[selected], function ()
    {
        return '#' + this;
    }).get().join(', ')).show();
});

I've done exactly this by using the 'rel' tag, which is mostly unused in HTML. 我通过使用'rel'标记(完全在HTML中未使用)完成了此操作。 Note that my example uses jQuery, but can be easily adapted to any other JS framework, or straight Javascript. 请注意,我的示例使用jQuery,但可以轻松地适应任何其他JS框架或纯Javascript。

<select id="artkind">
    <option value="cool">Cool</option>
    <option value="awesome">Awesome</option>
    <option value="rainbow">Rainbow</option>
    <option value="2xrainbow">Double Rainbow</option>
</select>

<input name="url" rel="cool awesome">
<input name="name" rel="cool awesome">
<input name="color" rel="rainbow 2xrainbow">
<input name="size" rel="rainbow 2xrainbow">

<script>
    $('#artkind').change(function() {
        $('input').hide(); // To hide everything
        $('[rel*="'+this.value+'"]').show(); // To show only desired fields
    })
</script>

Note, I haven't actually tested this exact code, so I can't guarantee it works as-is. 请注意,我尚未实际测试此确切的代码,因此无法保证它能按原样工作。 But I have used this exact method before for the exact thing you're talking about. 但是,我以前用过的,你谈论的是确切的事情这个确切的方法。

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

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