How to bind JavaScript result to a div on my page? - javascript

i have a java script file that it's output is a table with some information.
i want to show this result in one of my DIVs in my page but the result of function,placed at top of my page's Header!
What can i do to fix this?
this is end of my java script file ,in fact this is its output
' document.write("")
document.write(" اوقات شرعی کلیه شهر ها ")
document.write("")
document.write(" ")
document.write(" اذان صبح طلوع خورشید اذان ظهر غروب خورشید اذان مغرب")
document.write(" اوقات به افق : انتخاب شهراراکاردبیلارومیهاصفهاناهوازایلامبجنورد بندرعباسبوشهربیرجندتبریزتهرانخرم آبادرشتزاهدانزنجانساریسمنانسنندجشهرکردشیرازقزوینقمکرمان کرمانشاهگرگانمشهدهمدانیاسوجیزد ")
document.write("") '' and this is its call at the and of my master page '
$(document).ready(function ogh() {
var CurrentDate = new Date();
var JAT = 1;
function pz() { };
init(); document.getElementById("cities").selectedIndex = 12;
coord(); main();
});
$(document).ready(function () {
$("#oghatSharii").append(ogh());
});
</script>
</form>
'
if you could't understand top of my code,,its output is a table

You can set the HTML of the div using jquery in the ready event like follows:
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
....
<script type="text/javascript">
$(document).ready(function () {
$("#myDiv").append(pz());
});
function pz() {
// do here something useful and return the text you want to add to the div
return "Hello there =) !!!";
};
</script>
<div id="myDiv"></div>
Don't forget to install jquery:
https://nuget.org/packages/jQuery

i use this
function ogh()
{
var CurrentDate = new Date();
var JAT = 1;
function pz() { };
init(); document.getElementById("cities").selectedIndex = 12;
coord(); main();
}
$(document).ready(function () {
$("#oghatSharii").append(ogh());
});
but i got an error : one of my functions could't access to oits data

Some steps
Move your JavaScript code at the bottom of the page.
Make use of innerHTML (basic JavaScript) or html() (jQuery) to add so.

Related

Reusing Javascript code without repasting it again and again

