How can I load a hotel search from the HotelsCombined script? - javascript

I am trying to add a hotel search on my website. The hotel search is created by HotelsCombined and they have given me this code to show the hotel search:
<script type='text/javascript' src='http://hoteles.gangatravel.es/SearchBox/297018'></script>
But I've put the code in my html and does not work, anyone know how I can load the script? I tried it with an iframe and does not work either.

Well, what exactly do you want it to do?
I can show you the general idea. That is: the script puts a variable HCSB in the memory. That variable has properties (= variables of an object) and methods (= functions of an object)
<script src="http://hoteles.gangatravel.es/SearchBox/297018"></script>
<script>
// by loading this script, you get a variable HCSB
// so, an example of a variable dump of HCSB
function var_dump() {
for (i in HCSB) {
log(i +': '+ HCSB[i]);
}
}
function log(text) {
document.getElementById('log').innerHTML += text + '<hr>';
}
</script>
<input type="button" value="var dump" onclick="var_dump()">
<div id="log"></div>
EDIT: I presume you want something like this: http://hoteles.gangatravel.es/
You want such a form on your site. But would you mind elaborating a little more?
Oh yes, forget iframe. This is an javascript API.

Related

How to use chrome.storage

I'm a newbie to coding, and I wanted to know how to use chrome.storage.local to store variables.
This is my HTML and javascript code(its a very basic version of what I want)
chrome.storage.sync.set({'value': document.getElementById("userInput").value}, function() {
// Notify that we saved.
})
chrome.storage.local.get(['value'], function(result) {
OnTaskPage=result.key;
document.getElementById("userInput").value = result;
});
<body>
<h1 id="userInput">What site do you want to stay on?</h1>
<input type="text" value="">
</body>
<script src="content.js"></script>
I'm pretty sure I'm messing up the javascript, but I don't know where because I am new to the syntax, and pretty much have no clue what I'm doing. The point of the javascript code is to store the value inside the html text box. Can someone please help me? Thanks!
Problems:
The id should be on input element, not on h1.
result is an object so to access the value you need to read result.value, look for tutorials on using JavaScript objects.
Currently you clear the saved value first by using set() with an empty value, and then read that empty value. You probably don't need set() here, but rather in some other event like a click on a button element.
The script content.js is named ambiguously/incorrectly because content scripts are for web pages, not for the extension page, so it should be named differently, e.g. popup.js
chrome.storage.local.get({value: ''}, result => {
OnTaskPage = result.value;
document.getElementById('userInput').value = result.value;
});
document.getElementById('save').onclick = () => {
chrome.storage.sync.set({value: document.getElementById('userInput').value});
};
and html:
<body>
<h1>What site do you want to stay on?</h1>
<input id="userInput">
<button id="save">save</button>
</body>
<script src="popup.js"></script>

Store JSON information within a HTML file or the other way around

