ab1428x
ab1428x

Reputation: 804

MVC click on link upon page load with jQuery

I'm trying to make a link click whenever the page reloads with jQuery, however this code is not working:

@model IEnumerable<SPMVCApp.Models.Picture>
@{
    ViewBag.Title = "Index";
 }
<h2>@ViewBag.Mb Mb</h2>
<p>
    @Html.ActionLink("Create New", "Create", null, new { id = "btn" })
</p>
<table>
    <tr>
        <th></th>
    </tr>
</table>

<script type ="text/javascript">
    $(document).ready(function(){
      jQuery('#btn').click()
    })
</script>

I tried using $ instead of jQuery when firing the click but still no luck, I haven't got much experience with jQuery/JavaScript

Upvotes: 0

Views: 905

Answers (4)

ab1428x
ab1428x

Reputation: 804

Ok I fixed it.

I just need to add [0] after the parameter as so:

$('#btn')[0].click()

or

jQuery('#btn')[0].click()

Upvotes: 0

Loda
Loda

Reputation: 31

you can debug it in console at chrome or firefox .

check whether jQuery('#btn') is [] or the elemnt you want.

Upvotes: 0

vaibhav shah
vaibhav shah

Reputation: 5069

By seeing your code I understood that you want to call Create Action of your controller. So instead of calling click event of your button you call call that action directly from your javascript using ajax.

Se bellow e.g.

$.get("Home/Create", function (result) {
  // do wahtever you want to do with result
});

Upvotes: 0

Saeed
Saeed

Reputation: 3795

You can use this code:

$(function(){
    $("#btn").click(function(){
        document.location.href = "YourUrlFor Refresh"
    })
})

also do not remember that include your page to Jquery Script like 1.8.1

Upvotes: 1

Related Questions