Using AJAX I have retrieved Json information but, during the function, I cannot display the text in the relevant Div.
The code works right to the bottom, as I can see using the console, but even if I put placeholder text in the div "place", the placeholder text stays the same right to the end of the function.
$.each(data, function(i,item){
if(i===0){
var placeHTML='<h2>'+item.name+'</h2>' +
'<p>where you can get <br>' +
'a pint of <em>'+item.pint+'</em> for only<br>' +
'<span>£'+item.cost+'!</span></p>';
window.localStorage.setItem("placeName", item.name);
window.localStorage.setItem("placeLoc1", item.location);
window.localStorage.setItem("placeLoc2", item.location2);
window.localStorage.setItem("placeEmail", item.email);
window.localStorage.setItem("placeNumber", item.number);
console.log("Data saved");
document.getElementById("place").innerHtml = placeHTML;
console.log("Data placed:");
console.log(placeHTML);
$("#loadText").fadeOut();
$('#place').fadeIn();
return false;
}
});
I have also tried replacing document.getElementById("place").innerHTML = foo to $("#place").val(foo) with no luck.
The div has the values id="place" and class="place".
document.getElementById("place").innerHtml = placeHTML;
should be
document.getElementById("place").innerHTML = placeHTML;
to do it with jQuery
$("#place").html(placeHTML)
val will set the value of something like an input field, to change the inner HTML with jQuery you want to use the html() function
Try this:
$("#place").html(foo)
Or
$("#place").text(foo)
Also, it is not innerHtml, it should be innerHTML here:
Change it to:
document.getElementById("place").innerHTML = placeHTML;
This line is wrong,
document.getElementById("place").innerHtml = placeHTML;
Change innerHtml to innerHTML (HTML should be caps),
document.getElementById("place").innerHTML = placeHTML;
May be try to use
$("#place").html(placeHTML);
Related
New to javascript, how do I fix this problem I'm having?
I want to add an a tag to a string variable that i'm creating using a function.
The whole message (eg - "Your tutor is JOHN DOE. Contact them here: CONTACT FORM") Is added to the DOM with another function (which works).
When I run the script it outputs to the browser but the second part (makeLink()) doesnt work.
This is what I get: "Your tutor is JOHN DOE. Contact them here http://www.example.com" - Instead of the URL I want word CONTACT FORM which should be a link.
How do I do this?
I tried using link() Method, which also didnt work and had similar output.
I'll only include the relevant script below, the rest works fine...
function makeMessage(){
for(i in msgArr){
stringMSG += msgArr[i];
//do not add a comma after last item
if(i < msgArr.length - 1){
stringMSG += ', ';
}
}
var highRiskmsg = "Your tutor is " + stringMSG + ". Contact them here" + makeLink();
return highRiskmsg;
}
function makeLink() {
var contactLink = document.createElement("a");//create <a> tag
contactLink.setAttribute("id", "linkC");//set id att for <a> tag
contactLink.setAttribute("href", "http://www.example.com/contact.php");//set id att for <a> tag
var contactLinkTxt = document.createTextNode("CONTACT FORM");//new text node
contactLink.appendChild(contactLinkTxt);//append text as child of <a> tag
return contactLink;
}
It seems the problem is you are returning a DOM element from your makeLink() function, and this won't concat with the string as you expect.
You need to return a valid HTML string instead, such as: <a id=".." href="..">..</a>
The quickest way to fix your code would be just to change the return for the makeLink() function as follows:
return contactLink.outerHTML;
Using outerHTML will return the HTML string for the element, rather than the element itself.
Here is a working example
As an alternative to musefan's answer, you can return an element that contains both the message and link as nodes, instead of text.
function makeMessage(){
var highRiskmsg = "Your tutor is " + msgArr.join(',') + ". Contact them here";
var span = document.createElement('span');
span.appendChild(document.createTextNode(highRiskmsg));
span.appendChild(makeLink());
return span;
}
Fiddle
Sorry for the noobish question but, I am trying to build a form summary that will populate a div (immediately) with all of the fields being used. Here is a small sample of the field: Fiddle
For some reason the JS is not working as I would expect it to, can anyone point out what I am doing wrong?
For example, I would like it to output: "AND name: john EXCEPT number 222".
I would also like to be able click on a result to remove it, and clear the field. Thank you
$(".allS").change(function () {
if ($(this).next('.textArea').not(':empty'))
// varible to hold string
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("#text_here").text(str);
}).change();
$('.textArea').change(function(){
var $inputs = $('form#form :input[type="text"]'),
result = "";
$inputs.each(function(){
// access the individual input as jQuery object via $(this)
result += $(this).val()+"<br>";
});
// store result in some div
$('div#text_here').text(result);
}).change();
There were many mistakes in your code. I simplified it to a very short code that only does what's needed to get the output you requested. Here's the working fiddle.
$(".allS, .textArea").change(function () {
var str = '';
if ($('#name').val().length > 0 && $('#number').val().length > 0)
var str = $('#nameMod>option:selected').text() + ' name:' + $('#name').val() + ' ' + $('#numberMod>option:selected').text() + ' number ' + $('#number').val();
$("#text_here").html(str);
});
Basically, what this does is attach a change event handler to both classes (.alls, .textArea), and when the event is triggered, both input fields are tested for any content. If this test passes, a string is composed out of all the relevant values, and the div content is set. If the test failed (no content), the str variable contains an empty string and the div is cleared.
Just glancing at the code, the selector 'form#form :input[type="text"]' looks wrong. For starters, input is not a pseudoclass. Also, attribute matching shouldn't have the quotes.
This may or may not be what you want (I think it is, from looking at your html):
'form#form input[type=text]'
Also your <br>'s are not working because you called text(). call html() instead.
I am trying to get a value from a hidden field. I am using the code
function foo(){
alert($('#idhere').val());
}
the answer i am getting is only the first word of that sentence.
the value is a large sentence I am using the above code inside a function foo and this function foo is called inside a append function inside a ajax call.
$.each(data, function(i, item) {
$("#news").append('<a onclick="foo()">xxx</a><input type="hidden" id="idhere" value="item[0]"');
}
Why am i getting only a single word as alert.
Am i doing it wrong
Well, where is "#idhere"?
There is no element that has this id assigned!
You have not given id idhere to element.
Try:
$("#news").append('<a onclick="foo()">xxx</a><input type="hidden" value="item[0]" id="idhere"');
i think you miss the id in hidden field
$("#news").append('<a onclick="foo()">xxx</a><input type="hidden" value="item[0]" id="idhere"');
Id should be unique! You use $.each, that means you probably will create many elements with the same id. That's bad.
$.each(data, function(i, item) {
$("#news").append('<a onclick="foo()">xxx</a><input type="hidden" id="idhere' + i + '" value="item[0]"');
}
Use:
function foo(){
alert($('#idhere0').val());
}
Or:
var vals = $.map($('input[type="hidden"]'), function(el) {
return $(el).val();
});
alert(vals.join('\n'));
I am new to javascript and jquery I am using 'append' function to append 'a' tag in to div which is working fine
$('#div1').append('<a href=./1.php>'+test+'</a>');
var test= "<script>";
test+="alert("hello1")";
test+="<";
test+="/script>";
this code shows hello1
my problem is that I want to pass variable with test like this
$('#div1').append('<a href=./1.php>'+test(variable)+'</a>');
var test= "<script>";
test+="alert(variable)";
test+="<";
test+="/script>";
Is there anyway or am I doing it wrong?
thanks in advance
You need to use javascript functions that returns a string;
function test(variable) {
return "<script> alert('" + variable + "'); </" + "script>";
}
you probably want to do something on user click:
$('#div1').append('link text').click(function() {
alert("hello1");
});
in this code i am trying to get the alert value to the element.
brief:
my ajax code checks the database values and gets the new values from database and
displays the fetched values in alert. but i am not able to put that alert values into
element...
How can i do this?
Code:
<script>
$(document).ready(function(){
$("#refresh").click(function(){
var fileId=id;
var rowNum = $(this).parent().parent().index();;
$.ajax({
type:"post",
url:"checkStatusAndNumRecs",
data:{fileId:fileId},
success:function(data)
{
setTimeout(alert(data), 2000);
var allTds = $("#rtable tr:eq('"+rowNum+"')").find('td');
$(allTds)[4].html(data[0]);
$(allTds)[3].html(data[1]);
document.getElementById("#div1").innerHTML=data;
},
error:function(data)
{
document.getElementById("#div1").innerHTML="It was a failure !!!";
}
});
});
});
</script>
HTML code:
<td><div id="div1"><s:property value="%{#m.status}" /></div></td>
In alert(data) i am getting the value.
but when i put same value like this
document.getElementById("#div1").innerHTML=data;
it is not applying the value to element
you don't need # using javascript's getElementById
try this
document.getElementById("div1").innerHTML=data; //notice no `#` in front of div1
or
using jquery that should be
$('#div1').html(data);
try
document.getElementById("div1").innerHTML=data[0];
document.getElementById("div2").innerHTML=data[1];
or
$('#div1').html(data[0]);
$('#div2').html(data[1]);
Pass the actual data inside the object to the HTML element, not the object itself.