jQuery on not working for dynamically added elements [duplicate] - javascript

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 9 years ago.
I want to use .on on dynamically created elements... Although its not working, and yes I am using a selector :)
$(".metadata").on("click", "i.icon-remove", function () {
console.log("what");
$(this).parent(".metadata").slideUp(function () { $(this).remove(); });
});
This works perfectly for existing content, but not for anything thats dynamically created. Both initial and dynamic content use the exact same creation method so I know their signatures are the same, any ideas?
Here is my HTML as it stands, the first item is present in the HTML, the second is dynamically created
<div class="metadata">
<input type="text" value="" style="width: 200px;">
<i class="icon-remove"></i>
</div>
<div class="metadata" style="">
<input type="text" maxlength="100" style="width: 200px;">
<i class="icon-remove"></i>
</div>

Try this
$(document).on("click", ".metadata i.icon-remove", function () {
console.log("what");
$(this).parent(".metadata").slideUp(function () { $(this).remove(); });
});

As an addendum to Pranav's answer, avoid if at all possible doing delegated events off of $(document) - that results in all events that happen anywhere in the page being inspected for matches to your selector.
Far better would be to use a more targeted selection that exists on the page from the start. Something like
$('#otherDivThatsThere').on("click", "i.icon-remove", function () {
console.log("what");
$(this).parent(".metadata").slideUp(function () { $(this).remove(); });
});
Where, again, #otherDivThatsThere is already in your dom at the moment that line of code is run.

Related

How to add class in input type text using Javascript? [duplicate]

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 1 year ago.
I want to add a class with input tags Because there is a problem with my display (it not beautiful) And I have to Add this class by using javascript and my code is as follows But it doesn't work I'm not sure where I went wrong.
mychoices.html
<script>
document.addEventListener('DOMContentLoaded', function() {
new Choices('#choices-remove-button', {
removeItemButton: true,
});
var inputs = document.querySelectorAll('input[type=text]');
inputs.classList.addClass("browser-default");
});
</script>
myform.html
<div class="section">
<form action='.' method='POST'>
{% csrf_token %} {{ form.media }}
{{ form }}
<input type='submit' value='Save' class="button" />
</form>
</div>
Which I added classes browser-default and other existing classes must work correctly.
What should I do?
Thanks
So you're really close.
The first thing to note is that document.querySelectorAll returns a NodeList (like an array of elements). So you'll need to use forEach to loop over each input.
From MDN
The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.
The second thing is that the classList.addClass doesn't exist. It's just classList.add. For more about Element.classList, please refer to this MDN article: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
Try the following instead:
<script>
document.addEventListener('DOMContentLoaded', function() {
new Choices('#choices-remove-button', {
removeItemButton: true,
});
var inputs = document.querySelectorAll('input[type=text]');
inputs.forEach(function (input) {
input.classList.add("browser-default");
})
});
</script>
X/Y problem "there is a problem with my display" - explain the problem instead of trying to fix a solution that might not be efficient or good practice. Also what is Choices ?
To answer your immediate question:
You are trying to add a class to a node list. That is jQuery syntax.
In vanilla JS, you need to use classList.add to each
document.querySelectorAll('input[type=text]').forEach(input => ;
input.classList.add("browser-default"));
or similar loop

jquery attribute listener for onclick [duplicate]

