1

I have an Index.cshtml Page in MVC3 Razor View Engine with Following Code:

@{
    ViewBag.Title = "Home Page";
}

<h2>@ViewBag.Message</h2>

<label id="lblClickMe" style="cursor:pointer"> Test Java Script Work in MVC Razor</label> || <label id="lblReset" style="cursor:pointer"> Rest    </label>

<br /><br /><br /><br />
<input type="text" id="txtResult"  style="width:300px"/>

And i have some JavaScript in Sane page Like :

<script type="text/javascript">
    $("#lblClickMe").click(function () {

        var txtResukt = document.getElementById("txtResult");
        txtResukt.value = "Java script work successfully";

    })

    $("#lblReset").click(function () {

        var txtResukt = document.getElementById("txtResult");
        txtResukt.value = "";

    })
</script>

When I try to load my view give following exception from "lblClickMe" Click Event :

Microsoft JScript runtime error: Object expected

Any one fix this bug?

0

3 Answers 3

3

Try this:

  <script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
    <script type="text/javascript">
        $("#lblClickMe").click(function () {
         $("#txtResult").val("Java script work successfully");
        });
        $("#lblReset").click(function () {
          $("#txtResult").val("");
        });
    </script>
Sign up to request clarification or add additional context in comments.

Comments

2

Try this:

$(document).ready(function()
{
    $("#lblClickMe").click(function () { 

        var txtResukt = document.getElementById("txtResult"); 
        txtResukt.value = "Java script work successfully"; 

    }) 

    $("#lblReset").click(function () { 

        var txtResukt = document.getElementById("txtResult"); 
        txtResukt.value = ""; 

    }) 

});   

This ensures the HTML in the page is loaded first before code attempts to wire up the click events.

2 Comments

AnthonyWJones : i try you suggestion but full ready function give same exception.
@Mohammed: have you tried the browsers view source function ? Does the html look right? Have checked error console in the browser for parse errors of JavaScript? Are any referenced js files being delivered correctly?
1

Why not do this?

$("#lblClickMe").click(function () {
    document.getElementById("txtResult").value = "Java script work successfully";
});

or in pure jQuery:

$("#lblClickMe").click(function () {
    $("#txtResult").val("Java script work successfully");
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.