That title might be a little confusing but I don't know how to put it otherwise. I have some JSON encoded data in a .json-file:
{"foo":"bar", "bar":"foo", "far":"boo"}
and some HTML content in a .html-file:
<h1>I'm a Title</h1>
<p>Lorem Ipsum</p>
<br>
<img src="./media/foo.png">
There is a jQuery script that takes the data from both files ($.getJSON() and $(#div).load()) and creates a page with some predefined head, uses the html as content and the json data to create some buttons (key=destination & value=name) on there.
Because the project has many of these pages I would love to have only one file that holds both my HTML content AND the JSON data so I had all I needed for one page would be a single file access. So the question really is: How can I store both JSON and HTML data in one file so jQuery can access, distinguish and process it?
This is part of an electron application but I'm not sure if that even matters for that question.
The content of the json file assuming it is a json object can be assigned to a javascript variable in the html document in a script tag.
Then to refer to, for example foo, you use theJsonObject.foo;
With the following javascript snipet you can see inthe browser's console the name of each property an the value.
How you mix this in your current code depends on how you are writting it. But make sure the variable is declared before you use it.
for (let prop in theJsonObject) {
console.log( prop + ": " + theJsonObject[prop] );
};
<html>
<head>
....
<script>
var theJsonObject = {"foo":"bar", "bar":"foo", "far":"boo"};
</script>
</head>
<body>
....
</body>
</html>

Script to pick up the HTML value of a page? Explanation inside

I am quite the noob at anything other than some HTML, CSS etc, basic website stuff. My javascript is pretty non-existant too. However we were quoted £2,500 by the people who develop our website to add Paypal on the checkout page! They use a fancy 3rd party program which is a standalone software made by themselves that contains all the products etc. We pay monthly to have access to that and make all website changes (such as price, product name etc) in that.
To cut a long story short, I had a look around and found this:
<script src="paypal-button.min.js?merchant=YOUR_MERCHANT_ID"
data-button="buynow"
data-name="My product"
data-amount="1.00"
async
></script>
Now, can I change the data-amount field to pick up what the "value" is on the page in the HTML? That way I can simply just add a button that picks that up. Which would work with paypal.
<div class='basketLabel'>Total Amount To Pay:</div>
<span>£</span>1,038.00</li>
<input type=hidden name='amount' value='1,038.00'>
Basically, how can I get the javascript code to pick up the value from the HTML (or somewhere else). I only have access to the full HTML of the page.
I am not sure how many of these data fields you have on a page but you could write a JS method to dynamically assign the values of the given HTML.
I would start by giving the HTML you're working with some ID's.
<script id="paypalScript" src="paypal-button.min.js?merchant=YOUR_MERCHANT_ID"
data-button="buynow"
data-name="My product"
data-amount="1.00"
async
onload="assignAmount"
></script>
<div class='basketLabel'>Total Amount To Pay:</div>
<span>£</span>1,038.00</li>
<input id="amount" type=hidden name='amount' value='1,038.00'>
Then write a method to execute onload.
function assignAmount(){
var amtElm = document.getElementById('amount');
var scriptElm = document.getElementById('paypalScript');
scriptElm.dataset.amount = amtElm.value;
}
Then attach the method to the onload event of the script element. Putting the script tag below your data field in the HTML should prevent any load issues you might run into.

Is using custom HTML tags and replacing custom tags with outerHTML okay?

Is it alright to define and use custom tags? (that will not conflict with future html tags) - while replacing/rendering those by changing outerHTML??
I created a demo below and it seems to work fine
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<script type="text/javascript" src="jquery.min.js"></script>
</head>
<body>
<div id="customtags">
<c-TextField name="Username" ></c-TextField> <br/>
<c-NameField name="name" id="c-NameField"></c-NameField> <br/>
<c-TextArea name="description" ></c-TextArea> <br/>
<blahblah c-t="d"></blahblah>
</div>
</body>
<script>
/* Code below to replace the cspa's with the actual html -- woaah it works well */
function ReplaceCustomTags() {
// cspa is a random term-- doesn;t mean anything really
var grs = $("*");
$.each(grs, function(index, value) {
var tg = value.tagName.toLowerCase();
if(tg.indexOf("c-")==0) {
console.log(index);
console.log(value);
var obj = $(value);
var newhtml;
if(tg=="c-textfield") {
newhtml= '<input type="text" value="'+obj.attr('name')+'"></input>';
} else if(tg=="c-namefield") {
newhtml= '<input type="text" value="FirstName"></input><input type="text" value="LastName"></input>';
} else if(tg=="c-textarea") {
newhtml= '<textarea cols="20" rows="3">Some description from model</textarea>';
}
obj.context.outerHTML = newhtml;
}
z = obj;
});
}
if(typeof(console)=='undefined' || console==null) { console={}; console.log=function(){}}
$(document).ready(ReplaceCustomTags);
</script>
</html>
Update to the question:
Let me explain a bit further on this. Please assume that JavaScript is enabled on the browser - i.e application is not supposed to run without javascript.
I have seen libraries that use custom attributes to define custom behavior in specified tags. For example Angular.js heavily uses custom attributes. (It also has examples on custom-tags). Although my question is not from a technical strategy perspective - I fail to understand why it would strategically cause problems in scalability/maintainability of the code.
Per me code like <ns:contact .....> is more readable than something like <div custom_type="contact" ....> . The only difference is that custom tags are ignored and not rendered, while the div type gets rendered by the browser
Angular.js does show a custom-tag example (pane/tab). In my example above I am using outerHTML to replace these custom tags - whilst I donot see such code in the libraries - Am I doing something shortsighted and wrong by using outerHTML to replace custom-tags?
I can't think of a reason why you'd want to do this.
What would you think if you had to work on a project written by someone else who ignored all common practices and conventions? What would happen if they were no longer at the company to find out why they did something a certain way?
The fact that you have to just go through with JavaScript to make it work at all should be a giant red flag. Unless you have a VERY good reason to, do yourself a favor and use the preexisting tags. Six months from now, are you going to remember why you did things that way?
It may well work, but it's probably not a good idea. Screen readers and search engines may have a hard/impossible time reading your page, since they may not interpret the JavaScript. While I can see the point, it's probably better to use this template to develop with, then "bake" it to HTML before putting it on the server.

How do you write Valid XHTML 1.0 Strict code when you are using javascript to fill an element that requires a child?

I'm running my site through the W3C's validator trying to get it to validate as XHTML 1.0 Strict and I've gotten down to a particularly sticky (at least in my experience) validation error. I'm including certain badges from various services in the site that provide their own API and code for inclusion on an external site. These badges use javascript (for the most part) to fill an element that you insert in the markup which requires a child. This means that in the end, perfectly valid markup is generated, but to the validator, all it sees is an incomplete parent-child tag which it then throws an error on.
As a caveat, I understand that I could complain to the services that their badges don't validate. Sans this, I assume that someone has validated their code while including badges like this, and that's what I'm interested in. Answers such as, 'Complain to Flickr about their badge' aren't going to help me much.
An additional caveat: I would prefer that as much as possible the markup remains semantic. I.E. Adding an empty li tag or tr-td pair to make it validate would be an undesirable solution, even though it may be necessary. If that's the only way it can be made to validate, oh well, but please lean answers towards semantic markup.
As an example:
<div id="twitter_div">
<h2>#Twitter</h2>
<ul id="twitter_update_list">
<script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script>
<script type="text/javascript" src="http://twitter.com/statuses/user_timeline/stopsineman.json?callback=twitterCallback2&count=1"></script>
</ul>
</div>
Notice the ul tags wrapping the javascript. This eventually gets filled in with lis via the script, but to the validator it only sees the unpopulated ul.
Thanks in advance!
The following fragment is valid XHTML and does the job:
<div id="twitter_div">
<h2 class="twitter-title">Twitter Updates</h2>
<div id="myDiv" />
</div>
<script type="text/javascript">
var placeHolderNode = document.getElementById("myDiv");
var parentNode = placeHolderNode.parentNode;
var insertedNode = document.createElement("ul");
insertedNode .setAttribute("id", "twitter_update_list");
parentNode.insertBefore( insertedNode, placeHolderNode);
parentNode.remove(placeHolderNode);
</script>
<script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script>
<script type="text/javascript" src="http://twitter.com/statuses/user_timeline/stopsineman.json?callback=twitterCallback2&count=5"></script>
Perhaps you could use javascript to write the initial badge HTML? You'd probably only want the badge code to be inserted in your document if javascript were available to populate it, right?
You'd just need to make sure your document writing happens before the javascript for your various badges.
Could you give a specific example of the HTML / link to a page with the invalid code?
The solutions might be different for each badge. In Twitter's case, you can just write your own callback function. Here's an example based on their badge code:
<div id="twitter_div">
<h2>#Twitter</h2>
<div id="twitter_update_list"></div>
</div>
<script type="text/javascript">
function updateTwitterCallback(obj)
{
var twitters = obj;
var statusHTML = "";
var username = "";
for (var i = 0; i < twitters.length; i++)
{
username = twitters[i].user.screen_name;
statusHTML += ('<li><span>' + twitters[i].text + '</span> <a style="font-size:85%" href="http://twitter.com/' + username + '/statuses/' + twitters[i].id + '">' + relative_time(twitters[i].created_at) + '</a></li>');
}
document.getElementById('twitter_update_list').innerHTML = '<ul>' + statusHTML + '</ul>';
}
</script>
<script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script>
<script type="text/javascript" src="http://twitter.com/statuses/user_timeline/stopsineman.json?callback=updateTwitterCallback&count=1"></script>
I put a <li> with "display:none" in the <ul> Tag:
<ul id="twitter_update_list"><li style="display:none;">A</li></ul>
<script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script>
<script type="text/javascript" src="http://twitter.com/statuses/user_timeline/01241.json?callback=twitterCallback2&count=1"></script>
This does not disturb the script and in this case it works,
and I think its not a "undesirable solution" :)
At some point the page becomes valid, right? That's the only time it can really be validated.
I'm not sure a non-trivial page will remain valid at every point during its construction if it's constructed with a lot of DOM scripting.
This might not be the most popular opinion on this topic, but...
Don't worry about 100% validation. It's just not that big of a deal.
The point of validation is to make your markup as standard as possible. Why? Because browsers that are given markup that doesn't conform to the spec (eg, markup that does not validate) do their own error checking to correct it and display the page the way you intended it to look to the user. The quality of the browsers error checking varies, yadda-yadda-yadda, it's better to have valid markup... But it's not even your code that's causing the validation to fail! The people who wrote those badges probably tested them in multiple browsers (and you should do the same, of course), if they work as expected then just leave it at that.
In short, there's no prize for validating :)

Categories