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

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

Related

How do I get a jQuery function to work with specific elements when they have the same class names?

I have sections (divs) with text in it, but when the text is too long I made it so the text "fades" (with css) and displays a "show more" button, which shows the full text for that specific div when clicked. The problem is that it only works for the first div, and I believe it's because they all have the same class and id name. What's the best way to get around that? Here's my code:
HTML:
<div id="fade-container">
<div id="fade-content">
<p>
Long text goes here...
<div class="fade-anchor"><span class="btn-primary round-xl small btn-shadow">Show more</span></div>
</p>
</div>
</div>
Script:
<script>
$('.fade-anchor').click(function(e){
e.preventDefault();
$('#fade-content').css('max-height','none');
$('.fade-anchor').remove();
});
</script>
By the way, info is being fetched from the database in a php while loop.
When the user clicks on .fade-anchor you can use thisto get the element currently selected, you should also use classes instead of ids for multiple elements, like so:
$('.fade-anchor').click(function(e){
e.preventDefault();
$(this).parent('.fade-content').css('max-height','none');
$(this).hide(); // Maybe you should hide instead of removing, in case you want to add a toggle effect later on.
});
You can also check out this jsFiddle with the working version.
Hope it helps.
You can achieve it by e.currentTarget
$('.fade-anchor').click(function(e){
e.preventDefault();
$(e.currentTarget).css('max-height','none');
$('.fade-anchor').remove();});

prev() not returning div element

I'm probably being especially dense about this, but I can't get an element to return using prev(). My basic HTML structure is:
<div>
<table></table>
</div>
<input type="button">
Where when I press the button, I want to get the previous element (the div element). To achieve this my button has a function attached to it with
var nearestDiv = $(this).prev();
When I've checked the contents of nearestDiv in the console it appears to be some kind of JQuery object rather than a HTML div. I've tried popping .val() at the end of .prev() but this comes back empty. How can I get the div element?
Note that my button is generated on the fly and doesn't have anything which identifies it.
you need to use jquery get function, to get a native html object and not the jquery wrapper:
$("input").on("click",function(){
console.log("jquery wrapper:",$(this).prev());
console.log("native html div object:",$(this).prev().get(0));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<table></table>
</div>
<input type="button">
If your html structure is same as you provided in the question, it will definitely return the div element. Note that there is no val() method for div element, you need to either use .html() or .text() inorder to get the contents.
$("input[type='button']").click(function () {
var div = $(this).prev();
alert(div.html());
alert(div.text());
});
Fiddle
You need to give .text() or .html() for standard HTML Elements. So your code should be:
var nearestDiv = $(this).prev().html();
var nearestDiv = $(this).prev().text();

Replace multiple elements using replace with in query

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>');

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

grab span text using jquery and pass as query

<span class="MapDirections" style="padding-top:10px">
<span class="HosAddHidden" style="display:none;">
<xsl:value-of select="concat(#ADDRESS_LINE_1,',',#CITY,' ',#STATE,' ',#ZIP)" />
</span>
Maps & Directions
</span>
How do I grab the span class HosAddHidden text which is some address and pass it to the the map url like this:
<a href="http://maps.google.com/maps?q=" onclick="location.href=...." return false;>Maps and directions</a>
I see from your response above that you have multiple HosAddHidden. Provided each one is followed by the anchor you want to manipulate (as your example above), you want to loop over each of the hidden addresses and change the href of the anchor following it. Here you go:
$('.HosAddHidden').each(function(index) {
$(this).next().attr('href', 'http://maps.google.com/maps?q='+$(this).text());
});
Note, this is not on an onclick, but rather should be run when the dom loads and changes all the anchors for you. The benefit of not putting it on an onclick is the actual href has already been changed, so someone can right-click the anchor and copy-it, open in new tab, etc.
Try this instead on using inline click handler. You can use text() to grab the text from span which you can select using .HosAddHidden class selector.
$('a').click(function(e){
e.preventDefault();
location.href = $(this).href + $.trim($('.HosAddHidden').text());
});

Categories

Resources