JQuery is not detecting my DOM Object when clicked [duplicate] - javascript

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 8 years ago.
Having a bit of trouble figuring out what is going wrong here and wondered if anyone might be able to help me out. I'm using JQuery throughout my site but for some reason on this particular page it does not seem to be working.
This code here:
$("#keyword").autocomplete({
source:'../../pages/ajax/autocomplete/autocomplete_tags.php',
dataType: 'json',
minLength:1
});
//When you hit the search button load the new tags
$("#srchBtn").click(function(e){
e.preventDefault();
var tag_name = $('#keyword').val();
$(".dashboardtable").load('../../pages/ajax/autocomplete/search_tags.php', {tag_name: tag_name },function(response, status, xhr){
$(".dashboardtable").html(response);
$("#keyword").val("");
$("#keyword").attr("placeholder", "Search Tags...");
});
});
What should happen is when the user begins typing it begins pulling suggestions out of the database and when they click the search button it loads the results into a div using AJAX. I noticed it wasn't working and I decided I'd try a simple test:
$('#srchBtn').click(function(){
console.log('hit');
})
But nothing appeared in the console. I then tried
console.log($('#srchBtn')); and It does seem to be getting a reference to my dom object, it just isn't firing the click event for some reason.
I've got the following scripts at the top of the page:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/jquery-ui.min.js"></script>
<script src="../scripts/auto-complete/tag_list_search.js"></script>
and I am getting no errors in my console. So what could possibly be the problem? Any help is much appreciated. Also this is my HTML:
<input type="text" id="keyword" placeholder="Search Tags..." size="33"/>
<input type="button" class="" id="srchBtn" value="Search"/>

Please wrap the code in jquery ready function...(in case this is not done)
$(function(){ // jquery ready function
$("#keyword").autocomplete({
source:'../../pages/ajax/autocomplete/autocomplete_tags.php',
dataType: 'json',
minLength:1
});
//When you hit the search button load the new tags
$("#srchBtn").click(function(e){
e.preventDefault();
var tag_name = $('#keyword').val();
$(".dashboardtable").load('../../pages/ajax/autocomplete/search_tags.php', {tag_name: tag_name },function(response, status, xhr){
$(".dashboardtable").html(response);
$("#keyword").val("");
$("#keyword").attr("placeholder", "Search Tags...");
});
});
});

Related

How can I make an AJAX application similar to nodebb?

I am very new to ajax and am really struggling. My end goal is to make a forum software like nodebb. I've already made a php forum but decided not to use it because it just seemed old unlike faster looking forums like nodebb. What I'm trying to understand is how to make multiple tabs that display different information each but keep the same data for the header. I understand this is probably a very simple thing to do, but currently I am unable to accomplish this.
https://dogecraft.net is a great example of what I'm trying to accomplish.
If you click on the different tabs, it loads information in each one. I tried this but I had trouble with the url. When I reloaded, it simply just loaded my new file and that's not what I want.
(Yes, I am using a local jquery file. Jquery isn't the issue.)
I've tried w3schools but didn't find really helpful information
I've also tried many other websites.
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
$( "#one" ).click(function(){
$("#div1").load("/one/").hide().fadeIn();
window.history.pushState("object or string", "Title", "/one/");
});
});
$(document).ready(function(){
$( "#two" ).click(function(){
$("#div1").load("two.html").hide().fadeIn();
});
});
</script>
</head>
<body>
<button id='one'>Page one</button> <button id='two'>Page two</button>
<h2>This text never changes :)</h2>
<div id="div1"></div>
</body>
</html>
I would like to have a homepage 'index.html/php'
I need a button to load one page of content (one.html/php) and then another button that loads another page of content (two.html/php).
On refresh, I would like it to keep the same content that was on the homepage including the buttons in the header.
You could make an Ajax call to your html/php to retrieve the html code and then inject the content on your div. Here is an example:
$(document).ready(function() {
$("#one").click(function() {
$.ajax({
url : 'http://myserver.com/myhtmlpage.html',
success : function(html) {
$("#div1").html(html);
}
});
});
$("#two").click(function() {
$.ajax({
url : 'http://myserver.com/myphppage.php',
success : function(html) {
$("#div1").html(html);
}
});
});
});
When you click a button, an ajax call is made, and if succesful, the success function will be called. The first parameter has the html code of the webpage you requested. Then you can use the html function of jQuery you can inject it on your div.
A couple of tips:
You might want to use only one onready function, no need to declare it several times
You might consider returning a json object with the data instead of a php page. This will be useful later on if you consider using a framework such as Angular or Vue. If you can generate a JSON file on your php such as this:
{
"name": "John"
}
Then you could do something like this:
$("#two").click(function() {
$.getJSON({
url : 'http://http://myserver.com/myphppagethatservesjson.php',
success : function(json) {
$("#div1").html("<h1>My name is " + json.name + "</h1>");
}
});
});
Then it will render "My name is John".
This could be improved a lot,but I hope it could help you a bit.

jquery using autocompete. I'm wanting to add async to remove render-blocking

