开发者

check all values match using prototype

Using prototype, is there a simple method of checking that a group of v开发者_C百科alues match, for example - can this code be refined to a single line or something otherwise more elegant?

var val = null;
var fail = false;

$('form').select('.class').each(function(e){
    if(!val){
        val = $F(e);
    }else{
        if(val != $F(e)) fail = true;
    }
});


Oh, this oneliner should do it:

$(form).select('.'+className).invoke('getValue').uniq().size()===1; // true means all values are the same

  • Make an array out of the values of the (input/etc) elements with the class name you are after (run invoke on a set of selected elements)
  • Make the array contain unique values only (call uniq on the array)
  • See if its length is 1

Links to Prototype docs: Element.select, Enumerable#invoke, Form.Element.getValue, Array#uniq

Example:

<body>

<form action="#" id="myform">
    <input type="text" name="foo1" class="foo" />
    <input type="text" name="foo2" class="foo" />
    <input type="text" name="foo3" class="foo" />
    <input type="text" name="foo4" class="foo" />
    <input type="text" name="foo5" class="foo" />
    <input type="submit" />
</form>

<script type="text/javascript">
// Returns true if all values of elements with a certain classname in the form has the same value
function bar(form, className) {
    return $(form).select('.'+className).invoke('getValue').uniq().size()===1;
}
// Usage: bar('myform', 'foo');
</script>
</body>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