jquery button click not working , using django templates for rendering - javascript

I have multiple buttons on the same page with same id so basically
rendering in a for loop with same id . I set a click event handler in
jquery but it fires for only the first button.
Can you suggest?

You can see the error in console, which probably would be because of same ID for all the buttons. One solution would be to append the index to the button id string so that each button will have unique id(btn1, btn2 etc), or use the class instead of id.

Duplicating ids are causing your HTML to be invalid. Javascript (and jQuery) assumes that there is a single id, therefore:
$("#yourid")
will not search for the id further.
You can sidetrack the issue via
$("[id=yourid]")
which will find all the elements, but that's not advisable, because then your HTML is still invalid. A better approach would be to change your id into a class and use that as a selector afterwards.
EDIT
In jQuery you can create a click event like this:
$("[id=saveFavorite]").click(function() {/*...*/})
But even though this will work, I recommend refactoring your code, changing the HTML you have by replacing every id="saveFavorite" to class="saveFavorite" and do it like this:
$(".saveFavorite").click(function() {/*...*/})

Related

How to use click event on <a> tag

How to use click event on tag without id
Hello everybody, I have a html tag bellow:
<a class="fc-day-grid-event fc-h-event fc-event fc-start fc-end fc-draggable fc-resizable" href="https://www.youtube.com/watch?v=XXXXX"><div class="fc-content"> <span class="fc-title">event</span></div><div class="fc-resizer fc-end-resizer"></div></a>
this html code was built automatically by jquery so I can't add id or "onlick" event on this tag.
What I want is when I click on this tag, it will open a new windows with href for me. I tried to use
$('.fc-day-grid-event).on('click, function() {
...//
});
But it's not working.
How should I do for this case? Please help.
this html code was built automatically by jquery so I can't add id or "onlick" event on this tag
If you can't control when that happens, you can still use event delegation to get involved in the click event:
$(document).on('click', '.fc-day-grid-event', function() {
...//
});
That works even if the code runs before the element exists. The code in your question only works if the element exists as of when your code runs. See the documentation for details.
As the code is generated after the page rendering, you should use a delegated event handler:
$('body').on('click','.fc-day-grid-event', function() {
//...
});
The original code is missing apostrophes after the class name and after the 'click'.
This should work:
> $('.fc-day-grid-event').on('click', function() {
...//
});
However you might consider to check, if there are other dom elements with that class. An ID is much safer. A workaround could be to use multiple classes in the jQuery selection by selecting the element(s), that matches them all:
$('.fc-day-grid-event.fc-h-event.fc-event.fc-start.fc-end.fc-draggable.fc-resizable')
but this might still be not sufficient, because these framework-classes seem to be dynamically created and maybe deleted and the selection might be too wide or too narow. You could try to select the a tag with parent/child relations, where you know, that you are getting the right element and you could even use the innerHTML of the elements. Alternatively you could iterate through a JQuery-Selection and check for certain attributes.
I'm not sure, if you want to change the target of the link or the target window of the link. Opening the target of a link in a new window works with standard html by using the target attribute
<a href='bla' target='_blank'>bla ...
If you use Javascript for manipulating the target adress of a link outside of the href, the code might get hard to maintain in most contexts and the user might get confused, because he get's to page, he didn't expect. I would try to manipulate the Javascript, that is creating the a tag or if that's really impossible, i would manipulate the existing a tag according to my needs and change the attributes like this, if you want to use jQuery:
For the target address of the link:
$('.fc-day-grid-event').attr("href", "www.newhrefvalue.com")
Or for opening the link in a new tab:
$('.fc-day-grid-event').attr("target", "_blank")
Then you don't need to prevent or emit events or create event listeners.
<a onclick="doStuff(this)">Click Me</a>

How to identify elements in the DOM to use in click button event?

Trying to learn some Javascript now that I have a few months of Python under my belt. Having trouble with HTML elements on a page which uses Javascript (not sure that is the right wording).
I have a simple Chrome Extension which I am trying to tell it to click a button when the page loads.
The DOM shows this code more or less:
<body class="skin-mark toolbar-open table-active">
<div class="tile-tables"></div>
</body>
My attempt at clicking the button has been multiple ways similar to this:
document.querySelector('#tile-tables').click();
Any help in understanding the process here and what I am doing wrong would be great! Thanks in advance! Feel free to correct me at any place and I will fix my language.
When you use getElementById you have to pass an element's id to it. There is only one element with an id in your HTML, the outer userActActions-51 - so, if you were to select by ID first, you would do
document.getElementById('userActActions-51')
and then you would access the second nested child:
const userActions = document.getElementById('userActActions-51');
const span = userActions.children[0].children[0];
span.click();
But it would be more convenient to use querySelector for this, which will allow you to use a selector string to select the span descendant of the element with the id userActActions-51 at once:
document.querySelector('#userActActions-51 span').click();
If the element might not exist, then make sure that it exists before trying to click on it:
const span = document.querySelector('#userActActions-51 span');
if (span) span.click();