Hi am wanting to speed up the page using async to remove the render-blocking.
What is happening; when I put async in the script before jquery file it the auto complete stops working?
If I don't use async its then rending blocking.
Any ideas has to how to get both working?
Or
can explain why this may be happening?
It is for a form postcode selection
site
<script async src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script><!----NEED for postcode--->
<script >
//custom select box
$("#swSearch").autocomplete({
minLength: 1,
source: function(req, add){
$.ajax({
url: 'http://www.vestedutility.com.au/WMS/index.php/welcome/sw_search', //Controller where search is performed
dataType: 'json',
type: 'POST',
data: req,
success: function(data){
if(data.response =='true'){
add(data.message);
}
}
});
}
});
</script>
I visited the page you have provided and there are a lot of errors on the page :
First remove all async from <script> tags.
Then put your autocomplete code inside this
$(function() {
//your autocomplete code here
}
This should solve your issue as autocomplete itself is using jquery.
Other than that your html document is starting with <head>.
There is no body tag also.
You are downloading bootstrap.min.js 3 times.
Your own code depends on jquery, so async won't work there. Your code would be executed before jquery is even loaded. The developer console always gives you great error stack traces.
On the link you posted it seems like you forgot to include the autocomplete script.

jquery select2 after ajax not working anymore

I have a simple select2 control on my site placed in a div. When the site loads, everything works fine. However, if the html content of the div "simpleDiv", where the Select2 is placed, is loaded with Ajax, the Select2 is not showing the results anymore when triggered.
That means, in this case the Select2 data is got from the Server, but never shown in the Select2.
And this all happens just when the "simpleDiv" html content is loaded with Ajax. Otherwise, everything works fine.
Can anyone help, please?
<div id='simpleDiv'>
<input type="hidden" id="MedikamentID" name="MedikamentID" class="fixed-width4" />
</div>
<script>
$('#MedikamentID').select2({
placeholder: "[Medikament]",
allowClear: true,
minimumInputLength: 2,
ajax: {
url: "/Medikament/List",
dataType: 'json',
data: function (term, page) {
return {
query: term
};
},
results: function (data, page) {
return { results: data };
}
}
});
</script>
Whenever you change things using .html() or .innerHTML, essentially, the DOM gets reconstructed and all the javascript events and properties attached to them is lost. But the fix is simple. Just call Select 2 again after you finished inserting the new HTML. So something like:
$.ajax("example.php").done(function(data){
$("#simpleDiv").html(data)
$("#MedikamentID").select2(...) //rebuild select2
})
I attached a jsfiddle to illustrate this:
http://jsfiddle.net/HT3rP/1/
If I got your question correct, you may be having a similar problem related to this stackoverflow problem
You could try something like this
$(document).on("ready", "#MedikamentID", function () {
$(this).select2({
// options go here
});
});

jquery popup effect 'onclick' submit button (WITHDRAWN)

Since I am a beginner, I have a beginner's question.
Using the famous fancyBox plugin. It is called in the head like so:
$(document).ready(function() {
$(".fancybox").fancybox();
});
Normally the script is attached by adding the class-name:
<a class="fancybox fancybox.iframe">...</a>
My present difficulty arises because I would like to run the fancyBox pop-up after the user submits a form:
<form action="http://maps.google.com/maps" method="get">
...(google API stuff etc, etc)...
<input type="submit" value="...">
My research to this point has led me to conclude that I probably have to use onsubmit or onclick within the
<input type="submit">
However, my experimentation has proven a futile effort.
Any help would be greatly appreciated.
========================================
UPDATE: (1/7/2013)
I am withdrawing my question because I have apparently wandered into subject matter that is slightly above my head at the moment. I choose not to delete the question in case someone in the future may find something of some use here. Thank you for your help everyone.
My reason: it appears that Google directions does not permit display in <iframe>. That being considered, configuring a workaround for fancyBox would be far too complex. I am abandoning the fancyBox and have gone with plain old Javascript:
as shown here
Post the form using $.ajax gives you the greatest control. You can then control the success and error conditions from the client side.
To do this you will either need to catch the submit event:
$('#form').submit(function() {
ajaxUpdate();
return false;
});
Then create a function:
function ajaxUpdate(){
var formSerial = $('#form').serialize();
$.ajax({
url: '<url to post to>',
dataType: "text",
type: "POST",
data: formSerial,
success: function(text) {
$(".fancybox").fancybox();
},
error: function(text) {
alert('error in posting');
}
});
}
You can then do what you like in the success and error blocks.
To load a window you could add the following to your function:
if(confirm("Do you want to open the directions?")){
$.fancybox({
'titleShow': false,
'width': 370,
'height': 300,
'href': <URL>,
'type': 'iframe'
});
}
Using jquery submit buttoin it can be possible :
$('#target').submit(function() {
$(".fancybox").fancybox();
return false;
});
After fancy box 'ok' button click submit the form ..
Hope this idea will helpfull.

Why does my JS/JQuery code only work in a web browser's console?

The $(element).scroll(function(){}); function isn't working for me when I put it into a js file but when I enter it into the console (just the scroll func), it works just fine.
I'm trying to do a scrolling pagination.
I've looked through my other js files and the only thing that I think could be conflicting is another one of the files has a $(document).ready(function(){}) but I'm pretty sure that's not the problem. I'm also using Dropkick to make pretty dropdowns but I doubt that's it either.
Here's the code, almost verbatim. It's basic for now until I can figure out how to get it to load.
$('#main').scroll(function(){
if(($('#main').prop('scrollHeight'))==
($('#main').scrollTop()+$(document).height()-10)){
//^there's a strange 10px empty space that needs to be accounted for
$('#loading').show();
$('#main').css('overflow','hidden');
addMore();
}
});
$(document).ready(function(){
addMore();
});
addmore.counter=0;
function addMore(){
$.ajax({
async: 'true',
url: 'http://mywebsite.com/bc/get',
type: 'post',
data: ({'offset':(addmore.counter)}),
success: function(data) {
$('#scrollingpagination').append(data);
$('#loading').hide();
$('#main').css('overflow','scroll');
addmore.counter++;
}
});
}
And here's the HTML (not verbatim, but same idea)
<!--I'm only including the "main" div that shows the content.-->
<div id='main'>
<div id='scrollingpagination'></div>
<div id='loading'></div>
</div>
Thanks guys, I really appreciate it!
try keeping
$('#main').scroll(function(){
......
})
inside document.ready. i think it was called before the dom was ready

Categories