开发者

How to compare field values with the same data attribute in javascript

How do I compare the values in the text fields with the same data attribute in javascript?

<input type="text" name="a" id="a" data-common="candy" class="loop" value="2">
<input type="text" name="b" id="b" data-common="candy" class="loop" value="3">
<inp开发者_运维知识库ut type="text" name="c" id="c" data-common="ice" class="loop" value="7">
<input type="text" name="d" id="d" data-common="ice" class="loop" value="2">
<input type="text" name="e" id="e" data-common="water" class="loop" value="5">
<input type="text" name="f" id="f" data-common="water" class="loop" value="9">

What I want to do is to determine the higher value on each of the fields with common data attribute. If the common attribute is candy, then the program will compare the values 2 and 3. My problem is I can't think up of a good algorithm to even start coding. Can you give me an idea? What do I need to do first.


Here you go. The below code will find all the unique data-common attributes with max value.

Working demo

var dataAttributes = {}, attrValue, inputValue, $this;
$('input[data-common]').each(function() {
    $this = $(this);
    attrValue = $this.attr("data-common");
    inputValue = parseInt($this.val());
    if(!dataAttributes[attrValue]){
        dataAttributes[attrValue] = inputValue;
    }
    else{
        if(dataAttributes[attrValue] < inputValue){
            dataAttributes[attrValue] = inputValue;
        }   
    }
});
console.log(dataAttributes);


var datum = "candy";
var maxd = Number.NEGATIVE_INFINITY;;
$('input[data-common="'+datum+'"]').each(function() {
  maxd = Math.max(maxd,$(this).val());
});

http://jsfiddle.net/KaUEX/


Well they already answered it, but I did the work so I'm going to post it

var common_values = {},
    result = $('#result');

$('[data-common]').each(function(){
    var element = $(this),
        common_key = element.attr('data-common'),
        value = parseInt(element.val(), 10);
    if(typeof(common_values[common_key]) === 'undefined'){
        common_values[common_key] = [];
    }
    common_values[common_key].push(value);
});

for(var data in common_values){//or you could find the min, or average or whatever
    result.append(data + ': ' + Math.max.apply(Math, common_values[data]) + '<br>');
}

http://jsfiddle.net/dtanders/QKhu7/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