use brackets in checkbox name when using php and javascript?

折月煮酒 提交于 2019-11-30 14:30:20

PHP has an unusual system for handling multiple form controls with the same name, it expects the names to include [] but it doesn't use them in the variable name.

JavaScript doesn't have that issue. The property will still have the brackets.

Of course, square brackets have special meaning in JS, so you can't use dot notation to access the property.

f['type[]'][i].checked

In javascript, you could use f['type[]'] instead of f.type. It's only php that changes [] to array.

Of course, you can also put a 'key' in between the square brackets, too (ie. give each field an actual unique name). Something like 'type[1]', 'type[2]' and 'type[3]'. PHP still throws it into an array (keyed by those numbers) and JS could access them, too.

You can always use document.getElementsByName() because it takes a string as argument.

Like this:

var f = document.getElementsByName("type[]");
for (var i=0; i < f.length; i++){
    if(f[i].checked == true){
        break;
    }
    if(i == (f.length-1)){
        alert("No categories entered!");
        valid=false;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!