jquery .text() updating "source" but not the DOM

This is my jquery scenario:
User click on div
It triggers an ajax call to save some data on DB
when callback received, we show an update msg <--everything good
until here
Now, when user click on the same element, it shows the information
from the DB, the same should happen with the other divs!
Noticed that when you click, the same text that you saved later is showing up in all the divs!!! it is not refreshing, but the actual source IS showing
the changes!
It looks like only the DOM is not reflecting the changes!
I am trying to put the text in the divs using .text();
All the divs are using the same element id!, I am just updating its data!
Thanks,
Marco
All the divs are using the same element id! - never ever should two elements have the same ID, because it breaks the principles on which HTML is built on and 3rd party libraries rely on.
If you need to target multiple elements use classes.
In case your elements have the class yourClass and you want to set them the text "foo", then
var yourResponseText = "foo";
$('.yourClass').text(yourResponseText);
Especially if you use jQuery - the ID selector is implemented in such way, that when it finds an element with that ID it doesn't look for another - the settings will only affect the first (from the viewpoint of DOM) element. On the other hand, when you're using the class selector, then simply said you're doing a forEach cycle through the elements with that class.

How to access elements from a certain form and certain type with jquery

so I have a page with multiple forms and I would like to be able to access input elements of type="datetime" within a particular form. I know I can do $('input[type="datetime"]') but that would give me all input tags on the page. I also cannot use the "form" attribute because not all browser use it (Sigh IE). Worse scenario for me is to do something like:
$(document.forms["..."].elements).each(function() {
if (this.type="datetime") {.....}
});
but I am sure this can be done in jQuery with one selector. Can someone tell me how do this with one selector?
Add id to your form and then select DOM inside of that form as below.
$('#form input[type="datetime"]')
Without seeing some HTML this is just a shot in the dark. But if you give your forms an id you can do:
$("#yourFormId input[type='datetime']");
If you do not have ids, but you know the number, then this might do it:
$("form:eq(4) input[type='datetime']");
There are multiple ways to do it
Solution 1.
use descendant selector
ex:
$('#yourform input[type="datetime"]') //or
$('.yourform input[type="datetime"]') //or
$('form:eq(3) input[type="datetime"]')
Solution 2:
Use context based look up
Ex:
$('input[type="datetime"]', yourform)

How to make function work after append

For example i'm using append, and for example i'm appendig button in to a div, and i have function $('button_id').click(... etc to work affter i append the div, how can i do that.I mean i get no errors, but the function is not starting, it's because i append and then i want to use the function but how to do that, i tryed with delegate, but same thing.I tryed with function in the button tag , onmouseover and then the function thing, but nothing it gives me function not found.What is the solution ?
I have two events, one event is click event that appends button, the other event is click event that does something if the button that was appended is clicked, but that second event is not working ?
Try using :
$(elem).live(...)
It will bind event for now and in the future.
Firstly, it always helps if you show us the exact source code. $('button_id') is the incorrect selector to start with, try something more along the lines of $('#button_id') as your selector. Also, are you appending dynamic content? Anyways, I've always used the delegate() function quite successfully, but have you tried using the live() function? Also, one more thing to make sure of is that you have the newest version of jQuery as your source.
As was stated as well, you can not have duplicate ids, if you want to have a pointer, use class, instead of id="some_id" use class="appended". To select those using jQuery, use the selector like this $('.appended').
Try something like this it will work as per your expectations.
$("#button_id").click(function(){
//On click code goes here
}).appendTo($("#div_id"));
It's difficult to determine the problem you're having without seeing your code, but delegate (or live) should be perfect for what you're trying to do:
$("body").delegate("#b", "click", function() {
alert("ok");
});
$("#example").append('<input type="button" id="b" value="Click" />');
The click handler above will fire when an element with id="b" is clicked, whether or not that element happens to be in the DOM right now or not.
However, as others have noted, it's important to remember that IDs need to be unique within a document, so by the sounds of it you may be better of using classes instead.
You can see an example of the above code running here.

Categories

Resources