im new to jquery and twitter bootstrap so please forgive the dumb question.
I have an MVC view which setups up a twitter bootstrap modal and this is activated by a link also output within this view.
I want to use data-remote with the modal to load the modal with the contents of an MVC partial view.
I have all of this working nicely.
but what I then wanted to do was be able to access elements (from the partial view) via jquery from the main view, and even though I am sure I have got the selectors right it is not working as expected.
for example I have a href link which I try to assign to the click event, but this does not fire.
however if I move the script so that it is output within the partial view as pulled into the modal-body, then the script does work and the click event is handled.
I would rather not have to have script in the partial view (even if referenced) , I would rather reference one script in the main view.
is there anyway of being able to access the elements that are remotely loaded into the modal-body without having to put the script within the remote partial view?
as an addition, I just mocked up a test where the modal doesn’t use the data-remote and the anchor href was inserted directly within the modal-body, and doing this I am still unable to access this anchor.click event from the main page.
any suggestions much appreciated.
doing more research I have found an answer in the following post
How to set the input value in a modal dialogue?
This seems to suggest the jquery selector should also include .modal-body
so I have changed my selector from the following :
$("#TestButton").click(function (ev) {
ev.preventDefault()
alert('Test Button Clicked');
})
to this
$(".modal-body #TestButton").click(function (ev) {
ev.preventDefault()
alert('Test Button Clicked');
})
and now the click event fires as I had originally expected.
However im now unsure why I need the .modal-body as part of the jquery selector.? Could someone explain this?
You need to wire up the click events to the href’s when the new dynamic content has been loaded into the DOM.
When the page loads, JQuery will look through the DOM for your $(“#TestButton”) and find nothing as at the time when this happens the dynamic content has yet to be injected.
There are a couple of ways of handling this… firstly you can delay the wire up of the click events with JQuery until the new content has been injected, or you can use the .live function of JQuery.
Your code would be:
Actually… it seems Live has been depreciated as of JQuery 1.7
it is…
Hope this helps.