I want to add script tag using javascript, but I am not able to get it work. Below is code. I want to add this code in bigcommerce cart page.
var duration = document.getElementsByName("cartdata");
var cartstr = '<!-- MyBuys Page Parameters – Place in <body> element -->';
cartstr += '<script type="text/javascript">';
cartstr += 'mybuys.setPageType("SHOPPING_CART");';
cartstr += 'mybuys.set("email","consumer#example.com"); <!--consumer email can be blank if not known-->';
cartstr += 'mybuys.set("amount","99.34");';
for (var i = 0; i < duration.length; i++) {
str = duration[i].value;
var n = str.split('|');
cartstr += 'mybuys.addCartItemQtySubtotal("'+n[0]+'","'+n[1]+'","'+n[2]+'");'+'<br>';
}
cartstr += '</script>';
cartstr += '<!-- End MyBuys Page Parameters -->';
//alert(cartstr);
var script = document.createElement("script");
script.type = "text/javascript";
script.text = cartstr; // use this for inline script
document.body.appendChild(script);
I want below code added to page:
<!-- MyBuys Page Parameters – Place in <body> element -->
<script type="text/javascript">
mybuys.setPageType("SHOPPING_CART");
mybuys.set("email","consumer#example.com"); <!--consumer email can be blank if not known-->
mybuys.set("amount","99.34");
mybuys.addCartItemQtySubtotal("12345","1","54.34");
mybuys.addCartItemQtySubtotal("56789","3","45.00");
</script>
<!-- End MyBuys Page Parameters -->
This demonstrates how to dynamically add JavaScript:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
var optionalFunctionLoaded = false;
var commonFunction = function() {
console.log("test button clicked " + (new Date()).toLocaleString());
if (!optionalFunctionLoaded) {
// get optionalSrc e.g. via AJAX, eventually providing actual input values
var optionalSrc = 'function optFun(){console.log("optional function");}';
// if optionalSrc is not empty
var script = document.createElement("script");
script.innerHTML = optionalSrc;
document.head.appendChild(script);
optionalFunctionLoaded = true;
}
if(optionalFunctionLoaded) optFun();
}
</script>
</head>
<body>
<button id ="testButton">test</button>
<script type="text/javascript">
document.getElementById("testButton").onclick = commonFunction;
</script>
</body>
</html>
Tested with Firefox 24.0 / Linux.
The solution is to just add the code to the page:
<!-- MyBuys Page Parameters – Place in <body> element -->
<script type="text/javascript">
mybuys.setPageType("SHOPPING_CART");
mybuys.set("email","consumer#example.com"); <!--consumer email can be blank if not known-->
mybuys.set("amount","99.34");
mybuys.addCartItemQtySubtotal("12345","1","54.34");
mybuys.addCartItemQtySubtotal("56789","3","45.00");
</script>
<!-- End MyBuys Page Parameters -->
Why use JavaScript to put it there? Just add it to the page. You might have to adjust it a bit with your loop:
for (var i = 0; i < duration.length; i++) {
str = duration[i].value;
var n = str.split('|');
mybuys.addCartItemQtySubtotal(n[0],n[1],n[2]);
}
You should just be executing the code, there is no need to build the string. In the end, what you are trying to do is the same thing as running the code! Just execute it.
mybuys.setPageType("SHOPPING_CART");
mybuys.set("email","consumer#example.com");
mybuys.set("amount","99.34");
for (var i = 0; i < duration.length; i++) {
str = duration[i].value;
var n = str.split('|');
mybuys.addCartItemQtySubtotal(n[0],n[1],n[2]);
}
I don't know why would you want to do that. But if you really want to, here is a way you could try.
$('body').append("console.log('blah');")
OR
$('body').html($('body').html()+"console.log('blah');")
Replace console.log('blah') with your code
Note this is assuming you are using JQuery.
If not, you can still use Native Javascript to do something similar. Just search for creating an element and adding it to another using vanila javascript and you'll get lots of information on google.
Although, as epascarello says, its not a good idea to do this. Its basically a code smell and you can improve your code.
Hope this helps.
Related
When a HTML file is loaded, I want to run a script which would remove few scripts tags from the HTML file based on the user agent.
To do this I've followed this question: Removing all script tags from html with JS Regular Expression
But couldn't achieve what I needed, the script tags are removed and they are getting downloaded.
HTML:
<html>
<head>
</head>
<body>
<p></p>
<script type="text/javascript">
function stripScripts(s) {
var div = document.createElement('div');
div.innerHTML = s;
var scripts = div.getElementsByTagName('script');
var i = scripts.length;
while (i--) {
scripts[i].parentNode.removeChild(scripts[i]);
}
return div.innerHTML;
}
var userAgent = navigator.userAgent;
console.log(userAgent);
if (!userAgent.includes("Chrome")) {
stripScripts(); // Here how can I call the present index.html?
}
else {
var para = document.createElement("P");
var t = document.createTextNode("You cannot view this in Chrome");
para.appendChild(t);
document.body.appendChild(para);
};
</script>
<script type="text/javascript" src="scripts2.js"></script> <!-- load only when the condition is met else remove it --!>
</body>
</html>
When I run the index.html in chrome, script2.js is loading all the time.
i just want to know how to execute this [JSCODE][1] on page load, I'm a newbie and I cant figure it out. I just want to disregard the form or submit button and execute the script on page load. Thank You in advance!
[1]: http://jsfiddle.net/Noumenon72/9X3yZ/8/
Write your code inside anonymous function given below..
$(function() {
//Write your code here
})
Use jquery $(document).ready like this.
$(document).ready(function(){
//task which you want to perform
});
See you code below. I have mentioned where to call these functions.
$(document).ready(function(){
$('#domain').val('http://yourblog.blogspot.com/');
$('#get_tags').click();
});
function getTagsFromFeed(domain){
var myscript = document.createElement("script");
myscript.src = domain + "feeds/posts/summary?alt=json&max-results=0&callback=cat";
document.getElementsByTagName('head')[0].appendChild(myscript);
}
function cat(json){ //get categories of blog & sort them
var label = json.feed.category;
var lst=[];
for (i=0; i<label.length; i++){
lst[i] = label[i].term;
}
displayList(lst.sort()); //use any sort if you need that
}
function displayList(list) {
var mylist = document.getElementById("mylist");
mylist.innerHTML = "";
for (i=0; i<list.length; i++) {
var li = document.createElement("li");
li.appendChild(document.createTextNode(list[i]));
mylist.appendChild(li);
}
urlifyTagsInList(document.forms.myform.host.value);
}
function urlifyTagsInList(hostname){
var mylist = document.getElementById("mylist");
var newlist = document.createElement("ul");
var elements = mylist.getElementsByTagName("li");
for (j=0; j<elements.length; j++) {
var link = document.createElement("a");
var blah = document.createTextNode("blah");
link.href=hostname + "search/label/" + elements[j].innerHTML;
link.appendChild(elements[j].cloneNode(true));
newlist.appendChild(link);
}
mylist.parentNode.replaceChild(newlist, mylist);
newlist.id = "mylist";
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<form id="myform" method="POST" onSubmit="getTagsFromFeed(document.forms.myform.host.value); return false;">
<p> Enter blogspot domain (http://yourblog.blogspot.com/):</p>
<input id="domain" type="text" name="host"></input>
<button id="get_tags" type="submit">Get tags</button>
</form>
<ul id="mylist">
</body>
</html>
If you want to use pure javascript, Document ready with pure JavaScript will help you.
A simple way to submit form onload is like this.
$(document).ready(function(){
$('#myForm').submit();
});
So, I'm new to learning js. And I know that document.write is outdated and the new solution is element.innerHTML. I'm working through some tutorial, but in testing my code it's breaking. What would be the appropriate means of going about inserting element.innerHTML and it's accompanying code, to get this to work?
Below is my snippet:
<!DOCTYPE html>
<html>
<head>
<title>8. Javascript Arrays</title>
</head>
<body>
<h1>8. Javascript Arrays</h1>
<script>
<div id="flightDate"></div>
<div id="myValues"></div>
var flightDate = new Date("September 22, 2004");
var myValues = ["Oceanic", 815, flightDate];
for (i in myValues)
{
document.write("<br />" + myValues[i]);
}
</script>
</body>
</html>
You can display the output in the DIVs that you created.
document.getElementById('flightDate').innerHTML = flightDate;
for (i = 0; i < myValues.length; i++) {
document.getElementById('myValues').innerHTML += myValues[i] + '<br/>';
}
+= concatenates the value with the content that's already there.
i have a code that is supposed to read from a html file, split it into an array and display parts of that array, but when going though with alert, i found that $.get is not actually getting the file
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
</head>
<body>
<button onclick="myfunction()">update</button>
<div id="div1"></div>
<script>
function myfunction() {
var info = "";
$.get("../Read_Test/text.html", function(data) {
SomeFunction(data);
});
alert(info);
var array = info.split("§n");
var people = array[1].split(",");
for (var i = 0; i < people.length; i++) {
document.getElementById("div1").innerHTML = people[i] + "<br>";
}
}
function SomeFunction(data) {
var info = data;
}
</script>
</body>
</html>
the directories are on a server and go like so:
Sublinks->Read_Test->This_File.html,text.html
The objective of this is that a file would have something along the lines of "a§nb1,b2,b3,§n" and the script would split it via "§n" then get "array[1]" and split that via ",". lastly it displays each part of that newly created array on a new line, so a file with "a§nb1,b2,b3,§n" would result in:
b1
b2
b3
Please help
Ajax is asynchronous, it make request and immediately call the next instruction and not wait for the response from the ajax request. so you will need to process inside of $.get. success event.
I have changed delimiter character to ¥. change same in text.html. problem was you have not mentioned character set to utf8 and due to this it could not recognized the special character and subsequently not able to split the string. i have aldo document type to HTML5.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<button onclick="myfunction()">update</button>
<div id="div1"></div>
<script>
function myfunction() {
$.get("../Read_Test/text.html", function(data) {
var info = data;
var array = info.split("¥");
var people = array[1].split(",");
for (var i = 0; i < people.length; i++) {
document.getElementById("div1").innerHTML += people[i] + "<br>";
}
});
}
</script>
</body>
</html>
I'm creating a page which is suppose to be a little interactive. The user is suppose to be able to change a bunch of information by checking off an checkbox.
Index.php:
<span id="changeIt">Deactivated! - [ChangeMod]<img src="pic/deactivated.png"></span>
<form action="">
<input type="checkbox" id="checkboxChange" onclick="ChangeEverything();">Change Everything!</input>
</form>
<script TYPE="text/javascript" SRC="script/map_checkbox.js"></script>
map_checkbox.js:
var checkbox6 = document.getElementById("checkboxChange");
var posting6 = document.getElementById("changeIt");
var script = document.createElement("scriptChange");
function ChangeEverything(){
if (checkbox6.checked){
posting6.innerHTML="Activated! - [ChangeMod]<img src='pic/activated.png'>" ;
script.src = 'scriptMain.js';
var head = document.getElementsByTagName("head")[0];
head.appendChild(scriptChange);
}
else{
posting6.innerHTML="Deactivated! - [ChangeMod]<img src='pic/deactivated.png'>" ;
script.src = 'scriptSec.js';
var head = document.getElementsByTagName("head")[0];
head.appendChild(scriptChange);
}
}
Is it possible to overwrite the script like this, or do I have to use another method?
i think you have a problem with the
var script = document.createElement("scriptChange");
tou have to put the tag NAME
var script = document.createElement("script");