place results in a textbox after click - javascript

i'm working on an auto complete with jquery which is working perfectly. the results get displayed as the user types. Now the problem is when the user starts typing and the results appear, when the user clicks on the desired results, it doesn't get placed in the textbox
JS
$(function(){
$(".search_tab").keyup(function()
{
var searchid = $(this).val();
var dataString = 'fname='+ searchid;
if(searchid!='')
{
$.ajax({
type: "POST",
url: "http://localhost/myapp/search.php",
data: dataString,
cache: false,
success: function(html)
{
//console.log(html)
$("#result").html(html).show();
}
});
}return false;
});
$('.search_tab').click(function(){
jQuery("#result").fadeIn();
});
});
HTML
<input type="text" class="search_tab" placeholder="Search" autocomplete="off">
<div id="result"></div>

You'll need to do some event delegation over the items that get placed into the div#result element. You'll want something like this:
$('#result').on('click', 'RESULT_ITEM', function (event) {
$('input.search_tab').val(event.target.innerHTML);
});
Where RESULT_ITEM is a selector that matches the individual items that are listed in the autocomplete results.

While i dig into this have you considered using jQuery UI to acomplish this?
https://jqueryui.com/autocomplete/
This is a nice and polished way of doing exactly what you are wanting.
Not quite sure why I am getting down voted really as my suggestion is a perfectly valid solution to this problem...
That being said here is a working fiddle for you.
https://jsfiddle.net/wxr5y5gu/
The main part you seem to be missing is something like this:
$('#result').on('click','li',function(){
/* I used li as the element as im unsure what your response html looks like */
let newValue = $(this).text();
$('.search_tab').val( newValue );
$('#result').html('').hide();
});
That will clear the results, set the clicked value, and hide the results box for you.
That contains a working soution for you. As i dont have access to AJAX your local resources I had to extrapolate and create my own auto fill to show how it works in principal however i can certainly help you tailor the solution to your needs.
This solution uses your code and is compatible with all current jQuery versions.

Related

