Removed DOM element still appears on the page [duplicate] - javascript

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.

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

How to select text on click input box in JavaScript? [duplicate]

This question already has answers here:
Selecting all text in HTML text input when clicked
(29 answers)
Closed 2 years ago.
I am new to JavaScript and building an application in which, using plain JavaScript, I would like to select the text (similar to right clicking and select all) upon click of an element on a web page if the element is of type input. Can this be done? If so how would I go about doing this. Any info would be appreciated.
You can add this script at the bottom of your body tag
<script>
document.querySelectorAll('.js-select-input').forEach(input => {
input.addEventListener('click', (e) => e.currentTarget.select())
})
</script>
and for every input that you would like to have this autoselect functionality add the class "js-select-input" as in this example:
<input class="js-select-input" value="foo">
Use select method to achieve this.
Use select method in the callback function of input's onfocus event.
For better understanding, see the following example:
function testFunc(focusedInput) {
focusedInput.select();
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input id="test-input" type="text" name="test-input" value="default-value" onfocus="testFunc(this)">
<script>
function testFunc(focusedInput) {
focusedInput.select();
}
</script>
</body>
</html>

jQuery on not working for dynamically added elements [duplicate]

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.

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.

JQuery .on only firing once on dynamically generated elements

So I have the following problem. I am trying to add a two events to a table of checkboxes.
Here's an example of the html.
<body>
<div id='container'> //static element, everything beyond this element is dynamic
<div id='pane_x'>
<div id='bottom_x'>
<div id='bottom_left_x'>
<div id='results_x'>
<div id='list_x'>
<div id='table_1'>
<table>
<tbody>
<tr>
<td>
<input type='checkbox' name='blah' id='blah_obj.id_x' class='blahblah'>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
I am trying to select the checkboxes only hopefully by using a prefix selector [id^='blah_']. I am able to get the code working for the first pane ie: pane_0, but it doesn't fire on pane_1 or beyond.
jquery(document).on("change", "[id^='blah_" + obj.id + "']", function() {
//code here
});
There may be nesting errors as I just made an approximate estimate of the html. The weird thing is I can see them by using a daisy chained .children() statement, but I can't select the input elements.
Since the comments don't support the same code blocks as this section I'll just add it here:
jquery(document).on("change", ".checked", function() {
var ids = jquery(this).attr("id").split("_");
if (ids[0] === "blah")
//do code
}
});
edited the id for clarity. The id structure is "blah_" obj.id "_" individual iterator. So 3 checkboxes on pane 0 would look like this:
blah_0_0
blah_0_1
blah_0_2
there are 2 other sets of checkbox lists on this page that I do not want to target with these functions, that is why i'm using the prefix selector.
The point of using startsWith selector is not to try to complete the whole value as you are doing with obj.id if obj.id is even defined.
Following would find all input with ID's starting with 'blah_' either existing or in the future.
jQuery(document).on("change", "input[id^='blah_']", function() {
//code here
});
Using the class as selector makes even more sense if they all share a common class
jQuery(document).on("change", "input.blahblah", function() {
//code here
});
Also note you have typo in jquery should be jQuery unless you have defined it otherwise in your own code
Important note ID's may not be repeated in a page, in case you have been repeating the same checkbox ID. They must be unique by definition
here another sample :
$("body").on({
click:function(){
// where $(this) is the current item changed
}
}, "input.blahblah");
​

Categories

Resources