I have the below code, which looks for the text "UID" and changes it to "UID *"
On my page, there are other terms such as "description", "score" and so on. I would also like to append * to these as well - is there a tidy way to get the below code to edit those as well? Only way I know is to repeat this code block again and again?
<script type="text/javascript">
//Mark UID as Mandatory
var CFN = "UID";
$(document).ready(ExecuteOrDelayUntilScriptLoaded(MainFunction, "sp.js"));
function MainFunction() {
Mandatory();
}
function Mandatory(){
$(".ms-accentText").each(function() {
var text = $(this).text();
$(this).text(text.replace(CFN, 'UID *'));
});
}
</script>
EDIT. I tried the below reply, but this didn't work for me, I have got this code now, but again, doesn't seem to work (its trying to add a * onto "UID" and "Description" where found using a multi variable;
<script type="text/javascript">
//Mark UID as Mandatory
var MandatoryCFs = ["UID", "Description"];
$(document).ready(ExecuteOrDelayUntilScriptLoaded(MainFunction, "sp.js"));
function MainFunction() {
Mandatory();
}
function Mandatory(){
$(".ms-accentText").each(function() {
var text = $(this).text();
$(this).text(text.append(MandatoryCFs, ' *'));
});
}
</script>
Replace multiple strings by using list of| Regex
//Mark UID as Mandatory
var MandatoryCFs = ["UID", "Description"];
$(document).ready(ExecuteOrDelayUntilScriptLoaded(MainFunction, "sp.js"));
function MainFunction() {
Mandatory();
}
function Mandatory(){
$(".ms-accentText").each(function() {
var text = $(this).text();
$(this).text(text.replace(new RegExp(MandatoryCFs.join('|'),'g'), '$& *'));
});
}
or like this if you don't need to the replaced strings to be dynamic:
text.replace(/UID|Description/g, '$& *')

Having trouble appending javascript into my html

OK,so I am trying to pull some data from an api. The problem that I have run into is that I am able to find out the information that I am looking for, but am having trouble getting that information out of the console and onto my main index.html page.
Here is my JS code
var form = $('#search');
var input = $('#search-keyword');
var results = $('#results');
$(document).ready(function() {
$("#myBtn").on('click', function() {
var symbol = $("#search-keyword").val();
$.getJSON("http://dev.markitondemand.com/Api/v2/quote/jsonp?symbol=" + symbol + "&callback=?", function(info) {
console.log(info);
});
});
});
Here is my html code
<div id="search">
<h1>API Test</h1>
<input type="search" id="search-keyword">
<button id="myBtn">Try it</button>
</div>
<div id="results"></div>
By doing this, I am able to get pretty much what I am looking for. However I cannot get the data from the console to the actual page.
I have tried appendChild
var bob = document.getElementById(results);
var content = document.createTextNode(info);
bob.appendChild(info);
I have tried innerHTML
var theDiv = document.getElementById(results);
theDiv.innerHTML += info;
..and I have tried .append()
$('#myBtn').click(function() {
$(results).append(info)
})
I'm out of ideas. I realize that I probably have a small problem somewhere else that I am not seeing that is probably the root of this. Much thanks to anyone who can help me with this issue.
"results" needs to be in quotes with regular javascript and for jquery you have already decalred the results variable.
var theDiv = document.getElementById("results");
theDiv.innerHTML += info;
$('#myBtn').click(function(){
results.append(info)
})
Also since you are declaring results outside of your document ready call you have to make sure you html comes before the javascript.
<script>
var form = $('#search');
var input = $('#search-keyword');
var results = $('#results');
$(document).ready(function() {
$("#myBtn").on('click', function() {
var symbol = $("#search-keyword").val();
var resultedData = $.getJSON("http://dev.markitondemand.com/Api/v2/quote/jsonp?symbol=" + symbol + "&callback=?", function(info) {
return info;
});
var resultDiv = document.getElementById("results");
resultDiv.innerHTML += resultedData;
});
});
</script>

Adding HTML to page based on conditional logic in JavaScript or jQuery

I have a div in which I have to fill some data in. I have to render the HTML based on conditions and I am adding data to that div using jQuery. Can someone please tell me how I can add the condition based insertion of HTML on the page?
function AddData()
{
var data = "<div><h1>My data</h1>"
if(jsVariable){
<p>The JSVariable is present on page </p>
}
+"</div>"
$('.myDiv').after("<br/>"+data);
}
function AddData()
{
var data = "<div><h1>My data</h1>"
if(jsVariable){
data = data + "<p>The JSVariable is present on page </p>"
}
data = data + "</div>"
$('.myDiv').append("<br/>"+data);
}
function AddData(){
if(typeOf(jsVariable)!=="undefined"){
var data = "<div><h1>My data</h1>";
data += " <p>The JSVariable is present on page </p>";
data += "</div>";
$('.myDiv').after("<br/>"+data);
}
}
this should do the trick, but some element with a class of myDiv will need to already exist for this to work
<div class="myDiv"></div>
What exactly are you trying to do?
If you simply want to add some extra html content depending on the variable, you are almost done. You just need to add the <p> part to the data (data += "<p>...</p>").
If you're trying to add all of the html based on the variable, put the if statement around the $(".myDiv").after (which should be $(".myDiv").append btw).
You'r code is not valid.
Could you explain what do you want to do with
if(jsVariable){
<p>The JSVariable is present on page </p>
}
+"</div>"
If you want to add a html code at ending of a div, you should use
$('.myDiv').append('<p>Text text text text</p>');
simple usage:
<!DOCTYPE html>
<html>
<head>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function() {
$("p").click(function() {
var a = $("#div1").text();
if (a == "one") {
$("#div2").text(a);
}
});
});
</script>
</head>
<body>
<div id="div1">one</div>
<div id="div2"></div>
<p>click me</p>
</body>
</html>
function addData(to)
{
var h1 = $('<h1>').text('My Data');
var data = $('<div>').append(h1);
if (window.jsVariable) {
$('<p>').text('JS Variable is present on the page').appendTo(data);
}
to.append(data);
}
addData( $('.myDiv') );
if (condition) {
$('div#yourDivID').html('<p>The JSVariable is present on page </p>');
}
In addition to .html(which places the html inside your div), you can use other things like append, prepend etc. Check out jQuery's documentation on DOM Insertion.
Here is a JSFiddle http://jsfiddle.net/va4n8/
function addData() {
var newDiv = $('<div>');
newDiv.append($('<h1>').html('My data'));
if ('jsVariable' in window) {
newDiv.append($('<p>').html('The JSVariable is present on page'));
}
$('.mydiv').after($('<br>')).after(newDiv);
}

If / Else in DIV statement?

