jQuery load issue. Don't know how to approach this AJAX call - javascript

$("[littleBox]").load("ajax.php?eid="+$(this).attr("littlebox"));
the $(this).attr("little box") portion of the code returns undefined.
I'm trying to get the individual attribute of the initial $("[littleBox]").
this particular line of code is called as the soon as the document is ready.
when I put predefined values, such as
$("[littleBox]").load("ajax.php?eid=1");
It works as expected. Unfortunately, I need it to load specific content based on that element's attribute. Any idea how to make this work?

Loop through all items with proper this:
$("[littleBox]").each(function() {
var $this = $(this)
$this.load("ajax.php?eid="+ $this.attr("littlebox"));
});

this will not refer to $("[littleBox]") in that context, you'll have to repeat the selector - or select the element already and re-use it:
var $box = $("[littleBox]");
$box.load("ajax.php?eid=" + $box.attr("littlebox"));

post yout html that cotnain attr "little box" in it.
is it like
<a attr="little box" id="test">test<a/>
then it work like
$('#test').click(function(){
alert($(this).attr('little box'));
});

Related

Document.querySelector returns a NULL value - script is at bottom of page

I am trying to get the patientNumber (ClinicA100-PF-TR1-P1) using querySelector. I keep getting a NULL value. The patientNumber is at the top of the page and the script is at the bottom. Even after the page is loaded, I click a button that runs the function and it still returns a NULL value.
Here is a screenshot of the selectors (https://recordit.co/IypXuuXib0)
<script type="text/javascript">
function getPatientNumber(){
var patientNumber = document.querySelector("patientNumber");
console.log(patientNumber);
console.log("hello");
return patientNumber;
}
var patientNumber = getPatientNumber();
console.log(patientNumber);
_kmq.push(['identify', patientNumber]);
</script>
Thank you for any help you can provide.
ADDITIONAL HTML INFORMATION:
I am using Caspio (database management software) to create this HTML code. I don't know if that may be the cause of the issue. Here is the HTML CODE.
<p class="sponsorName" id="sponsorNameID">[#authfield:User_List_Sponsor_Name]</p>
<p class="clinicNumber" id="clinicNumberID">[#authfield:User_List_Site_Number]</p>
<p class="protocolNumber" id="protocolNumberID">[#authfield:User_List_Protocol_Number]</p>
<p class="patientNumber" id="patientNumberID">[#authfield:User_List_Patient_Number]</p>
You are missing a dot.
var patientNumberNode = document.querySelector(".patientNumber");
var patientNumber = patientNumberNode.innerText;
if you select the item with class".", if you select with id, you should use"#".
var patientNumber = document.querySelector(".patientNumber"); // class select
var patientNumber = document.querySelector("#patientNumber"); // id select
Your selector is incorrect. It should be
var patientNumber = document.querySelector(".patientNumber");
Why is it failing:
When you use patientNumber as the selector, JavaScript looks for an element with a name of patientNumber. Since that's not the case, and you are looking for an element with a class of patientNumber, you need to use the . notation.
Addon Suggestion (can be ignored):
Since you are also using IDs, consider using document.getElementById() as it is faster than using document.querySelector().
Note that if you use document.getElementById(), your .patientNumber selector won't work. You need to write it as
document.getElementById('patientNumberID');
//ID based on the screenshot of the DOM you've shared
While the code is at the bottom of the page, and the element is at the top, it is not loaded asynchronously as it comes from a third party database. i put a delay in the getPatientNumber() and it works now.

Cannot use elements that were created with append method

I have an AJAX call that when it's done i have this code:
$(".results").append('<div class="horizontal result_element"><div class="result_photo"></div><div id="'+user_id+'" class="result_data">'+user_name+'</div></div>');
Later i want something to happen when i click on the class result_element:
$(".result_element").click(function(){
var url = "profile.php?user_id="+$(this).children("[class='result_data']").attr("id");
$(location).attr('href',url);
});
But it doesn't work and my thought is that jQuery create the html elements but doesn't appends them to the DOM.Any idea on how can i make this work with that method?
I assume that you mean with 'later' the time in the user-sight an not the time in the script.
The problem is that the jQuery doesn't know about the element if you create it after explaining that jQuery shell do x on event y. So if you set the click-event in $(document).ready(function(){*here*}) and you create an element afterwards (after the document-ready was fired), jQuery doesn't know these fresh elements.
So to solve your problem, try to add the event after you created the element (creation not equal to appending!):
// created the element
var newElement = $('<div class="horizontal result_element"><div class="result_photo"></div><div id="'+ user_id +'" class="result_data">'+ user_name +'</div></div>');
// now set the event
newElement.click(function () {
var url = "profile.php?user_id="+ $(this).children("[class='result_data']").attr("id");
$(location).attr('href',url);
})
// now append it
newElement.appendTo($(".results"))
// or: $(".results").append(newElement)
And you can reorder the two last steps, so you first append it and then set the event, thats not the point. The point is, that you create the element first and then set the event.
I believe, click is not working on result_element class which is added dynamically. Try with following code snippet.
$(document).on("click",".result_element", function(){
var url = "profile.php?user_id="+$(this).children("[class='result_data']").attr("id");
$(location).attr('href',url);
});

Finding $(this) after a function

So here's my problem: I'm using a function and I need the function to be specific to each tr with the class "middleone". It's supposed to change the insides of a div inside of the the tr with the class "middleone". But it's not working!
I know the recursive portion of it is working, and the "navigation" should be spot on, because even when i'm using just $(this) it doesn't do anything. When using document.getElementById it works fine but of course that only targets the first div and the full version of the code has to "Go here, pull from here, put it here, go to the next area, pull from here.. etc" Here's the testing code.
$('.middleone').each(function() {
var tripleeagain = $(this).find('div')
tripleeagain.innerHTML = "$";
});
Thanks for any help
tripleeagain is a jquery object collection upon which you should use html() instead of innerHTML
Basically you could just write:
$('.middleone').find('div').html("$");
If you are doing specific stuff inside the loop then:
$('.middleone').each(function() {
//Some specific logic
var tripleeagain = $(this).find('div').html("$");
});
The problem is you are trying to access native API from a jQuery object.
var tripleeagain = $(this).find('div');// this will return a jQuery object
So you should use the jQuery API for setting the html contents
tripleeagain.html("$");
jQuery html API documentaion

Add multiple elements to a single var and detect if any of those are clicked?

I have a page that can have one of three possible elements. I would like to assign whatever element exists to a var and then check if the var is clicked.
I tried using the add(), but it has confused me:
var testingVar = $('#element-one').find('.object').add('#element-two').find('.object').add('#element-three').find('.object');
$(testingVar ).click(function() {
alert('works');
});
It seems to me that the add() overwrites the previous add()? if I am on a page that has #element-three, it works, if on a page with element-one or element-two, it doesn't. If I change the var to
var testingVar = $('#element-one').find('.object');
Then a page with element-one works.
Can someone help me understand how to use the add() properly in this case?
Thanks
I think what you're looking for is this:
$('#element-one .object').add('#element-two .object').add('#element-three .object');
.find() returns a new jquery object.
However, I think this would be easier in this case:
$('#element-one .object, #element-two .object, #element-three .object');
Or even easier, if you can change markup, is to give each element you're currently selecting by id a common class, and do this:
$('.common-class .object')

JQuery Copy text & paste into textarea

I've created a javascript function that will take a hidden span, copy the text within that span and insert it into a single textarea tag on a website. I've written a function in JavaScript that does this (well, kinda, only after a few clicks), but I know there's a better way - any thoughts? The behavior is similar to a Retweet for twitter, but using sections of a post on a blog instead. Oh, and I'm also calling out to jquery in the header.
<script type="text/javascript">
function repost_submit(postID) {
$("#repost-" + postID).click(function(){
$("#cat_post_box").empty();
var str = $("span#repost_msg-" + postID).text();
$("#cat_post_box").text(str);
});
}
</script>
Based on the comment in your question, I am assuming you have something like this in your HTML:
copy post
And I am also assuming that because you are passing a post ID there can be more than one per page.
Part of the beauty of jQuery is that you can do really cool stuff to sets of elements without having to use inline Javascript events. These are considered a bad practice nowadays, as it is best to separate Javascript from your presentation code.
The proper way, then, would be to do something like this:
<a href="#" id='copy-5' class='copy_link'>copy post</a>
And then you can have many more that look similar:
<a href="#" id='copy-5' class='copy_link'>copy post</a>
<a href="#" id='copy-6' class='copy_link'>copy post</a>
<a href="#" id='copy-7' class='copy_link'>copy post</a>
Finally, you can write code with jQuery to do something like this:
$(function() { // wait for the DOM to be ready
$('a.copy_link').click(function() { // whenever a copy link is clicked...
var id = this.id.split('-').pop(); // get the id of the post
var str = $('#repost_msg-' + id); // span not required, since it is an ID lookup
$('#cat_post_box').val(str); // empty not required, and val() is the proper way to change the value of an input element (even textareas)
return false;
});
});
This is the best way to do it even if there is only one post in the page. Part of the problem with your code is that on the first click it BINDS the function, and in the subsequent clicks is when it finally gets called. You could go for a quick and dirty fix by changing that around to just be in document.ready.
$("#repost-" + postID).click(function(){
$("#cat_post_box").val(''); // Instead of empty() - because empty remove all children from a element.
$("#cat_post_box").text($("#repost_msg-" + postID).text());//span isn't required because you have and id. so the selector is as efficient as it can be.
});
And wrap everything in a $(document).ready(function(){ /Insert the code here/ }) so that it will bind to $("#repost-" + postID) button or link when the DOM is loaded.
I had a problem with Paolo's example when I clicked on the link the text that appeared in #cat_post_box was "object Object". Once I added ".text()" to the end of that statement I worked.
var str = $('#repost_msg-' + id).text();
Thanks for you example Paolo!

Categories