Reputation: 322
I have the following javascript test.js file:
$("#addItem").click(function () {
alert("yup");
$.ajax({
url: this.href,
cache: false,
success: function (html) { $("#bandRows").append(html); }
});
return false;
});
That I want to use to inject some HTML into the "bandRows" div on a page. I'm using Razor in an MVC 3 app like so:
The Index View, which contains the link that, when clicked injects a partial view HTML:
@model IEnumerable<TariffBand>
<script type="text/javascript" src="[email protected]("~/Scripts/jquery-1.3.2.js")"></script>
<script type="text/javascript" src="[email protected]("~/Scripts/MicrosoftAjax.js")"></script>
<script type="text/javascript" src="[email protected]("~/Scripts/test.js")"></script>
<h2>Index</h2>
@using (Html.BeginForm())
{
<div id="bandRows">
@foreach (var band in Model)
{
Html.RenderPartial("BandEditorRow", band);
}
</div>
@Html.ActionLink("Add band...", "Add", null, new { id = "addItem" })
<input type="submit" value = "Done" />
At the moment, when I click on the link the javascript is not being called - the alert box is not being displayed - and the link just navigates to the "Add" partial view rather than injecting it into the 'bandRows' div.
Can anyone tell me why? I haven't used javascript before so I've obviously done something daft but can't work it out for the life of me.
EDIT - I have amended the .js file so the handler is for click not onclick. I have also tried amending the html helper to:
@Html.ActionLink("add band...", "Add", null, new { onclick = "addItem" }
but still no dice.
Thanks David
Upvotes: 0
Views: 1828
Reputation: 3870
You have
$("#addItem").onclick(function ()
There is nothing like $.onclick
.
This will be
$("#addItem").click(function ()
$().ajax({
should be $.ajax({
and the whole code should be within document.ready()
like
$(document).ready(function(){
$("#addItem").click(function (){
.
.
.
});
As you have admitted that you are very new to javascript world, I am giving the detail code:
<script type="text/javascript" src="[email protected]("~/Scripts/MicrosoftAjax.js")"></script>
@* <script type="text/javascript" src="[email protected]("~/Scripts/test.js")"></script> *@
<h2>Index</h2>
<script type="text/javascript">
$(document).ready(function(){
$("#addItem").click(function (){
alert("yup");
$.ajax({
url: this.href,
cache: false,
success: function (html) {
$("#bandRows").append(html);
}
});
return false;
};
});
</script>
document ready
is a very preliminary thing you need to learn when starting jQuery
. This is the API documentation of ready
event. And here is a tutorial for understanding document ready
.
Upvotes: 2