HTML with XML using jQuery - javascript

i have xml file which contains lots of data. now i want to pick a price with some condition. i set a parameteres in javascript function but it is not giving desire result. i think it can be done through childnode but i didnot aware about that
XML file
<flights updated="2012-03-09T04:38:00.437" type="flights" ob_id="45792117" lastedit="2012-03-09T15:10:01" partner_id="63" activate_date="2012-02-15T00:00:00" page_id="9646" page_pk_id="12597" pos_pk_id="51565" pos="1" module_id="3" pos_name="Flights" product_type_id="4" product_type="flight" headline="Bali" destination="Bali" localised_destination="Denpasar" headline_no_html="Bali" price="199" deals_space_limited="0" deals_sold_out="0" qa_approved="1" tp_available="0" tp_weight="10" partner_eapid="0-25" partner_pid="25" publish_path="\\dubvappdaily01\daily_aus\data\psf\" partner_lang_id="3081" FrTLAs="PER" ToTLAs="DPS" FrDate="2012-04-27T00:00:00" ToDate="2012-05-04T00:00:00" Airline="QZ"/>
<flights updated="2012-03-09T04:38:00.437" type="flights" ob_id="45792117" lastedit="2012-03-09T15:10:01" partner_id="63" activate_date="2012-02-15T00:00:00" page_id="9646" page_pk_id="12597" pos_pk_id="51565" pos="1" module_id="3" pos_name="Flights" product_type_id="4" product_type="flight" headline="Bali" destination="Bali" localised_destination="Denpasar" headline_no_html="Bali" price="199" deals_space_limited="0" deals_sold_out="0" qa_approved="1" tp_available="0" tp_weight="10" partner_eapid="0-25" partner_pid="25" publish_path="\\dubvappdaily01\daily_aus\data\psf\" partner_lang_id="3081" FrTLAs="SYD" ToTLAs="DPS" FrDate="2012-04-27T00:00:00" ToDate="2012-05-04T00:00:00" Airline="QZ"/>
HTML page
<head>
<script type="text/javascript">
function myXml(origin, destination ) {
var x = xmlDoc.getElementsByTagName("flights");
for(i=0; i<x.length; i++) {
if (x[i].getAttribute('FrTLAs') == origin
&& x[i].getAttribute('destination') == destination) {
alert(x[i].getAttribute('price'))
}
}
}
</script>
</head>
<body>
click me
</body>

did u miss this??
xmlDoc=loadXMLDoc("flights.xml");
chk this page
http://www.w3schools.com/dom/prop_element_attributes.asp
the example2 is very clear how to use this
x=xmlDoc.getElementsByTagName("book")[0].attributes;
//here its would be getElementsByTagName("flights") in the loop
//then .attributes on it
// and then this
frtlas=x.getNamedItem("FrTLAs");
desti=x.getNamedItem("destination");
//and your code here
hope this helps

Related

Text to Html list

