How can i use script parameters into my js file? - javascript

I have this script code:
<script src="http://example.com/embed.js?q=123&parameter1=450&parameter2=300"></script>
How can i get the values of q(123)and parameter1(450) and parameter2(300) and use them into embed.js file? I want to make conditions into my embed.js by using these values. How can i achieve that?

Give the script element and ID attribute like this:
<script id="embed-script" src="http://example.com/embed.js?q=123&parameter1=450&parameter2=300"></script>
Javascript:
var url = document.getElementById('embed-script');
function parseGet(val) {
var result = "",
tmp = [];
var items = url.src.split("?")[1].split('&');
for (var index = 0; index < items.length; index++) {
tmp = items[index].split("=");
if (tmp[0] === val)
result = decodeURIComponent(tmp[1]);
}
return result;
}
Get the values like this, in embed.js:
var value1 = parseGet('q');
value1 should then be "123".

I think you can't,but you can declare all param before required your js file same as:
<script type="text/javascript">
var q = 123;
var parameter1 = 450;
var parameter2 = 300;
</script>
<script src="http://example.com/embed.js"></script>

You could place the parameters in attributes of the <script> tag.
<script src="http://example.com/embed.js" q="123" parameter1="450" parameter2="300"></script>
You can access these parameters in embed.js with
document.currentScript.getAttribute('q');
document.currentScript.getAttribute('parameter1');
document.currentScript.getAttribute('parameter2');
Note: document.currentScriptdoes not work on IE.
For more info check this out.

You can access script tag as the last script tag if ask for it without waiting for document load.
~function() {
var s = document.querySelectorAll("script");
s = s[s.length-1];
console.log(s.src);
}();

Related

localStorage - Delete local|Storage value based on key

I am facing some problem in deleting localStorage json data. I have passed data in JSON format and want to delete value based on ID on click event. For example in JSON array if I have three entries of same id then want to delete three at a time.
here is my code
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var feed = {"proid":"2","canvas":"abc"};
a = JSON.parse(localStorage.getItem('names')) || [];
names = JSON.stringify(feed);
a.push(names);
localStorage.setItem('names', JSON.stringify(a));
var obj = "["+a+"]";
localStorage.setItem("productidf", obj);
$('#delete-item').click(function(){
var jsonprodId = localStorage.getItem("productidf");
var parsedJSON = $.parseJSON(jsonprodId);
var id = 2;
for(var i = 0; i < parsedJSON.length; i++){
if(parsedJSON[i].proid == id){
localStorage.removeItem(parsedJSON[i]);
}
}
localStorage.setItem("productidf", JSON.stringify(parsedJSON));
var newss = localStorage.getItem("productidf");
console.log(newss);
});
});
</script>
<a class="clicks" id="delete-item">Delete Items</a>
This code is not working to remove all values of id from localStorage. I can't use localStorage.clear(). Because it clear all localstorage.
Your localStorage.removeItem(parsedJSON[i]); line was the culprit.
localstorage cannot be traversed like an array. It just stores data in string format.
So you need to filter parsedJSON array using a js filter and then store the result back in localStorage
<script type="text/javascript" src="http://code.jquery.com/jquery-
latest.min.js"></script>
<script type="text/javascript">
var feed = {"proid":"2","canvas":"abc"};
var feed2={"proid":"3","canvas":"jack"}
a = JSON.parse(localStorage.getItem('names')) || [];
a.push(feed);
a.push(feed2);
localStorage.setItem('names', JSON.stringify(a));
localStorage.setItem("productidf", JSON.stringify(a));
var jsonprodId = localStorage.getItem("productidf");
var parsedJSON = $.parseJSON(jsonprodId);
var id = 2;
parsedJSON=parsedJSON.filter((obj)=>{
return obj.proid != id;
})
debugger
var obj = JSON.stringify(parsedJSON);
localStorage.setItem("productidf", obj);
console.log(parsedJSON);
</script>

string.split('/') not giving proper array

