Jquery remove element - javascript

I am basically trying to print the value of a button in the div with list class if the button is selected. Also remove the same value wwhen it is deselected. I am able to print the value successfully but not able to remove it. Could somebody please help me out with it.
var buttonSelect = $(".btn").click(function() {
if ($(this).hasClass('active')){
$(".list").append(this.value + " ")
}
else {
$(".list").remove(this.value)
}
});

You should rather append the content along with html element like span:
$(".btn").click(function() {
if ($(this).hasClass('active')){
$(".list").append('<span class="newval_'+this.value+'">'+this.value + "</span>");
}else{
$(".list").find('.newval_'+this.value).remove();
}});

The parameters from .remove() is a selector, just having a value in there that contains the content of the element you want to remove will not work. For example if I had this:
<li class="list">test</li>
Doing $(".list").remove("test") will not remove it. You will probably want to use the :contains selector (since you may have the value with spaces at the end). So in the example above doing $(".list").remove(":contains('test')") will remove the element. You can do the same thing in your case:
$(".list").remove(":contains('"+this.value+"')");

If you want to remove the element itself along with everything in it, just use jQuery’s remove() method.
$(document).ready(function() {
$("button").click(function() {
$("div").remove(); //remove Div element
});
});
You can see an example here: How to Remove Elements from DOM in jQuery

Related

Adding onclick events to appended div tags in JavaScript

