开发者

please help in fixing this issue with simple javascript

while( $data is comming from db)
{
  <{form} name=formName.$uniqueValue action= onsubmit=return validate(this){>}

    <input type=text name=sort_order[] value= value_from_db />
    <input type='submit' />
  <{/form}>

}

Below is the Javascript validate function

{<}script language="javascript1.2"{>}
{function} validate(obj)
{

    var x = obj.elements['sort_order'].length;




    var check = false;

    for(var i =0; i <x; i++)
    {
        var array = Array();
        array = obj.elements['sort_order'];
        var num=  array[i];

        if(!isInteger(num.value))
        {
            check = true;
        }


    }

    if(check)
    {
        alert('Please enter a valid sort number');
        return false;
    }

    return true;


}

function isInteger(val)
{

    if(val==null)
    {

        return false;
    }
    if (val.length==0)
    {

        return false;
    }
    for (var i = 0; i < val.length; i++) 
    {
        var ch = val.charAt(i)
        if (i == 0 && ch == "-")
        {
            return false;
        }
        if (ch < "0" || ch > "9")
        开发者_开发问答{
            return false;
        }
    }
    return true;
}
</script>

The problem is when i have values form with sort_order[] text field having more then 1 value the validation works fine but it fails when i have only one value in the sort_order[] please help


The problem was when input field name is given an array i.e. if the sort_order[] contains only one element then in the javascript it is not considered as an Array object . So that is why the value i was receiving was null i have put an check there if the value is null then consider it as an single element and then it worked fine. –


keep the check value by default true and make it false if one validation also fails like this

var check = false;

for(var i =0; i <x; i++)
{
    var array = Array();
    array = obj.elements['sort_order'];
    var num=  array[i];

    if(!isInteger(num.value))
    {
        check = true;
    }


}

And for check Integer Value you can use parseInt(val)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