在JavaScript中使用focus()

时间:2013-10-25 06:14:45

标签: javascript jquery asp.net-mvc

我正在尝试使用JavaScript将焦点放在文本框上。但它不起作用,请告诉使用focus()并为该文本框设置空值。

脚本:

<script type="text/javascript">
$(document).ready(function () 
{
   var str = ('@ViewData["ControlView"]'); //alert(str);
   if (str == "1")
       ShowProduct();
   else
       ShowGrid();
});
var message = ('@ViewData["Success"]');
if (message == "Product Code Already Exits.")
{
   document.getElementById("Item_Code").value ="";
   document.getElementById("Item_Code").focus();
}

查看:

@Html.TextBox("Item_Code", "", new { @Maxlength = "10", id = "Item_Code" });

4 个答案:

答案 0 :(得分:1)

Javascript中的focus()代码是:

var message="message";
if(message=="")
{
    document.getElementById("Item_Code").focus();
    document.getElementById("Item_Code").value=="";
}

答案 1 :(得分:0)

尝试使用jQuery,它更简单,更干净

<script type="text/javascript">
$(document).ready(function () {
    $(function () {
        $('#Item_Code').focus();
    });
});
</script>

答案 2 :(得分:0)

在此脚本块中

<script type="text/javascript">
    $(document).ready(function () 
    {
        var str = ('@ViewData["ControlView"]'); //alert(str);
        if (str == "1")
            ShowProduct();
        else
            ShowGrid();
    });

    var message = ('@ViewData["Success"]');
    if (message == "Product Code Already Exits.")
    {
        document.getElementById("Item_Code").value ="";
        document.getElementById("Item_Code").focus();
    }

声明并使用消息变量和document.getElementById函数调用不在ready函数中,所以如果在此之后声明你的文本框然后在调用document.getElementById("Item_Code")中返回null,因为具有此id的元素具有尚未呈现

for solve put code

    var message = ('@ViewData["Success"]');
    if (message == "Product Code Already Exits.")
    {
        document.getElementById("Item_Code").value ="";
        document.getElementById("Item_Code").focus();
    }
ready函数中的

        $(document).ready(function () 
        {
            var str = ('@ViewData["ControlView"]'); //alert(str);
            if (str == "1")
                ShowProduct();
            else
                ShowGrid();

            var message = ('@ViewData["Success"]');
            if (message == "Product Code Already Exits.")
            {
                document.getElementById("Item_Code").value ="";
                document.getElementById("Item_Code").focus();
            }
        });

答案 3 :(得分:0)

Jquery解决方案

<script type="text/javascript">
$(document).ready(function () 
{
   var str = ('@ViewData["ControlView"]'); //alert(str);
   if (str == "1")
       ShowProduct();
   else
       ShowGrid();
});
var message = ('@ViewData["Success"]');
if (message == "Product Code Already Exits.")
{
  $("#Item_Code").val("");
  $("#Item_Code").focus();
}