Replace multiple elements using replace with in query - javascript

I have a textarea and button that I need to replace with new ones. I use replaceWith in jquery to achieve this but it seems that I'm doing it wrongly.
This is my javascript:
<script>
$(document).ready(function () {
$(document).on('click', 'div', function(){
$('textarea, button').replaceWith('<textarea>New</textarea><button>Old</button>');
});
});
</script>
My HTML:
<textarea>Old</textarea>
<button>Old</button>
<div>Replace</div>
Clicking the Replace div should replace both the Old text area and the button with the new ones but for some reason it leads to displaying 2 text areas and 2 buttons.
Tried using $('textarea', 'button') but this does nothing at all.

If per your comments elsewhere you cannot split the two elements apart for text purposes, then alternatively you should ensure that both existing elements share a common parent (e.g. a <div>) and then replace the contents of that parent:
<div id="parent">
<textarea>Old</textarea>
<button>Old</button>
</div>
$('#parent').empty().append(newContent);
Alternatively if you cannot change the downloaded HTML, then within the event handler if you can assume that there are no other matching elements between the "replace" div and the original content:
$(this).prevAll('button').first().remove();
$(this).prevAll('textarea').first().remove();
$(this).before(newContent);

You should separate the two out, to avoid trying to replace both in the same statement.
$('textarea').replaceWith('<textarea>New</textarea>');
$('button').replaceWith('<button>Old2</button>');

Related

jQuery: How do I insert link text into input field?

I am working on an Ajax Live Search. My goal: When you click on one of the suggested results, the result shall be inserted into the search field. For example, when you enter "ros" into the input field and you want to look for roses and roses is a result suggested to you, then I want roses to show up in the search field on click.
<!-- Lets assume that up to this point the user has typed "ros"
into the following field -->
<input id="search" type="text">
<!-- ... then roses is a suggested result, with "ros" being highlighted -->
<ul id="results">
<li class="result">
<a>
<b class="highlight">ros</b>"es"</p>
</a>
</ul>
Here is the jQuery code that I have come up with so far, but it won't work:
$('#results a').click(function() {
var selection = $(this).html();
$('#search').val(selection);
});
Anyone has detected the error?
seems to be case of event delegation:
$('#results').on('click', 'a', function() {
what i see you have some dynamically generated links in the list as if user searches for something. if this is the case then you have to delegate the event to the closest static parent which is in your case is #results because an event is not bound to dynamically generated elements as they were not available when you bound the event.
Also there is a notice as you have a closing tag of </p> which doesn't have a opening tag. also if you want to place the text of the clicked element then you don't have to use .html(), you can use .text() method instead.
Yout HTML is invalid. You have a closing </p> without an opening one inside your <a> tag
Firstly I don't think you should simply use $(this).html() as it will include the html-tags, and you probably don't want that inserted.
But I think the reason you can't get it to work (I'm assuming absolutely nothing happens) is because you set the listener before the results are loaded, and hence they aren't bound to the links. Use $('#results').on('click', 'a', function(){}) to bind events "up front".
$('#results a').click(function() {
var selection = $(this).text();
$('#search').val((selection.replace("\"", "")).replace("\"", ""));
});

jQuery, DOM and on() method

I have a problem with jQuery, DOM and on() method. This is my div:
<div class="box">
<p class="addBox">Add Box</p>
<p class="remBox">Remove Box</p>
<textarea name="box[]"></textarea>
</div>
And a jQuery code:
$(document).on("click", ".addBox", function(event){
$(this).parent().append('<div class="box"><p class="addBox">Add Box</p><p class="remBox">Remove Box</p><textarea name="box[]"></textarea></div>').children(':last').hide().fadeIn(1000);
});
$(document).on("click", ".remBox", function(event){
$(this).parent().hide(1000).delay(1000, empty());
});
What I'm trying to achieve is a box with two buttons, one of them will make another copy of this box, and the other one will delete the chosen box. Two copies of the box are 'hardcoded' in index file, thus available in DOM from the start.
Buttons do they basic purpose, but DOM structure is getting crazy. If I press the 'add box' link on a newly created box, the new one will show up right after the one I clicked. However, sometimes it will show up at the end of the list. It's the same with 'del box' link, sometimes it deletes only one box, sometimes the one I want and two or three more. What do I do wrong? Thanks!
You probably want .after() (or .before()), but not .append(). That, and your .delay() syntax isn't correct.
$(document).on("click", ".addBox", function (event) {
$(this).parent().after('<div class="box"><p class="addBox">Add Box</p><p class="remBox">Remove Box</p><textarea name="box[]"></textarea></div>').children(':last').hide().fadeIn(1000);
});
$(document).on("click", ".remBox", function (event) {
$(this).parent().hide(1000).delay(1000).remove();
});
jsFiddle example
The reason that you're seeing all of your boxes removed sometimes is that you're appending new boxes to the parents of the .addBox item, which is the box div -- so you're getting boxes nested in boxes, rather than a bunch of .box divs in a row. If you change
$(this).parent().append( ... // removed for clarity
to
$('body').append( ... // the rest of your code
You won't get that improper nesting, and your boxes will correctly remove only themselves.

How to .append() an object

I'm making a simple game in javascript and I would like to .append() a box. To serve as a bullet. But I'm stuck. This is what I have
var existingdiv1 = document.getElementById('bullet');
and
$("#test").click(function() {
$("div").append([existingdiv1]);
});
It wont create additional "divs" when I press the button "#test".
You will have to select the existing div (I guess this is the bullet?). Then append it.
Here's and example:
Working Demo
Javascript:
$("#test").click(function(){
$("#appendToThis").append($('#bullet').html());
});
Html:
<input id="test" type="button" value="click" />
<div id="appendToThis"></div>
<div id="bullet"><div>BANG</div></div>
You will see the word "bang" be appended everytime you click. You can remove it by using the empty() method on the test div.
From the .append documentation:
If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned).
It seems like you want to clone [docs] the element first:
$("div").append($(existingdiv1).clone());
// or simpler
$("div").append($('#bullet').clone());
Note though that if you have multiple div elements on your page, $("div") will select all of them and the element you pass to .append will cloned automatically (as stated in the documentation).
You should append the element only to a single div.
I believe you wanted to add a new div to the existing div, so your code has been reversed the append order. and you need wrap the existing div by $('#bullet')
Try this
$('#bullet').append('<div></div>');
You can use .clone()
$("#test").click(function(){
$("#appendToThis").append($('#bullet').clone());
});

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());
});

dynamic tag count on keyup

I have a div that contains many spans and each of those spans contains a single href.
Basically it's a tag cloud. I have a textbox with a keyup event that filters the tag cloud div (It actually just hides the tags if not in filter condition).
Is there a way to get a count of the tags shown as the keyup event occurs?
Thanks,
rodchar
$("#filter_input").keyup( function() {
count = $("#cloud span:visible").size();
// Do something with the counted spans.
});
That should do it, substitute values as needed.
jquery size() Returns the number of matched elements.
$('.tags span a.visible').size();

Categories

Resources