First, I am not a programmer anymore... It's been years since doing it and even then it was only VBA and old school HTML.
What I would like to do is to show an image on my site in place of another depending on it's "state". For example, the site is http://w2zxl.hevener.com/ , towards the bottom of the page is a script that loads a HAM radio logbook as well as my current status in nearly real time. If I am on the Air, it will show a small image that says "On Air" and then show what frequency I am on and the Mode I am working in. When I am off the air however, that little image just disappears and shows nothing.
What I would like to do is to create a small image to replace the "nothing". In other words, if I am Off Air, I would like to show an "Off Air" image instead of nothing at all.
Is there an If/Then/Else statement that can do this given the code I am providing below?
Code below:
<!-- HRDLOG.net script start --><center>
<div id="hrdlog-oa"> </div>
<div id="hrdlog">www.hrdlog.net</div>
<script type="text/javascript" language="javascript" src="http://www.hrdlog.net/hrdlog.js"></script>
<script type="text/javascript" language="javascript">// <![CDATA[
var ohrdlog = new HrdLog('W2ZXL');
setInterval('ohrdlog.LoadOnAir()', 5000);
ohrdlog.LoadLastQso(10);
// ]]></script>
<img src="http://www.hrdlog.net/callplate.aspx?user=W2ZXL" alt="W2ZXL CallPlate" /></center><!-- HRDLOG.net script stop -->
Consider swapping CSS classes to change the background-image instead. This will simplify the javascript and html markup. When you're on air change the class to onair and toggle as needed to offair.
CSS
.onair {
background-image: url("onair.jpg");
}
.offair {
background-image: url("offair.jpg");
}
Html
<div id="hrdlog-oa" class="offair"></div>
Javascript
var statusDiv = document.getElementById("hrdlog-oa");
if (statusDiv.className == "offair") {
statusDiv.className = "onair";
}
else {
statusDiv.className = "offair";
}
Working jsfiddle http://jsfiddle.net/jasenhk/qMAZU/ using background-color instead.
You can not do that with pure HTML and you had 2 way for solving this
If you like markup languages you can use xsl that have if else tag for you
Using Javascript and check if you be on air show on air image and if you not be shows off air
for you the better way is change some javascript code in your site..
you should overwrite ohrdlog.LoadOnAir then you have two way again:
change http://www.hrdlog.net/hrdlog.js source code and rewrite LoadOnAir function
overwrite LoadOnAir function with inserting script tag after load http://www.hrdlog.net/hrdlog.js
i choose number 2 for you because i think you can`t change script that you load it from another domain address... now you should insert this code after this part:
<script type="text/javascript" language="javascript" src="http://www.hrdlog.net/hrdlog.js"></script>
and you can found link of offair image in HrdLog.prototype.ShowOffAir function that now, i point it to http://2.bp.blogspot.com/_Dr3YNV7OXvw/TGNNf561yQI/AAAAAAAABIk/-E2MB4jLP_o/s400/Off-Air.jpg:
<script type="text/javascript" language="javascript">
HrdLog.prototype.ShowOffAir = function() {
return '[<img src="https://i.stack.imgur.com/WEr1B.jpg" height="33" width="65" />][2]';
}
HrdLog.prototype.LoadOnAir = function() {
var t = this;
var async = new Async();
async.complete = function(status, statusText, responseText, responseXML, obj) {
if (status == 200) {
txt = '';
var xmldoc = responseXML;
var onairdoc = xmldoc.getElementsByTagName('OnAir');
if (onairdoc.length == 1) {
onair = onairdoc.item(0);
if (onair.getElementsByTagName('oa_QRZ').length > 0) {
txt += '<img src="http://www.hrdlog.net/images/onair.gif" height="33" width="65" /><br/>';
txt += '<font size="+1">' + onair.getElementsByTagName('oa_QRZ')[0].childNodes[0].nodeValue + ' is on air</font><br/>';
txt += '<b>';
txt += FormatNumber(onair.getElementsByTagName('oa_Frequency')[0].childNodes[0].nodeValue) + ' ';
try {
txt += onair.getElementsByTagName('oa_Mode')[0].childNodes[0].nodeValue + '</b><br/>';
txt += onair.getElementsByTagName('oa_Radio')[0].childNodes[0].nodeValue + '<br/><br/>';
} catch (e) { }
//txt += onair.getElementsByTagName('oa_Status')[0].childNodes[0].nodeValue + '<br/>';
}else{
txt += t.ShowOffAir();
}
}else{
txt += t.ShowOffAir();
}
element = document.getElementById('hrdlog-oa');
if (element != null) {
element.innerHTML = txt;
}
} else {
alert('Error\n' + statusText);
}
}
if ((new Date().getTime() - this._lastLoadOnAir.getTime()) > 14500) {
this._lastLoadOnAir = new Date();
async.req(this._host + 'hrdlog.aspx?onair=' + this._qrz, this);
}
}
</script>

Javascript event handler to update a JSON object name

I am just starting out in Javascript and was wondering if anyone would mind pointing me in the right direction with this query I have.
I have created a JSON array and now wish to update some text on the page from the array upon clicking of the button. I have an event handling function that updates an image OK but I can't work out how to have the object name (pageRef) update within the 'nextPage' function so that the text updates from the contents of the array. I appreciate that this is probably a really obvious question but a pointer in the right direct will be greatly appreciated.
var diary_1938 = {
'page_1': {
'date_0': '1st Jan','entry_0': 'This is the first line',
'date_1': '2nd Jan','entry_1': 'This is the second line',
'date_2': '4th Jan','entry_2': 'This is the third line',
'img': 'image_1.jpg'},
'page_2': {
'date_0': '12th Jan','entry_0': 'This is the first line',
'date_1': '13th Jan','entry_1': 'This is the second line',
'date_2': '14th Jan','entry_2': 'This is the third line',
'img': 'image_2.jpg'},
};
var counter = 1;
var pageRef = "page_"+counter;
function nextPage() {
counter++
document.getElementById("DiaryImage").src = "image_"+counter+".jpg";
}
function prevPage() {
counter--
document.getElementById("DiaryImage").src = "image_"+counter+".jpg";
}
</script>
</head>
<body>
<button type = "submit" name = "submit_prev" onClick = "prevPage()"> << </button>
<button type = "submit" name = "submit_next" onClick = "nextPage()"> >> </button>
<br/>
<script> document.write(diary_1938[pageRef].date_0 + "<br/>"); </script>
<script> document.write(diary_1938[pageRef].entry_0 + "<br/><br/>"); </script>
<script> document.write(diary_1938[pageRef].date_1 + "<br/>"); </script>
<script> document.write(diary_1938[pageRef].entry_1 + "<br/><br/>"); </script>
<script> document.write(diary_1938[pageRef].date_2 + "<br/>"); </script>
<script> document.write(diary_1938[pageRef].entry_2 + "<br/><br/>"); </script>
<script>document.write("<img id = 'DiaryImage' src = 'image_1.jpg' width='370' height='790' name ='Dunford'/>"); </script>
</body>
document.write is only read once as the page is being loaded into the browser, it's not really best practice to use it for updating dynamic content.
What you could do, is wrap up your dynamic content in a div like so:
<div id="content"></div>
then write a function that populates this div from the JSON data (this could be a lot more elegant but as you're just starting out, for simplicity's sake):
function populatePageFromJson(JSONobject){
var divElement=document.getElementById("content");
divElement.innerHTML=JSONobject[pageRef].date_0+"<br/>"+
JSONobject[pageRef].entry_0+"<br/><br/>"+
JSONobject[pageRef].date_1+"<br/>"+
JSONobject[pageRef].entry_1+"<br/><br/>"+
JSONobject[pageRef].date_2+"<br/>"+
JSONobject[pageRef].entry_2+"<br/><br/>"
}
And when the page loads have this function load up:
window.onload= function() {
populatePageFromJson(diary_1938);
}
also change prevPage() and nextPage() as well (Note that in your case, you forgot to update pageRef):
function prevPage() {
counter--
pageRef = "page_"+counter;
document.getElementById("DiaryImage").src = "image_"+counter+".jpg";
populatePageFromJson(diary_1938);
}
Here is a jsFiddler example to tie it all up.
Again this is hardly the most elegant way of doing so, but hopefully it will give you some insight into Javascript.
Once you're comfortable with the understanding of basic Javascript I recommend you getting acquainted with jQuery. It will make such tasks much easier. Good luck!
Because you code in nextPage() is invoked every time when button is clicked. However, your code like :*var counter = 1;var pageRef = "page_"+counter;document.write(diary_1938[pageRef].date_0 + "");* is executed only once when initializing. so you'd better write you code as:
function nextPage() {
counter++;
pageRef = "page_"+counter;
/*clear written content before*/
document.write(diary_1938[pageRef].date_0 + "<br/>");
/*other document.write,*/
document.getElementById("DiaryImage").src = "image_"+counter+".jpg";
}

Categories