How do I get click event of model form button? - javascript

On my django web app, I have a webpage and when a button is clicked a modal form is opened. On this form there are a few fields and a save button. When the save button is pressed, I want to do something, like printing an alert. Here is what I tried:
Model form code:
<div class="container-content">
<div class="infor-experience col-lg-2 more_info">
{% if request.user|isEmployer %}
<div class="add-to-list">{% include "layout/addtolistmodal.html" %}</div>
<div class="connect-now bottom">{% include "layout/bidmodal.html" %}</div>
{% endif %}
<!-- more code below here -->
Javascript block in same HTML file as modal above:
<script type="text/javascript">
// Add to short list handler
$('.add-to-list').on('click', '.submit', function(e) {
alert("TEST");
})
</script>
Basically, what I want to do is when the user clicks save on the add-to-list modal, print the alert "TEST".
From my understanding the reason its not working is because it cannot find '.add-to-list' but what I should use instead?

Just attach your click event to already present element which seems to be div.infor-experience, since your modal html gets appended after DOM load. Also, make sure your script renders in web browser if you have provided any conditions for them to render.
$('.infor-experience').on('click', '.submit', function(e) {
alert("TEST");
})

It might be that positioning of your script. At the time of its execution the DOM may not be ready or exist yet.
You could wrap your DOM related codes like so:
$(document).ready(init);
function init(){
$('.add-to-list').on('click', '.submit', function(e) {
alert("TEST");
})
}

Try this instead
$(document).ready(function () {
$('.add-to-list').on('click', '.submit', function(e) {
alert("TEST");
});
});
you should add the code under $(document).ready() so that it waits for whole DOM to load and then attaches the method instead doing so before loading of DOM.

Related

auto click button when javascript function is called NOT on page load or button click

I want to auto click a button when a javascript function is called. With the button clicked, a flask route is called. All I have been able to find is for when the page loads. Here is some code
<script>
function justClickin(){
$("#autoclick").get(0).click();
// $("#autoclick").trigger('click'); // This doesnt work either
}
</script>
{% if True %}
<script>
justClickin();
</script>
{% endif %}
<a id="autoclick" href="{{ url_for('login') }}">login </a>
So when the condition is true, the justClickin JS function is run. This should auto click the anchor tag and run the flask route. Problem is that the anchor tag is not clicked.
Thanks
Edit ------------------------------------------
So in the end, I did this
{% if True %}
<script>
$("document").ready(function(){
$("#autoclick").get(0).click();
});
</script>
{% endif %}
<a id='autoclick' style="display:none;" href="{{ url_for('login') }}">login </a>
Since your logic is being ran as soon as it is reached by the parser, the elements that you are trying to manipulate must already exist for you to use them. So if the element appears on the page after the function call, it will not exist in the DOM yet for you to find and click it logically. Your script will need to be after the element in the DOM. Otherwise, you could put your logic in a document ready and then it would not execute until the entire page is parsed into the DOM.

How do I make permanent changes to javascript variables or html elements inside of .click()?

For example:
$(document).ready(function(){
$('#submit').click(function(){
$('#rightAd').text("HELLO EVERYBODY");
});
});
This only changes the text in #rightAd for the moment the button is clicked. How do I make it remain, "HELLO EVERYBODY" after the click ends? Or am I thinking about this the wrong way?
changing via script will reflect until the page gets refreshed.
Try this:
HTML:
<div id="rightAd"> some text.....</div>
<button id="submit">Submit</button>
JQuery:
$('#submit').click(function(){
$('#rightAd').text("HELLO EVERYBODY");
});
If you are using <input type="submit"/> this will submit your page, so changes will be flashed as page gets refresh.
Use event.preventDefault() to prevent form from submission

How to show a hidden div with javascript when submitting a form?

I'm not really familiar with jquery, but am trying to get a simple animated gif to show when a form is submitted. When clicking 'submit' to upload an image I want to show gif so that users know that image is being uploaded. The submit button has an id="submit" and also an onClick="return confirm('message')"
I have the div code containing the gif:
<div id="loading" style="display:none">
<img src="images/hand_timer2.gif" alt="loading" />
</div>
which is hidden. And it does show if I remove the style. Fair enough. But when I try to show it with the following javascript it doesn't show:
<script type="text/javascript">
$(function(){
$('#submit').click(function(){
$('#loading').show();
});
});
I have
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"
type="text/javascript"></script>
in a separate PHP header file. As far as I can see it's the only reference to jquery library, but I do have other javascript codes that all work. I just can't get this one to work. Can anyone point out what I'm doing wrong and why I can't get the div to show gif when clicking submit?
I believe the problem could be that your inline onClick="return confirm('message')" prevent the click-event from reaching your click-event listener attached with jQuery - not sure though. Anyhow, instead of listening for a click-event on the submit-button, I would listen for the submit event on the form, that will fire when the form is actually submitted (a form can usually be posted by other means than clicking the submit button as well - through the Enter key for instance).
$('#idOfYourForm').on("submit", function () {
$('#loading').show();
});
Side note:
You don't close the style attribute properly on your loading div (notice that the > is blue):
<div id="loading" style="display:none>

YUI3 button click event is acting like a submit type instead of a button type