I'm having an issue with the following script.
The calling script is:
script src="//192.168.6.10/js/cYJIeCa30E.js
the resulting script needs to be parsed for cYJIeCa30E.js
in this script I have:
var scripts = document.getElementsByTagName('script');
var lastScript = scripts[scripts.length-1];
var scriptName = lastScript.src;
var name = scriptName.split('/');
alert(name);
alert(name) gives comma separated values:
http:,,192.168.6.10,js,cYJIeCa30E.js
but
alert(name[4]) gives ':' not the value after the last '/'
any idea what I am missing?
Thanks
The proper way will be like so:
var scripts = document.getElementsByTagName('script');
var lastScript = scripts[scripts.length-1];
var scriptName = lastScript.src;
var a = scriptName.split('/');
alert(a[4]); //cYJIeCa30E.js
Note You can change the variable a to any other variable. Thanks to Mike C for the MDN link

onClick JavaScript doesn't work at the first access (page access)

I have created a JavaScript function that doesn't work when we first access the web page. It will only work either by refreshing the page or accessing it for the second time.
How do I make sure that it works even when we access the page for the first time?
Here is the code:
<script type="text/javascript">
/*--adding/subtracting no. of seats and price-- */
function calculateSeat()
{
var nums = [document.getElementById('number_seat0').value, document.getElementById('number_seat1').value,document.getElementById('number_seat2').value,document.getElementById('number_seat3').value,document.getElementById('number_seat4').value];
var num = 0;
for (i=0; i < nums.length; i++) {
num += +nums[i];
}
document.getElementById('total_seat').value = num;
document.getElementById('total_amount').value = parseFloat(num * <?php echo $_SESSION['price'] ;?>).toFixed(2);
};
</script>
Check below sample
<script type="text/javascript">
function calculateSeat() {
// your php variables
var phpPrice = parseInt('<?php echo $_SESSION['price'] ;?>');
// shortcut
var $byId = document.getElementById; //faster that querySelector
// list of your DOM elements with ids
var ids = ['number_seat0', 'number_seat1', 'number_seat2', 'number_seat3', 'number_seat4'];
// function that will be used in [].reduce
// to calculate your result
function getSum(total, id) {
return total + ( +$byId( id ).value );
};
// total number
// Array.reduce docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
var result = ids.reduce(getSum);
$byId('total_seat').value = result;
$byId('total_amount').value = (result * phpPrice).toFixed(2);
}
</script>
I have actually managed to resolve this issue by simply placing the script at the bottom of the body tag instead of the head (note: where it was previously).

Getting data into an array from a separate javascript file

So I have a huge javascript file that is named locationsarray.js. I want to however call this file into this code
var myStringArray = ["Hello","World"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
//Do something
}
I'm not sure how to get that file into this array. Lastly I need to find a way to output the data within the file into html with new google.maps.LatLng() so that it would plot the points on the map. I'm sorry if this is vague but that's as far as my understanding goes. Please help!
The code for the outside javascript file is structured so:
var lsz = 10090;
var CountryTerritory = Array([lsz]);
var Region = Array([lsz]);
var City = Array([lsz]);
var Clicks = Array([lsz]);
CountryTerritory[0] = "United States";
Region[0] = "Florida";
City[0] = "Lauderdale-by-the-Sea";
Clicks[0] = "1";
CountryTerritory[1] = "United States";
Region[1] = "Florida";
City[1] = "Lake Lorraine";
Clicks[1] = "1";
CountryTerritory[2] = "United States";
Region[2] = "Florida";
City[2] = "Palmetto Estates";
Clicks[2] = "1";
In you HTML, include both scripts one after the other, starting with the outer:
<html>
<head>
<script type="text/javascript" src="./outerScript"></script>
<script type="text/javascript" src="./innerScript"></script>
...
</head>
<body>
...
This will make them use the same scope, so if the first script has var arr = []
You can use arr in the second.

Javascript Dynamic GetElementByID

I would like to use the same function on two different elements without duplicating my code and changing the id. I'd like to pass the ID as a parameter into my function but it's not working.
function getSelected(id){
var selected = new Array();
**var selObj = document.getElementById(id);** //The problem is here
var count = 0;
for (x=0; x<selObj.options.length; x++){
if (selObj.options[x].selected){
selected[count] = selObj.options.value;
count++;
}
}
alert(count)
}
Any ideas?
Looks to me as if the error is somewhere else, specificially in this line:
selected[count] = selObj.options.value;
Shouldn't that be:
selected[count] = selObj.options[x].value;
or (without the need for an extra "count" variable)
selected.push( selObj.options[x].value );
(Furthermore, you're missing a var in front of x = 0, thus making x a global variable.)

Categories

Resources