1

I am loading a partial view into a main view using ajax but struggling to get the jquery to fire within the partial view.

Basically I am trying to allow a partial view to load that contains a button that allows me to open up a dialog window.

My partial view contains this small piece of js

    <script type="text/javascript">
    $(document).ready(function () {
        alert('ready');
        $('#edit-note').click(function () {
            //$('#dialog').dialog('open');
            alert("alert displayed from jquery");
        });
    }); 

</script>

However it is never fired.

What do I need to do to enable jquery to work from a dynamically loaded partial view?

1
  • Where is the piece of code that you've shown us located? Is it in the main view, or in the partial view? Commented Aug 28, 2011 at 20:05

2 Answers 2

4

Your code that starts with $('#edit-note').click(function () {, is run when the document is ready. At that point in time, you have not yet loaded your partial view, so $('#edit-note') is an empty collection.

jQuery allows you to bind events to elements that are not yet on the page, via its live method:

$('#edit-note').live('click', function () {
    alert("alert displayed from jquery");
});
Sign up to request clarification or add additional context in comments.

3 Comments

Hi Joseph, I had the above code in the partial view that was loaded dynamically not the actual page. Ideally I dont want the above code in the actual page I would prefer to keep it in the loaded partial view. <br/>I tried your suggestion however it doesnt get triggered.
@Diver Dan: Did you wrap it in $(document).ready? You shouldn't. Since you're using live, there's no need for $(document).ready.
Your right. I moved everything out of the actual page into a global js file and all is good. Thank you
0

Another thing you can do is use an @Ajax.ActionLink and in the AjaxOptions use the OnSuccess event to call a JavaScript function that executes the JQuery you are trying to execute. ie.

@Ajax.ActionLink("Create New", "Create", "Employee", new AjaxOptions()
{
UpdateTargetId = "divAction",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET",
OnSuccess = "createNew_Success"
}, new { id = "btnAdd", @class = "newButton", OnClick = "$('#divAction').slideDown();" })

Then in your Javascript:

<script type="text/javascript">
function createNew_Success() {
$('.button').button();
}
</script>

What this does is loads a PartialView into a div and after it loads successfully, it applies JQuery styling to objects with the class of button

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.