I am using ASP.NET MVC 3 with the Yahoo API version 3. I am trying to get my YUI3 button to redirect to another page when I click on it, this button is my cancel button. The cancel button is a plain button type, but it is being treated like a submit button. It is not redirecting to the correct page, but acting like a submit button and it kicks off my page validation like what the submit button would do.
I thought that it might be with my HTML but I did validate it. It validated 100% correct. So I then stripped down the whole page to a bare minimum but the cancel button is still working like a submit button. Here is my HTML markup:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Create2</title>
</head>
<body class="yui3-skin-sam">
<h1>Test submit</h1>
#using (Html.BeginForm())
{
<button id="SaveButton" type="submit">Save</button>
<button id="CancelButton" type="button">Cancel</button>
}
<script src="http://yui.yahooapis.com/3.6.0pr4/build/yui/yui-min.js"></script>
<script>
YUI().use('button', function (Y) {
var saveButton = new Y.Button({
srcNode: '#SaveButton'
}).render();
var cancelButton = new Y.Button({
srcNode: '#CancelButton',
on: {
'click': function (e) {
Y.config.win.location = '/Administration/Department/List';
}
}
}).render();
});
</script>
</body>
</html>
I'm not sure what I am doing wrong here? Is this maybe a bug in their API? I am testing on IE8 and on the latest version of FireFox.
UPDATE:
I forgot to mention that if these buttons are not between form tags then the redirect works fine. If I put them in form tags then the redirect does not work.
I would use a link because you are redirecting to another page. Doing it this way you wouldn't need to initialize it with javascript or register the onClick listener.
<button id="SaveButton" type="submit">Save</button>
<a id="CancelButton" href='/Administration/Department/List'>Cancel</a>
Look at this link to style your link: http://yuilibrary.com/yui/docs/button/cssbutton.html
The Y.Button widget is removing the type attribute from the Cancel button. This makes that button behave like a submit button.
There are many possible paths to make this work. I'll start from simple to complex. The first is to avoid the issue entirely and not use JavaScript at all. Just use a link:
<form action="/Administration/Department/Create2" method="post">
<button class="yui3-button">Save</button>
<a class="yui3-button" href="/Administration/Department/List">Cancel</a>
</form>
After all, all that the Button widget is doing is adding a couple of css classes to each tag and a lot of other stuff that makes more complex widgets possible. As you can see in the Styling elements with cssbutton example, even <a> tags can look like nice buttons using just the YUI css styles. If you don't have to use JavaScript, better not to use it.
A second option is to avoid the Y.Button widget and use the Y.Plugin.Button plugin. It's more lightweight in both kb and processing power. And it doesn't touch the tag attributes, so your location code will work.
YUI().use('button-plugin', function (Y) {
Y.all('button').plug(Y.Plugin.Button);
Y.one('#CancelButton').on('click', function () {
Y.config.win.location = '/Administration/Department/List';
});
});
And finally you can hack around the behavior of the Y.Button widget by preventing the default action of the button:
var cancelButton = new Y.Button({
srcNode: '#CancelButton',
on: {
'click': function (e) {
e.preventDefault();
Y.config.win.location = '/Administration/Department/List';
}
}
}).render();

No pagechange event firing

In jQuery mobile, I am trying to detect a successful page change to a specific page. I have the following code, inline on the page I want to load.
<script>
$(document).bind( "pagebeforechange", function( e, data ) {
alert("pagebeforechange");
});
$(document).bind( "pagechange", function( e, data ) {
alert("pagechange");
});
$(document).bind( "pagechangefailed", function( e, data ) {
alert("pagechangefailed");
});
$(document).live( "pagebeforechange", function( e, data ) {
alert("pagebeforechange live");
});
$(document).live( "pagechange", function( e, data ) {
alert("pagechange live");
});
$(document).live( "pagechangefailed", function( e, data ) {
alert("pagechangefailed live");
});
</script>
I get the the appropriate alerts when loading the page directly, or refreshing, but not when navigating from another area in the Jquery Mobile app.
Page is called by the the "Your Car" Tab in the footer
<div id="footer" data-role="footer" data-position="fixed">
<div data-role="navbar">
<ul>
<li>Home</li>
<li>Features</li>
<li>Your Car</li>
<li>Contact</li>
</ul>
</div>
</div>
Would it work to place your code in the pageshow event? It may if you are trying to detect the page or location. Something like this maybe:
<script type="text/javascript">
$('[data-role=page]').live('pageshow', function (event, ui) {
hash = location.hash;
page = hash.susbtr(1);
if (page.indexOf('about.html') >= 0) {
alert('you made it!');
}
});
</script>
UPDATE
After testing this scenario a bit more and rereading your question, I think I was able to reproduce the results.
This works as you described and only fires alerts when loading the page directly or refreshing the page:
<body>
<div data-role="page">
<!-- page stuff -->
</div>
<script type="text/javascript"> ..bind events... </script>
</body>
However, when I move the javascript directly inside the page, it works as expected and fires all of the bound events, no matter how the page was reached:
<body>
<div data-role="page">
<script type="text/javascript"> ..bind events... </script>
<!-- page stuff -->
</div>
</body>
Where are you binding to this events?
Have you read following in the Docs http://code.jquery.com/mobile/latest/demos/docs/api/events.html:
Important: Use pageInit(), not $(document).ready()
The first thing you learn in jQuery is to call code inside the
$(document).ready() function so everything will execute as soon as the
DOM is loaded. However, in jQuery Mobile, Ajax is used to load the
contents of each page into the DOM as you navigate, and the DOM ready
handler only executes for the first page. To execute code whenever a
new page is loaded and created, you can bind to the pageinit event.
This event is explained in detail at the bottom of this page.
Luke's thinking is in the right direction: clearly the problem you had has to do with where in the code the binding is occurring. This is proved by shanabus.
However, in your case, you should be doing the binding when jQuery mobile's mobileinit event is fired, not pageInit, as Luke is suggesting.
Example (fires on all page change events):
<script type="text/javascript">
$(document).bind('mobileinit', function() {
$(document).on('pagechange', function () {
window.alert('page changed!');
});
});
</script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.js"></script>
As illustrated in the code above, be mindful that handlers triggered by mobileinit must be included before the jQuery mobile <script> tag.

Categories