Ajax is not working (don't know why)

Hi and thanks to everybody in advance!
I want to do a simple thing with Ajax but is not working: push the button and change the html with another one from the same folder. Is something with the javascript but I can't identify the problem. I'm quite a novice with web design.
$(".about .ajax").on("click",function(e){
var section = $(this).closest("section");
var href = $(this).attr("href");
$.ajax({
url:href,
dataType:"html",
success:function(data){
var contenido = $("#about",data);
section.html(contenido);
}
});
e.preventDefault();
});
jsfiddle
I don't think you are binding it back properly.
I think you want something like this:
success:function(data){
$("#about").html(data);
}
Passing data as the 2nd argument will restrict jquery to find the right element.

Show all elements on typeahead focus

I am looking for a smart head.
I am using Bootstrap's typeahead and currently when I click my textfield, nothing happens.
How can I make it so, that when my typeahead textfield is clicked or gets focused, it shows all the options in the typeahead? Because currently I have to start writing for it to show anything. Maybe use a scrollbar if there's a lot of items in my list.
Thank you kindly.
I use a get to get all my items, and then this is my code. I have more than one autocomplete on this page, so they all have different id's.
$.get('link', function (data) {
var autocomplete = $('#typeahead-1').typeahead();
autocomplete.data('typeahead').source = data;
autocomplete.data('json', data);
}, 'json');
Would something like this work for you?
<input class="typeahead" type="text" >
<script type="text/javascript">
$(document).ready(function() {
$(".typeahead").on("click", function() {
$(this).typeahead('open');
});
}
</script>

Having issues calling an ID after I have appended data from an ajax call

Ok,
So I have a .on click event which is called to an ajaxed script. The script returns a set of HTML information.
Now, what I seem to be having an issue with and maybe I am just not typing the right search terms in for this so my apologies if this was answered already.
When the html is appended to the correct box, the user is then able to click a link on that box, drop down the box and see a new input box. The user should be able to type the text in and hit the enter key and it should work.
When I run an inspect element, I do see the element's ID properly inserted, but it is like javascript doesn't even recognize the new element id.
UPDATE: I am really not sure why you need code to be able to answer this question, however here it is. The code works normally unless the above happens so yes I am appending it, and yes I am SURE i am appending it, please make sure to read everything before posting a comment, thanks!
$('body').on('keypress', '.peapComment', function(event) {
if(event.which == 13) {
var peap_id = $(this).attr('rel');
var comment = $(this).val();
$.ajax({
type: "POST",
url: "index.php",
data: {
page: "postPeapComment",
peap_id: peap_id,
comment: comment,
}
}).done(function(msg) {
console.log(msg);
$('#comment_' + peap_id).append(msg);
});
console.log('Send to Peap #' + peap_id + ': ' + comment);
$('#commentbox_' + peap_id).val('');
}
});
I have tested your code, and it seems to work without problems for me. My assumption would be that the data returned from your ajax call, is failing to return the proper "Peap_ID" or not returning anything all around, as this is the only way I can reproduce what you have claimed your error is, otherwise the code you have posted looks great.

Help me make a jquery AJAXed divs' links work like an iframe

I want to make a few divs on the same page work similar to iframes. Each will load a URL which contains links. When you click on those links I want an AJAX request to go out and replace the div's html with new html from the page of the clicked link. It will be very similar to surfing a page inside an iframe.
Here is my code to initially load the divs (this code works):
onload:
$.ajax({
url: "http://www.foo.com/videos.php",
cache: false,
success: function(html){
$("#HowToVideos").replaceWith(html);
}
});
$.ajax({
url: "http://www.foo.com/projects.php",
cache: false,
success: function(html){
$("#HowToProjects").replaceWith(html);
}
});
This is a sample of code that I'm not quite sure how to implement but explains the concept. Could I get some help with some selectors(surround in ?'s) and or let me know what is the correct way of doing this? I also want to display a loading icon, which I need to know where the right place to place the function is.
$(".ajaxarea a").click(function(){
var linksURL = this.href; //
var ParentingAjaxArea = $(this).closest(".ajaxarea");;
$.ajax({
url: linksURL,
cache: false,
success: function(html){
$(ParentingAjaxArea).replaceWith(html);
}
});
return false;
});
$(".ajaxarea").ajaxStart(function(){
// show loading icon
});
Assuming you want to listen to click events for all anchor tags inside all elements with class ajaxarea, then your selector works fine:
$(".ajaxarea a").click(function(){ .. });
And this line of code, while not a selector (you're just accessing a property on the DOM element that was clicked), should work fine as well:
var linksUrl = this.href;
As for ParentingAjaxArea, you'll need to use $(this).closest() with a selector to determine which parent you want, but it's hard to give a specific example without knowing your HTML structure. It looks like you want ParentingAjaxArea to be either the element with id #HowToProjects or #HowToVideos, so you could write:
var ParentingAjaxArea = $(this).closest("#HowToProjects, #HowToVideos");
As for the loading dialog, I think this answer explains a good method (using ajaxStart and ajaxStop).
Edit: I also noticed you're using the click event--If you plan on being able to attach event handlers to links that will be inserted into the DOM via AJAX later, look at delegate or live.
$(".ajaxarea a").live('click',function(e){
e.preventDefault(); //*
var URL = $(this).attr('href');
var parentFrame = $(this).parent(".ajaxarea"); //**
$.ajax({
url: URL,
cache: false,
success: function(html){
parentFrame.replaceWith(html); //***
}
});
});
* - added preventDefault to prevent click action (see e in function's arguments)
** - instead of closest, i used parent – like it more for it's descriptive qualities
*** - the var containing parent AJAX frame should be jQuery object, no need to wrap it in $(..)
This should work fine, but beware, it's untested.
edit:
You probably need a live (okay, I'm sure you need it). what click() does it's that it adds to all elements at the time in DOM an onClick event. What live() does, it's that it waits for any change in DOM and runs used selector (.ajaxarea a) again and if it fits for any of new elements, it adds the action. In pseudocode, it does basically this:
DOM.hasChanged{
$('selector').click(..)
}
I used this example for my own web page:
http://www.queness.com/post/328/a-simple-ajax-driven-website-with-jqueryphp
It works quite well and uses hash tags and jQuery.history.js for the history of your browser. It works very nice, because you can let something like a media player just continue playing. Take a look at my own site elsewise, where you can find the javascript file: ajaxpages.js. I haven't used live(), but maybe I should.
Figured it out! The problem was I was using the function ".replacewith()" which was removing my AJAXed div(class="ajaxarea") entirely instead of replacing the content. The proper function to use here was ".html()".
Here is my working code to make an AJAXed div work like an iframe:
//onload to initialize the div
$.ajax({
url: "http://www.foo.com/projects.php",
cache: false,
success: function(html){
$('#HowToProjects').html(html);
}
});
$(".ajaxarea a").live('click',function(e){ // must use live instead of .click()
e.preventDefault();
var URL = $(this).attr('href');
var parentFrame = $(this).closest(".ajaxarea");
$.ajax({
url: URL,
cache: false,
success: function(html){
parentFrame.html(html);
}
});
});

Popup using jQuery?

I'm trying to do a pretty simple thing, I believe. I need to popup a success confirmation dialog after a user clicks to add someone to his friends list. Simply there's an add link on the page with the url (mysite.com/add/friendname). I needed to make issue this request asynchronously so I used jQuery.ajax built-in function to send the request. Take a look at the following code:
$(document).ready(function() {
$('.track_links').click(function() {
if (confirm("are you sure you want to track <firstname lastname>?")) {
$.ajax({
type: "GET",
url: this.href,
success: function() {
alert("Congratulation! you're now tracking <firstname lastname>");
},
error: function() {
alert("Oops! An error occured, plz try again later!");
}
});
return false;
}
else {
return false;
}
});
});
Now, here's what I need to do in short:
1- I need to use an already designed Html form as the success or failure confirmation message, instead of just alerting!
2- I also need to replace a placeholder (###username###) on that html page with the actual user name (firstname space lastname) which is the value of another field on the document. How to manipulate this html before poping it up on the client?
p.s: My Html/Javascript skills is totally awesome ;) (well, not really)!
For the first part
You can use the
show
function to show a div in the ajax success function.
$("#divResult").show();
if divResult is the id of the div to be shown
For the second part
you can get the value of first name and last name using
$("#txtFirstname" ).val();
and
$("#txtLastname" ).val();
if your first name text box id is txtFirstname and last name text box id is txtLastName
This is how I setup an Acknowledgement dialog, which could quickly be modified to be a confirmation for an action like yours.
http://professionalaspnet.com/archive/2009/06/02/Displaying-a-Confirmation-Dialog-with-the-JQuery-UI-Dialog.aspx
For the Form, I would suggest the html() Method, which injects raw HTML you have to provide. Since you already have it, you can give it to the Method via parameters.
For the Placeholder Part, I would suggest the val() Methods, coupled with Javascript's built-in regex functions.
If your placeholder is "###firstname###", then you should try something like
var firstname = jQuery('input#firstname').val();
var lastname = jQuery('input#lastname').val();
var text = jQuery('span#ThePlaceMyPlaceholderIsAt').text();
text = text.replace(/\#\#\#firstname\#\#\#/,firstname);
text = text.replace(/\#\#\#lastname\#\#\#/,lastname);
jQuery('span#ThePlaceMyPlaceholderIsAt').text(text);

Categories

Resources