Mohammed Faruk
Mohammed Faruk

Reputation: 495

Execute JavaScript with MVC3 RAZOR View Engine?

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?

Upvotes: 1

Views: 1931

Answers (3)

Terry
Terry

Reputation: 14219

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");
});

Upvotes: 1

Kapil Khandelwal
Kapil Khandelwal

Reputation: 16144

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>

Upvotes: 3

AnthonyWJones
AnthonyWJones

Reputation: 189555

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.

Upvotes: 2

Related Questions