键入不同的值后,文本框的默认值未更改

时间:2012-11-27 17:52:53

标签: javascript html

我在查询字符串传递的值之后为文本框指定了默认值 previos网页。

它看起来像是:

<form method="post" name="create" onsubmit="return checkPercentValue()" style="font-size: medium; margin-top: 10%" dir="rtl" >
<input type="text" size="5px"  id="stocksPercents" name="stocksPercents" value="@stocks">
</form> 

现在,当用户在文本框中键入另一个值以更改默认值时, 我调用javascript函数来验证某个范围内的值(0 - 100)。

功能:

<script type="text/javascript">
function checkPercentValue() {

    var value = parseInt(document.getElementById("stocksPercents").getAttribute("value"));
    if (value > 100 || value < 0) {
        window.alert("please insert value between 0 - 100");
        return false;
    }
    else {
        return true;
    }

}
</script>    

所以我检查了为什么当我把值放在例如:200(大于100)时,警报不会弹出(!!!) 我在代码中添加了这一行:

document.write(value); 

我看到价值总是保持默认值....并且即使我改变它也不会改变 文本框之前。

所以我猜问题是在文本框中键入值不能更改默认值 就像那样......

解决方案是什么?

感谢...

2 个答案:

答案 0 :(得分:0)

替换此

var value = parseInt(document.getElementById("stocksPercents").getAttribute("value"));

var value = parseInt(document.getElementById("stocksPercents").value);

这将解决您的问题。

答案 1 :(得分:0)

您可能还想考虑使用jQuery。语法更容易,键入更短,并且跨浏览器兼容(也就是说,你不需要担心这个b / c jQuery为你保证。)

以下是jQuery中的代码:

<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script type="text/javascript">
        function checkPercentValue() {
            var value = parseInt($("#stocksPercents").val());
            if (value > 100 || value < 0) {
alert('I am GREATER');
                window.alert("please insert value between 0 - 100");
                return false;
            }
            else {
alert('I am LESS');
                return true;
            }

        }
        $(document).ready(function() {
            $('#stocksPercents').blur(function() {
                checkPercentValue();
//              alert('Yo!');
            });
        });
        </script>    
</head>
<body>

<form method="post" name="create" onsubmit="return checkPercentValue()" dir="rtl" >
    <input type="text" size="5px"  id="stocksPercents" name="stocksPercents" value="@stocks">
</form> 


</body></html>
相关问题