This question already has answers here:
Selecting element by data attribute with jQuery
(12 answers)
Closed 8 years ago.
I want to set a listener to handle button clicks which I know could be done with:
$("#id").click(function() {...});
but i was wondering if there is a way to make it listen to an attribute rather than an ID. because i would like to add custom attributes for example
<span class="btn btn-primary" button-type="css-change"></span>
and i would like to do something like
$(document).attr("button-type").equals("css-change").click(function () { ... } );
is this at all possible?
Use attribute-equals selector [attribute='value']
$("[button-type='css-change']").click(function() {
alert("clicked");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<span class="btn btn-primary" button-type="css-change">hi</span>
You can do this with a attribute selector.
http://api.jquery.com/category/selectors/
In your case the:
http://api.jquery.com/attribute-equals-selector/
You can use the attribute-equals selector:
$("[button-type='css-change']")
Altho you should stick with data-* for custom attributes to pass validation.
$("[data-type='css-change']")
yes you can loop though all the elemnts in the .btn class ..
<span id="1" class="btn btn-primary" button-type="css-change"></span>
<span id="2" class="btn btn-primary" button-type="test"></span>
<script>
$(".btn").each(function()
{
if($(this).attr("button-type") == "css-change")
{
console.log("The winner is "+$(this).attr("id"));
}
});
</script>
or there is also an easier way ..
$("[button-type='css-change']").each(function(index)
{
$(this).html("hi");
}

jQuery - Hide & Show Element REVERSE [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I got this code off the internet and I'd Like it reversed so the Element is hidden and a button is pressed to show it.
jQuery:
jQuery(document).ready(function(){
jQuery('#hideshow').live('click', function(event) {
jQuery('#hide').toggle('show');
});
});
HTML:
<input onclick="change()" id='hideshow' type="button" value="Hide">
<div id='hide>
*content here*
So basically i'd like it reversed if possible. So the Element (div) is hidden, and the button (input) is clicked to show it.
You can do this with jQuery:
jQuery(document).ready(function(){
var $divHide = jQuery('#hide');
$divHide.hide();
jQuery('#hideshow').live('click', function(event) {
$divHide.toggle();
});
});
But I'd recommend you do it with CSS (with your jQuery in tact as it is now):
#hide
{
display: none;
}
I recommend this approach because Javascript executed on DOM ready can sometimes be visible to the user. Meaning your #hide div will be visible initially (if only for a split second).
Also (as an aside), I'd rethink the naming convention a bit. I wouldn't call a div 'hide', especially when, on occasions, you'll want it to show.
.live() was deprecated, you should use .on() instead, and also use .toggle():
jQuery(document).ready(function(){
jQuery('body').on('click','#hideshow', function(event) {
jQuery('#hide').toggle();
});
});
HTML:
<input onclick="change()" id='hideshow' type="button" value="Hide">
<div id='hide' style="display:none;">
^ check for this apostrophy
JS:
jQuery(document).ready(function(){
jQuery('#hideshow').on('click', function(event) {
jQuery('#hide').show();
});
});
.live doesn't get used anymore and got removed from the jquery api on version 1.9. So to ensure compatibility with newer versions you should use the on method instead (http://api.jquery.com/on/)
If you want to toggle the element, keep using
jQuery('#hide').toggle("show");
.show(); will only show and not hide it
try
jQuery(document).ready(function(){
jQuery('#hide').hide();
jQuery('#hideshow').live('click', function(event) {
jQuery('#hide').toggle('show');
});
});
DEMO
Jquery (replace live by on):
jQuery(document).ready(function(){
jQuery('#hideshow').on('click', function(event) {
jQuery('#hide').toggle();
});
});
HTML (add a single quote at the end of id='hide' and the closing tag </div>):
<input onclick="change()" id='hideshow' type="button" value="Hide">
<div id='hide'>
*content here*
</div>
CSS (add this css rule):
#hide {
display: none;
}
You need to trigger $("#hide").show(); on clicking on button element.
HTML Code
<input id='hideshow' type="button" value="Hide">
<div id='hide' style="display: none;">
LoremIpsum
</div>
jQuery Code
$("#hideshow").click(function(){
$("#hide").show();
});

Removed DOM element still appears on the page [duplicate]

This question already has answers here:
How to remove an HTML element using Javascript?
(11 answers)
Closed 8 years ago.
I'm trying to add/remove a DOM element (id ="result") dynamically. The addition seems to work fine but after removal the element still appears on the page.
What's happening here? What am I doing wrong?
Here is my code:
<!DOCTYPE html>
<html>
<body>
<script>
function clearResult() {
if (document.getElementById("result") != null){
alert("remove #result");
$("#result").remove();
if (document.getElementById("result") != null) {
alert("#result still exists");
}
}
alert("Exiting clearResult");
}
function search() {
clearResult();
if (document.getElementById("result") == null) {
alert("add #result");
$('<table id="result"><tr>I am a table</tr></table>').appendTo('#ex');
}
}
</script>
<div>
<button id="search" onclick="search()" value="Send">Search</button>
</div>
<div id="ex">
#*Add result table here dynamically*#
</div>
</body>
</html>
Your HTML is invalid. Content within a table needs to be in td tags. Without those, your code is being rendered as:
I am a table
<table id="result"><tr></tr></table>
You can see that then removing the #result element appears to do nothing, because the text does not disappear. If you change your code to include the td elements, it works fine:
$('<table id="result"><tr><td>I am a table</td></tr></table>').appendTo('#ex');
Example fiddle
Note that you can also massively simplify your code. You don't need to check for the existance of an element before removing it in jQuery. Also, you should use jQuerys event handlers, instead of outdated on attributes. Try this:
<div>
<button id="search" value="Send">Search</button>
</div>
<div id="ex"></div>
$('#search').click(function() {
$('#ex').empty().append('<table id="result"><tr><td>I am a table</td></tr></table>');
});
Updated fiddle
I use empty() here on the #ex element to save a selector, it has the same behaviour as remove(), except is performed on the children of an element, not the element itself.

Appended Elements Using .on Method Unable To Be Removed

jQuery is deciding to be dumb or I'm simply missing something, but removing appended elements does not work for me using the following code:
$('#add-show').click(function() {
if ( $('#fav-search').val() == '' ) {
// do nothing
}
else {
$('.fav-results').append('<code><span class="icon-remove"></span>' + $('#fav-search').val() + '</code>');
}
});
$('.fav-results code').on('click', 'a', function() {
$(this).parent().remove();
});
And the HTML for anyone who is interested:
<div class="input-append">
<input class="span2" id="fav-search" type="text">
<button class="btn" type="button" id="add-show"><span class="icon-plus"></span></button>
</div>
<div class="pull-right fav-results">
<?php foreach($shows as $show): ?>
<code><span class="icon-remove"></span><?php echo $show['showname'] ?></code>
<?php endforeach ?>
</div>
Existing titles pulled from my database table are able to be removed but no appended elements can be.
I originally was using a .click handler but I read that it only works for elements existing in the DOM at the time of page load. After reading previous questions of the same nature I changed to using .on but it's still acting the same.
For your click event to apply to dynamically created elements, you should delegate it to the ancestor <div> instead of the <code> elements:
$(".fav-results").on("click", "code a", function() {
$(this).parent().remove();
});
You are using remove() instead of detach() which is removing the event handlers on all of the code elements before they are executed.

Categories

Resources