I have a php employee directory website that lists all our employees in a table (connected to mysql), and you are able to click each employee to open up their details in another div.
$('.emptab').click(function(event) {
var status = $(this).attr('id');
$("#empview").load("employee.php", {'data': datastring, 'current': status});
});
I originally had the above code, but needed to be able to attach events to dynamic elements, so I changed to the following code:
$('tbody').on('click', 'tr.emptab', function() {
var status = $(this).attr('id');
$("#employeedetails").load("employee.php", {'data': datastring, 'current': status});
});
I did it that way as I read in another question (In jQuery, how to attach events to dynamic html elements?) that you can use that format to attach events to dynamic elements. Just to clarify, this code continues to work with the initial page, but fails after the search filter is used.
My dynamic elements comes from a filter/search function I have that will change the list of employees based on a search text box which changes the list of employees based on a filter.php document I created.
$('#search').on('input propertychange paste', function() {
var string = $('#search').val();
$("#employeelist").load("filter.php", {'data': datastring, 'search': string});
});
However, when those elements are created from that php file, I am unable to access the elements through my jquery, I'm not sure what I'm doing wrong. There were about 4 other questions I saw where the answer was to use the jquery on function, which I've tried with no success.
Thanks for your time.
You can use following code for this
$(document).on('click', '.emptab', function() {
var status = $(this).attr('id');
$("#employeedetails").load("employee.php", {'data': datastring, 'current': status});
});
Related
My code below was used to retrieve records from a loop using JavaScript. Everything works fine. Each of the records button has a unique id that when click
should alert users_id in a Bootstrap Modal popup.
The problem is that the looped button that contains users_id is not alerting anything when each button is clicked.
Below is the code for retrieving records in JavaScript along with Bootstrap modal button:
<script>
$(document).ready(function () {
$.post('users.php', function(response){
$.each(JSON.parse(response).items, function(i,v) {
$('.userslist').append('<span>'+v.id+'</span> Profile');
});
});
});
</script>
Below is the code for posting the users_id and then alert it:
<script>
$(document).ready(function(){
$(".modalLink").click(function() {
var id = $(this).attr("id");
alert(id);
var dataString = 'id='+ id;
$.ajax({
type: "POST",
url: "ajax_modal.php",
data: dataString,
cache: false,
success: function(data) {
$("#rmm").html(data);
}
});
});
});
</script>
but if I take the Modal button outside the retrieve records in a javascript loop
it will alert users_id and everything will work fine as in code below
Profile
Can someone help me make each of the JavaScript looped button to post its own unique users_id and then alert it in a Bootstrap modal popup. I have attached a screen shot of the result obtained from the JavaScript loop.
Thanks
If I understand your question properly;
Try changing
$(".modalLink").click(function() {
to
$(document).on('click', '.modalLink', function() {
Without seeing the rest of your code or a working fiddle, I suspect your content is dynamic and JQ cannot bind the click handler, simply because there is no content to bind to. this answer does a good job of explaining the difference between .on and .click.
If you get the expected result, I would drop the document selector and use the closest parent static element.
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.
I have rows generated in a table dynamically. I am getting the data for the dynamic rows by ajax calls. This loading of dynamic rows is happening at the time of page load. I am not able to access this dynamic data using Jquery. To be specific, I need to iterate through all the rows in the table.Is there a good way to accomplish this?
Also There is no event like button click to load the data. The data is loaded at the time of page loading.
$.ajax({
type: "POST",
url: serviceUrl,
contentType: "application/json",
data: ko.toJSON(getevent),
dataType: "json",
success: function (data) {
$(".childrenrow").each(function(){ //.childrenrow are the dynamically generate table rows
alert("Here"); //This part is not getting exeucuted
//I am planning to check for the the existence of data.children in each .childrenrow once the loop is entered
});
},
error: function () {
}
});
Try this,
As you said your data will be loaded while page load then you can access those data from following code:
$(document).ready(function(){
$("table tr td").each(function(){
alert($(this).text());
});
});
This will iterate through each td of each tr and .text() will return the data inside respective td. You can also use $("table tr").each(function(){ , which will get the data from each tr.
Working js code
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);
}
});
});
I'm using jquery and uploadify to upload photos to server. After uploading photos they are added to a div container using ajax. Everything works great except DELETE button. All delete buttons work on page load but those added via ajax don't work. I suppose that's because I defined function that enables image deletion and didn't use 'classic' way of deleting (form deletion):
// Delete photo
$(".blog_slike .delete_slika").click(function() {
var commentContainer = $(this).parent().parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
type: "POST",
url: "./include/ajax-edit/delete.php?polje=blog_slika",
data: string,
cache: false,
success: function(){
commentContainer.fadeOut("slow");
$('#load').fadeOut();
}
});
return false;
});
Any idea how to make button work after it's added to html code using append() function?
One more thing... to add photos to tinymce editor I use this function:
Ubaci sve slike u blog
...which was also added on page load. How can I add content to place where is $slike_u_sadrzaj located and how to delete it?
Thanks,
Ile
You need the jquery live method.
Added in jQuery 1.3: Binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events.
jQuery documentation
Sample code:
$(".blog_slike .delete_slika").live('click',function() {