I am trying to add a click event to a bunch of div elements that I created by appending them and I am having some trouble.
I have a bunch of div elements the with the ids a0 ---> an. I am trying to create a for loop after the divs are created to assign them click events. The issue is the way I am doing it when the click event happens I do not have any way to track which div fired the event. The code bellow might make that more clear. So the issue I am having is that #a + i always returns the last div, and I want it to return the div number that was clicked.
$(document).ready(function () {
traverse(oo);
for (i = 0; i <= groupNum; i += 1) {
$("#a" + i).click(function () {
console.log("#a" + i + "clicked");
});
}
});
I thought about returning a closeur, but that seems I would make it even more complicated. Does anybody have any advice on how to do this the best?
Thanks in advance.
I'm not sure what you are trying to do but if you just want to assign a click event to a bunch of elements then use the correct selector (note the use of $(this) to get the clicked element):
$("div").click(function(){
var clickedDiv = $(this);
var id = clickedDiv.attr("id");
});
If you don't want ALL div elements, then you could add a class to them and use a different selector:
$(".MyDivClass").click(function(){...
or without the class, a 'starts with' on the id (the following with get all div elements where the id attribute starts with "a"):
$("div[id^='a']").click(function(){...
If you are dynamically adding divs with other javascript and you want them to automatically have the click events, use the on function...
$(document).on("click", ".MyDivClass", function(){...
The variable i will, as you noticed, will contains the value set on the last iteration. Change
console.log("#a" + i + "clicked");
by
console.log(this.id + " clicked");
Within the event handler, this is the target DOM element for the event.
You can do it in this way:
$('[id^="a"]').click(function () {
console.log(this.id+" clicked");
});
You may assign a click event to a class instead of to specific ID's and use conditional statements within the click function to do different things base on ID.
$(documnet).ready(function(){
$('.clickclass').click(function(){
/* conditional code here */
});
});

use of Jquery .after() for moving an element around

I'm reading the jquery manual regarding the .after() function:
$('.container').after($('h2'));
and it says
"If an element selected this way is inserted elsewhere, it will be
moved rather than cloned"
So if I have multiple
<div class='before' onclick='afterfunction();'><div>,
and I would want to place <div class='after'></div> after whichever div is clicked (have it move, not clone) would I do something like this?
var afterdiv = "<div class='after'></div>";
function afterfunction() {
$(this).after(afterdiv);
}
Thanks for all your help!
Like you said:
An element in the DOM can also be selected and inserted after another element:
$('.container').after($('h2'));
If an element selected this way is inserted elsewhere,
it will be moved rather than cloned:
But you missed the bold part.
$('.before').click(function() {
afterfunction(this);
});
// this will not work cause you'll append a string to your DOM
// var afterdiv = "<div class='after'>ola</div>";
// and will repeatedly be appended after each action.
// instead define your element by wrapping it into a $( )
var afterdiv = $("<div class='after'>ola</div>");
// now 'afterdiv' variable is binded to that element only once inside the DOM
function afterfunction(elem) {
$(elem).after(afterdiv);
}
And you don't need to .remove() it (like wrongly suggested in an answer here.)
demo jsFiddle
Make .before div like this:
<div class='before'><div/>
Then try,
$('.before').on('click', function() {
afterfunction(this);
});
function afterfunction(el) {
var afterdiv = "<div class='after'></div>";
$('.after').remove(); // remove previous `.after`
$(el).after(afterdiv); // add newly after the clicked div
}
DEMO

How to add a class when a link has a certain label

I have a series of links with no a classes. I am unable to manually add any classes in the HTML...otherwise I would. I want to use either JavaScript or jQuery to detect a certain link label and add a class to it if the match is found.
Here is the HTML:
<ul class="menu-main-nav">
<li>Duck</li>
<li>Duck</li>
<li>Goose</li>
</ul>
I want to add a class whenever "Goose" appears. Here is what I attempted... and failed.
$(document).ready(function(){
if ($("#menu-main-nav li a").text() == "Goose") { this.addClass("itsagoose")};
});
Use the .filter method:
$("#menu-main-nav li a").filter(function(){
return $(this).text() == "Goose"; //<--- Only include these elements
}).addClass("itsagoose");
Use .html() instead of .text() if you want an exact match, and don't want to allow anything else (eg, don't match <a><span>Goose</span></a>).
Fiddle: http://jsfiddle.net/RWSCY/
Look at the jQuery contains selector. That's what it's for :)
Well, you could use filter:
Demo
$("a").filter(function(){
return $(this).text() == "Goose"
});

jquery .each() loop

i want to read all links in ".vm-video-title"-divs and post them each in the same div. So i made this script:
$('.vm-video-title').each(function(i) {//all divs
$(this).html($(this).html()+$("div.vm-video-title>a").text());//add to div the link
});
but i have the problem that it reads ALL the links of all divs and put them in one div.
example:
<div class="vm-video-title">Text1</div>
<div class="vm-video-title">Text2</div>
<div class="vm-video-title">Text3</div>
output:
Text1Text1Text2Text3
Text2Text1Text2Text3
Text3Text1Text2Text3
wanted output:
Text1Text1
Text2Text2
Text3Text3
You can select the <a> elements directly, and use the after()[docs] method to append the content of each after each one respectively.
$("div.vm-video-title > a").after(function() { return $(this).text(); });
This doesn't do a "destroy then recreate" of the existing elements like the html()[docs] method will.
Working example: http://jsfiddle.net/CCr9C/
This should do the job for you,
you need to find the div inside current element in the loop (el).
$('.vm-video-title').each(function(i, el) {
el = $(el);
el.html(el.html()+el.find("a").text());
});
in your code you are adding text() of all matching "a" tags in your divs (i.e. Text1Text2Text3)
You were almost there. Instead of : $("div.vm-video-title").text(), which gives you text inside any div with class vm-video-title, you need to find a tag inside current div and get text from it. We pass this as context for selecting a inside current div jQuery( selector, [context] )
$('.vm-video-title').each(function(i) {//all divs
$(this).html($(this).html()+$("a", this).text());
});

why this javascript code is not working?

Do you know why this is failing, I mean alert is working (it shows me that if found the button) but text or background is not changed:
$('input[type=button]').click( function() {
var button=document.getElementsByName("contactme");
alert(button.length + " elements!");
button.value="New Button Text";
button.style.backgroundImage="url(some_real_gif);"
});
HTML:
<input type="button" name="contactme" value="test"/>
Thanks...
I have to use plain java script not jQuery..
You're setting value and style of a NodeList. getElementsByName can retrieve multiple elements, as the name attribute does not have to be unique in the document (the clue's in the name!) Setting these has no effect -- it doesn't affect the properties of the element(s) within the NodeList.
Either loop through the element(s) manually (using a for loop) or fully use jQuery:
$('input[type=button]').click(function () {
var buttons = $('input[name="contactme"]');
alert(buttons.length + " elements!");
buttons.val("New Button Text");
buttons.css({backgroundImage: "url(some_real_gif)"});
});
See the jQuery API:
val
css
attribute-equals selector ([name="value"])
It looks like var button=document.getElementsByName("contactme"); would return an array of elements. Try:
var button=document.getElementsByName("contactme")[0];
getElementsByName will return a nodeList but value and style are properties of HTMLElementNodes. You have to loop over the list to get them.
$('input[type=button]').click(function() {
$("#contactme").val('New Button Text').css('background-image', 'url(some_real_gif)');
});
You would need to make sure the button id matches the name...
Because button is a list of elements (even if it is a list of one)
What you can do is use button[0].value and button[0].style.background
Or use a jQuery solution:
To change only clicked button:
$('input[type=button]').click( function()
{
$(this).val("New Button Text");
$(this).css('background-image','url("some_real_gif")');
});
To change all buttons:
$('input[type=button]').click( function()
{
$('input[type=button]').each(function(){
$(this).val("New Button Text");
$(this).css('background-image','url("some_real_gif")');
});
});

Categories

Resources