开发者

processing a Mutlidimensional HTML array in Javascript

I've got the fo开发者_StackOverflow社区llowing HTML which has been looped around in smarty template language:

<td><input type="checkbox" name="confirmRelated[{$relatedIP.ipInt}_{$relatedIP.patternID}][confirm]" /></td>
<td><input type="hidden" name="confirmRelated[{$relatedIP.ipInt}_{$relatedIP.patternID}][ipInt]" value="{$relatedIP.ipInt}">{$relatedIP.robotIP}</td>
<td><input type="hidden" name="confirmRelated[{$relatedIP.ipInt}_{$relatedIP.patternID}][patternID]" value="{$relatedIP.patternID}">{$relatedIP.pattern}</td>

I'm trying to access the fields in javascript, but I'm having troubles with even the basics so far. Can anyone help?

var boxes = document.getElementsByName('confirmRelated');
alert(boxes.length);

That returns 0 at the moment, which is obviously wrong. I'm attempting to loop through all of them and check the checkbox "confirm" ones.

Any help appreciated.


You can't access them via document.getElementByName(). The following should work:

var boxes = document.getElementsByTagName('input');
for(i = 0; i < boxes.length; i++){
    if(boxes[i].name == 'confirmRelated' && boxes[i].type == 'checkbox'){
        boxes[i].checked = 'checked';
    }
}

That would check all inputs with the type checkbox.

EDIT: Using a framework like prototype you can make it a lot easier:

$$('input[name=^"confirmRelated"]').each(function(elm){
    if(elm.type == 'checkbox') elm.checked = 'checked';
});


That returns 0 at the moment, which is obviously wrong.

no, its's not. there is no element with 'confirmRelated' as name.

to loop through your 'array' (javascript doesn't notice this as array) you should loop trough all input fields (getElementsByTagName('input')...) and check if the name of your currrent element starts with 'confirmRelated' (and if it does, do whatever you want to do).


You can use JQuery selector-

$("input[name^='confirmRelated']")

since all the input name are started with 'confirmRelated' and the template engine add some postfix to it

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