I want to make a html which will auto get the information for a *.txt file
something1
something2
something3
and output into this html file
<!DOCTYPE html>
<html>
<head>
<title>List</title>
</head>
<body>
<ul>
#here to output#
</ul>
</body>
</html>
I prefer to use JavaScript. Some help is appreciated.
You have to request the file using AJAX call. Then you need to iterate through each line of response and generate DOM element (li in this case) and input line inside of it. After that insert each li element into your ul list.
You can achieve it using jQuery as you are probably new to JavaScript it's probably the easiest way.
What you need to do is request the file first:
$.ajax('url/to/your/file', {
success: fileRetrieved
});
Now after the file is retrieved jQuery will call fileRetrieved method, so we have to create it:
function fileRetrieved(contents) {
var lines = contents.split('\n');
for(var i = 0; i < lines.length; i += 1) {
createListElement(lines[i]);
}
}
Now for each line from the file function fileRetrieved will call createListElement function passing line of text to it. Now we just need to generate the list element and inject it into DOM.
function createListElement(text) {
var into = $('ul');
var el = $('<li></li>').html(text);
el.appendTo(into);
}
Of course you don't want to retrieve into element each time createListElement is called so just store it somewhere outside the function, it's your call, I'm just giving you the general idea.
Here is an example of the script (without AJAX call of course as we can't simulate it):
var into = $('#result');
function fileRetrieved(contents) {
var lines = contents.split('\n');
for (var i = 0; i < lines.length; i += 1) {
createListElement(lines[i]);
}
}
function createListElement(text) {
var el = $('<li></li>').html(text);
el.appendTo(into);
}
var text = $('#text').html();
fileRetrieved(text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- This element simulates file contents-->
<pre id="text">
fdsafdsafdsa
fdsafd
safdsaf
dsafdsaf
dsafdsafds
afdsa
</pre>
<div id="result"></div>
Try this
<html>
<head>
<title>List</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<ul id="renderTxt_list">
</ul>
<input type="button" id="lesen" value="Read Data" />
</body>
<script>
$(document).ready(function(){
$("#lesen").click(function() {
$.ajax({
url : "testTxt.txt",
dataType: "text",
success : function (data) {
$html = "";
var lines = data.split("\n");
for (var i = 0, len = lines.length; i < len; i++) {
$html += '<li>'+lines[i]+'</li>';
}
$("body ul").append($html);
}
});
});
});
</script>
</html>
You need to request the file first, and then append it to your chosen place in the document.
You can for example use jQuery's get (or any other function like the native fetch), and then inject it into the ul element:
$.get("*.txt").then(x => $("ul").html("<li>" + x.split('\n').join('</li><li>') + "</li>"))
Let's break this solution by steps:
First, we need to request the external file:
$.get("*.txt")
Read about jQuery's get here. Basicly it will request the file you asked for using network request, and return a promise.
In the Promise's then, we can do stuff with the request's result after it is resolved. In our case we want to first break it by lines:
x.split('\n')
split will return an array that will look like this: ["line 1, "line 2", "line 3"].
JS arrays have the join method, which concat them to string while putting the string you want between the items. So after we do this:
x.split('\n').join('</li><li>')
We only need to add the <li> element to the start and end of the string like this:
"<li>" + x.split('\n').join('</li><li>') + "</li>"
Finally we appent it to your chosen element using jQuery's html.

How to open a URL and estimate the word count using JavaScript?

<html>
<head>
<script type="text/javascript">
function open_urls() {
var url1="https://finance.yahoo.com/";
var newpage=window.open(url1);
alert(newpage.document.body.innerText.split(' ').length);
}
</script>
</head>
<body onload="javascript: open_urls()"></body>
</html>
The code above did not work, how to access DOM for a different URL?
I'd like to open an URL and show the word count of that URL.
You can't simply open another window and page and expect to have access to it. The web follows many security policies to prevent operations like this, such as the Same-Origin policy. Long-story short, you can't access URLs that don't fall under the same-origin as the page you're calling from. You couldn't therefore access Yahoo finance in your example (most likely).
If you were calling from the same origin, you could use an API like fetch to get just the text and do a word count there, or you could even load an iframe and query that: myIframe.contentWindow.document.body.innerHTML.
So knowing that you cannot do this from the browser, you could do it from a NodeJS application (perhaps also using fetch):
var fetch = require('node-fetch');
fetch('https://finance.yahoo.com/')
.then(function(res) {
return res.text();
}).then(function(body) {
console.log(body);
// perform word-count here
});
I understand that you were hoping to do this from the browser, but unfortunately you will not be able to do so for origins that you do not control.
You can try this out.
In you index.html (suppose) write this:
<html>
<head>
<title>Index Page</title>
</head>
<script type="text/javascript">
function poponload()
{
testwindow = window.open("new_window.html", "mywindow","location=1,status=1,scrollbars=1,width=600,height=600");
}// here new_window.html is file you want to open or you can write any url there
</script>
<body onload="javascript: poponload()">
<h1>Hello this can Work</h1>
</body>
</html>
And suppose your new_window.html is like this:
<html>
<head>
<script>
function get_text(el) {
ret = "";
var length = el.childNodes.length;
for(var i = 0; i < length; i++) {
var node = el.childNodes[i];
if(node.nodeType != 8) {
ret += node.nodeType != 1 ? node.nodeValue : get_text(node);
}
}
return ret;
}
function run_this(){
var words = get_text(document.getElementById('content'));
var count = words.split(' ').length;
alert(count);
}
</script>
</head>
<body onload='javascript: run_this()' id="content">
<h1>This is the new window</h1>
</body>
</html>

Javascript not rendering - Blank head

There's something wrong with my script, it doesn't render the JS correctly. I tried to pinpoint the problem but cannot find any typo. If i load the page, the tag is blank, making all css & other JS disabled. But suprisingly the data is loader correctly. If i remove the script, everything went to normal.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="jquery-1.9.1.js"></script>
<script src="jquery-ui.js"></script>
<script>
// Create a connection to the file.
var Connect = new XMLHttpRequest();
// Define which file to open and
// send the request.
Connect.open("GET", "Customers.xml", false);
Connect.setRequestHeader("Content-Type", "text/xml");
Connect.send(null);
// Place the response in an XML document.
var TheDocument = Connect.responseXML;
// Place the root node in an element.
var Customers = TheDocument.childNodes[0];
// Retrieve each customer in turn.
$("#middle").ready( function () {
document.write("<ul class='product'>");
for (var i = 0; i < Customers.children.length; i++)
{
var dul = "wawa"+[i];
//document.getElementById(dul).addEventListener('click', storeData, false);
var Customer = Customers.children[i];
// Access each of the data values.
var Pic = Customer.getElementsByTagName("pic");
var Name = Customer.getElementsByTagName("name");
var Age = Customer.getElementsByTagName("tipe");
var sex = Customer.getElementsByTagName("country");
var checked = window.localStorage.getItem("selected"+i);
// Write the data to the page.
document.write("<li><img href='./pic/");
document.write(Pic[0].textContent.toString());
document.write(".jpg'><a href='display.html?id="+i+"'>");
document.write(Name[0].textContent.toString());
document.write("</a><div class='age'>");
document.write(Age[0].textContent.toString());
document.write("</div><div class='sex'>");
document.write(sex[0].textContent.toString());
document.write("</div><div class='cex'>");
document.write("<input name='checkbox' type='checkbox' id='wawa_"+i+"'");
if (!checked) {
document.write(" onClick='cbChanged(this, "+i+")'");
} else {
document.write("checked onClick='cbChanged(this, "+i+")'");
}
document.write("></div></li>");
}
document.write("</ul>");
});
function cbChanged(checkboxElem, x) {
if (checkboxElem.checked) {
window.localStorage.setItem("selected"+x, x);
alert("That box was checked.");
} else {
window.localStorage.removeItem("selected"+x);
alert("That box was unchecked.");
}
}
</script>
</head>
<body>
<div class="container">
<div class="content" id="middle">
</div>
<div class="content" id="footer">
</div>
</div>
</body>
</html>
Ok here's the full source.
You don't close the HTML img tag right
Change
document.write("<li><img href='./pic/");
document.write(Pic[0].textContent.toString());
document.write("'.jpg><a href='display.html?id="+i+"'>");
// ^ this quote
To
document.write("<li><img href='./pic/");
document.write(Pic[0].textContent.toString());
document.write(".jpg'><a href='display.html?id="+i+"'>");
// ^ should be here
If you open the developer console you can usually see where errors like this take place. It will also output and javascript errors that you come across so it will make that part a whole lot easier. Do you have any errors in your console?
The dev consoles are:
Chrome: It is built it.
Firefox: Firebug
Safari: It's built it
EDIT:
Don't do var functionName = function() {..} unless you know about how hoisting works. This is contributing to you problem so change
cbChanged = function(checkboxElem, x) {
if (checkboxElem.checked) {
window.localStorage.setItem("selected"+x, x);
alert("That box was checked.");
} else {
window.localStorage.removeItem("selected"+x);
alert("That box was unchecked.");
}
}
To
function cbChanged(checkboxElem, x) {
if (checkboxElem.checked) {
window.localStorage.setItem("selected"+x, x);
alert("That box was checked.");
} else {
window.localStorage.removeItem("selected"+x);
alert("That box was unchecked.");
}
}
Without the above changes the function cbChanged is not hoisted. So if you call it before it is reached you will get an error.
There are several other things that stand out to me on this. You might want to spend some more time on your javascript fundamentals. Read up on why document.write is a bad thing. Try removing parts of the script to narrow down what is causing the problem. It would have made this easier to fix if you had made a fiddle.

How to grab text from URL and place in JS array?

I've stated previously that I am very new to JavaScript and HTML. I'm creating a small search tool and I'm very confused as to how to get text from a URL and put it in my JS array.
For example, let's say the URL is: http://www.somethingrandom.com/poop
In that URL, there's a couple of words: "something", "everything", "nothing"
Literally just that. It's in a pre tag in HTML, and that's it.
Now, my JS code, I want it to open up that URL, and take those words and place them in a string/list/array, whatever, it could be anything as long as it can happen, I can manipulate it further later.
I have this so far:
<html>
<head>
<script type = "text/javascript">
function getWords(){
var url = "http://www.somethingrandom.com/poop"
var win = window.open( url );
window.onload = function(){
var list = document.getElementsByTagName("pre")[0].innerHTML;
var listLength = list.length;
alert( listLength);
}
}
</script>
</head>
<body>
<button id="1" onClick="getWords();">Click Here</button>
</body>
</html>
It doesn't work however.. And I'm not sure why. :( Please help.
Make an AJAX request and you will have access to the returned content.
Using jQuery:
function getWords(){
var url = "http://www.somethingrandom.com/poop"
$.get(url, function(data) {
var list = $('pre:eq(0)', data).html;
var listLength = list.length;
alert( listLength);
}, 'html');
}

JS Variable Passing Via URL

I am designing a webpage that loads images of a document into the webpage and then will relocate to a specific image (page) based on a variable passed from another page. The code is below. Right now, it does not look like the variable 'page' is being updated. The page will alert
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<!-- Javascripts -->
<script type="text/javascript">
var pageCount = 40; /*Total number of pages */
var p; /*Variable passed to go to a specific page*/
function pageLoad(){ /*Loads in the pages as images */
for( i = 1; i<= pageCount; i++){
if(i < 10){
i = "0"+i;
}
document.body.innerHTML += "<div class='page'><a id='page" + i +"'><img src='pages/PI_Page_"+ i +".png' /></a></div>";
if( i == pageCount){
gotoPage(p);
}
}
}
function gotoPage(pageNum){ /* Moves webpage to target page of the PI */
window.location = ("#page" + pageNum);
alert(p);
}
function Test(){
window.open("./PI.html?p=15","new_pop");
}
</script>
</head>
<body onload="pageLoad()">
<div class="ExtBtn" onClick="Test()">
<img alt="Exit" src="design/exit_btn-02.png" />
</div>
</body>
</html>
The function TEST() was set up to allow me to have a link to re-open the page with p set to 15. The page opens, however, the function gotoPage() still alerts that p is undefined. Any ideas why that is?
Variables passed in the URL do not automatically become variables in JavaScript. You need to parse document.location and extract the value yourself.
p is never set a value anywhere so of course it will be undefined. You need to pull the value from the query string manually, JavaScript does not magically get the query string value for you.
Use the function here: How can I get query string values in JavaScript? to get the value.
Also why are you checking for the last index, set the go to call after the for loop.
Here is your code with the correct alert(p) working:
http://js.do/rsiqueira/read-param?p=15
I added a "function get_url_param" to parse url and read the value of "?p=15".

Categories

Resources