从json中查找元素

时间:2013-06-04 07:31:06

标签: javascript jquery

<h3>Customer</h3>
<dl>
    <dd>
        <input name="customer[customerId]">
    </dd>
    <dt>customer[customerName]</dt>
    <dd>

        <input name="customer[customerName]">
        <span class="error">Find me</span>    
    </dd>
</dl>

<h3>Address</h3>

<dl>    
    <dd>
        <input name="customer[address][addressId]">
    </dd>
    <dd>
        <input name="customer[address][address1]">
    </dd>
    <dd>
        <input name="customer[address][address2]">
    </dd>
    <dt>customer[address][address3]</dt>
    <dd>
        <input name="customer[address][address3]">
        <span class="error">Find me</span>  
    </dd>
</dl>

<h3>District</h3>
<dl>
    <dt>customer[district][districtId]</dt>
    <dd>
        <select name="customer[district][districtId]"><br>
          <option value="">Choose district</option>
          <option value="1">Area 1</option>
        </select>
        <span class="error">Find me</span>  
    </dd>
</dl>

使用Javascript:

// Form error messages
var result = {messages: {
 'customer' : {
     'customerName' : { 'isEmpty' : "Value is required and can't be empty"} ,
     'address' : {
        'address3' : { 'isEmpty' : "Value is required and can't be empty"} 
     },
     'district' : {
        'districtId' : { 'isEmpty' : "Value is required and can't be empty"} 
     },
 }
}};

function parseMessages(messages, parent, result, prefix) {
    result = result || [];
    parent = parent || '';
    prefix = prefix || [];
    $.each(messages, function (name, value) {
        var inputName = '';
        if (prefix.length > 0) {
            inputName += parent;
            $.each(prefix, function(k, v){
                inputName += '['+ v +']';
            }); 
        } else {
           inputName = name;
        }

        var $input = $(':input[name="'+ inputName +'"]').eq(0);
        if ($input.size()) {
            console.log(inputName + ': Found');
        } else {
            console.log(inputName + ': Not found');
        }
        if ($input.size() > 0) {
            // Move up a level
            if (prefix.length > 0) {
                prefix.pop();
            }
            // Error message:
            // { isEmpty : "Value is required and can't be empty"}
            // Messages to string
            var messages = [];
            if (typeof value == 'object') {
                $.each(value, function(k, v) {
                    messages.push(v);
                });
            }
            var errorMessage = messages.join(',');

            // Add to result
            $input.siblings('span').append(' -> <strong style="color:red">Found</strong>');
            result.push({
                element : $input,
                message : errorMessage
            });
        } else {
            if (!parent) {
                parent = name;
            } else { 
               prefix.push(name)
            }
            return parseMessages(value, parent, result, prefix);
        }
    });
    return result;
}
console.log(result.messages);
var result = parseMessages(result.messages);
console.log(result)

见jsfiddle: http://jsfiddle.net/EeYs8/5/

enter image description here

我的脚本有一些问题,无法找到customer[district][districtId]元素, 热解决吗? 非常感谢。

===================更新=========================== ======= enter image description here

2 个答案:

答案 0 :(得分:0)

将此添加到元素

if (name == "district"){
     prefix.length = 0;
     prefix.push(name); 
}

See Demo

答案 1 :(得分:0)

像这样更改你的代码:

// Move up a level
if (prefix.length > 0) {
     prefix.length=0;
}

确实为我解决了这个问题,但是这可能会破坏更深层嵌套的表单。

Fixed example

您可能需要进行一些进一步的测试,也许还需要重构,您的代码看起来非常脆弱。