开发者

Javascript match with wildcard

Hi and thanks for looking.

I need to get all form inputs from a form using javascript, the inputs are named like so:

<input name="site[1]" type="text" size="3" id="sitesinput" value="0" />
<input name="site[2]" type="text" size="3" id="sitesinput" value="0" />
<input name="site[3]" type="text" size="3" id="sitesinput" value="0" />
<input name="site[4]" type="text" size="3" id="sitesinput" value="0" />

......

<input name="site[10]" type="text" size="3" id="sitesinput" value="0" />

and I have the following to pick them up and adding the values togther, but it is not working, what am I doing wrong:

function site_change() {
         var sites= document.getElementById('sitesinput').value;    
         var sum= 0;
         var inputs= document.getElementById('inputsite').getElementsByTagName('input');
         for (var i= inputs.length; i-->0;) {
          开发者_JAVA技巧  if (inputs[i].getAttribute('name').match(/^site[\d+$]/))
            {
             var v= inputs[i].value.split(',').join('.').split(' ').join('');
             if (isNaN(+v))
                 alert(inputs[i].value+' is not a readable number');
             else
                 sum+= +v;
            }
         }
         var phones= document.getElementById('phonesinput').value;
         document.getElementById('siteresult').innerHTML = phones-sum;
    };

Is the Match function wrong?

Thanks, B.


Your regex is a little off (using [] blocks characters, but you actually want to find square brackets so they need to be escaped. And $ needs to be at the end). Try:

.match(/^site\[\d+\]$/)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