Get html data attributes from URL - javascript

I want to send prodName and prodItem into a URL that will be captured by product.html so when a user clicks on a product (index.html), a URL will be created and that URL will be used but on product.html. I want to catch prodName and proItem and put the text in the product.html but the value will be null.
index.html
$(".product-item").each(function(index, value) {
var prodName = $(this).children("h2").attr("data-prodname");
var prodItem = $(this).children("h2").attr("data-proditem");
var link = $("<a href='product.html?prodName=" + prodName + "&prodItem=" + prodItem + "'/>");
console.log(prodName);
console.log(prodItem);
$(this).children("img").wrap(link);
});
})
product.html
$.urlParam = function (parameterName) {
var results = new RegExp('[\?&]' + parameterName + '=([^&#]*)').exec(window.location.href);
if (results === null) {
return null;
} else {
return decodeURI(results[1]) || 0;
}
}
var adminSerial = $.urlParam('ProdName');
var dashboardName = $.urlParam('ProdItem');
$('#product').html("The text is " + adminSerial);

I put this code on pruduct.html and now it works.
var getParams = function (url) {
var params = {};
var parser = document.createElement('a');
parser.href = url;
var query = parser.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
params[pair[0]] = decodeURIComponent(pair[1]);
}
return params;
};
var mylocation ={};
var mylocation = getParams(window.location.href);
console.log(mylocation.prodName);
$('#product').html(mylocation.prodName);
$('#item').html(mylocation.prodItem);

Related

Javascript not working for first time in my HTML File

I have checked and tried various solutions provided here previously but still my javascript is not working for the first time. If I refresh the page manually only once, my javascript gets active in a very fine manner.
After refreshing the page, I am very fine with javascript but if I put this same script in other new HTML file then same issue found on loading the page first time.
My script actually search for a text in the HTML file and change the text style every where it is found in that page.
Following is the script that I have used::
<script type="text/javascript">
//<![CDATA[
function Hilitor(id, tag){
var targetNode = document.getElementById(id) || document.body;
var hiliteTag = tag || "EM";
var skipTags = new RegExp("^(?:" + hiliteTag + "|SCRIPT|FORM|SPAN)$");
var colors = ["#ff6", "#a0ffff", "#9f9", "#f99", "#f6f"];
var wordColor = [];
var colorIdx = 0;
var matchRegex = "";
var openLeft = false;
var openRight = false;
// characters to strip from start and end of the input string
var endCharRegex = new RegExp("^[^\\\w]+|[^\\\w]+$", "g");
// characters used to break up the input string into words
var breakCharRegex = new RegExp("[^\\\w'-]+", "g");
this.setMatchType = function(type){
switch(type) {
case "left":
this.openLeft = false;
this.openRight = true;
break;
case "right":
this.openLeft = true;
this.openRight = false;
break;
case "open":
this.openLeft = this.openRight = true;
break;
default:
this.openLeft = this.openRight = false;
}
};
this.setRegex = function(input){
input = input.replace(endCharRegex, "");
input = input.replace(breakCharRegex, "|");
input = input.replace(/^\||\|$/g, "");
if(input) {
var re = "(" + input + ")";
if(!this.openLeft) re = "\\b" + re;
if(!this.openRight) re = re + "\\b";
matchRegex = new RegExp(re, "i");
return true;
}
return false;
};
this.getRegex = function(){
var retval = matchRegex.toString();
retval = retval.replace(/(^\/(\\b)?|\(|\)|(\\b)?\/i$)/g, "");
retval = retval.replace(/\|/g, " ");
return retval;
};
// recursively apply word highlighting
this.hiliteWords = function(node){
if(node === undefined || !node) return;
if(!matchRegex) return;
if(skipTags.test(node.nodeName)) return;
if(node.hasChildNodes()) {
for(var i=0; i < node.childNodes.length; i++)
this.hiliteWords(node.childNodes[i]);
}
if(node.nodeType == 3) { // NODE_TEXT
if((nv = node.nodeValue) && (regs = matchRegex.exec(nv))) {
if(!wordColor[regs[0].toLowerCase()]) {
wordColor[regs[0].toLowerCase()] = colors[colorIdx++ % colors.length];
}
var match = document.createElement(hiliteTag);
match.appendChild(document.createTextNode(regs[0]));
match.style.backgroundColor = wordColor[regs[0].toLowerCase()];
match.style.fontStyle = "inherit";
match.style.fontWeight = "900";
match.style.color = "#000";
var after = node.splitText(regs.index);
after.nodeValue = after.nodeValue.substring(regs[0].length);
node.parentNode.insertBefore(match, after);
}
};
};
// remove highlighting
this.remove = function(){
var arr = document.getElementsByTagName(hiliteTag);
while(arr.length && (el = arr[0])) {
var parent = el.parentNode;
parent.replaceChild(el.firstChild, el);
parent.normalize();
}
};
// start highlighting at target node
this.apply = function(input){
this.remove();
if(input === undefined || !input) return;
if(this.setRegex(input)) {
this.hiliteWords(targetNode);
}
};
}
function getParameterByName(name, url) {
if (!url) {
url = window.location.href;
}
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var query = getParameterByName('query');
var myHilitor = new Hilitor("spnId");
myHilitor.apply(query);
//]]>
</script>

Prase query string from url javascript

my url look like http://localhost:13562/Student/RefreshStudents?sort=FirstName&sortdir=ASC&page=1
now i am looking for a function where i will pass url and query string name then that should return value.
so i did it this way but not working.
function getQueryVariable(url,variable) {
var query = url;
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
}
calling like this way
var x='http://localhost:13562/Student/RefreshStudents?sort=FirstName&sortdir=ASC&page=1'
alert(getQueryVariable(x,'sort'));
alert(getQueryVariable(x,'sortdir'));
alert(getQueryVariable(x,'page'));
where i made the mistake?
EDIT
working code
$.urlParam = function(url,name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(url);
if (results==null){
return null;
}
else{
return results[1] || 0;
}
}
var x='http://localhost:13562/Student/RefreshStudents?sort=FirstName&sortdir=ASC&page=1'
alert($.urlParam(x,'sort'));
alert($.urlParam(x,'sortdir'));
alert($.urlParam(x,'page'));
https://jsfiddle.net/z99L3985/1/
thanks
may be the following will help
function getUrlVars(url) {
var vars = {};
var parts = url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var x='http://localhost:13562/Student/RefreshStudents?sort=FirstName&sortdir=ASC&page=1';
var queryVars = getUrlVars(x);
alert(queryVars['sort']);
alert(queryVars['sortdir']);
alert(queryVars['page']);
I just get this from somewhere else as well..
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
console.log(vars);
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] === variable){return pair[1];}
}
return(false);
}
so far its doing its job.
with url: "http://urlhere.com/general_journal?from=01%2F14%2F2016&to=01%2F14%2F2016&per_page=25&page=2"
if im going to get the 'page' variable result would be : `2`
console.log(getQueryVariable('page'));
my query variable is only getting the search.substring(1) part of the the url so basically it only gets from=01%2F14%2F2016&to=01%2F14%2F2016&per_page=25&page=2 part of the url then from that it splits it and then return the value of the string parameter you specified on the function call getQueryVariable('page') for example.
Maybe this helps
var getUrlVars = function(url){
var vars = [], hash;
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++){
hash = hashes[i].split('=');
vars.push(decodeURIComponent(hash[0]));
vars[decodeURIComponent(hash[0])] = decodeURIComponent(hash[1]);
}
if(vars[0] == url){
vars =[];
}
return vars;
}
Then in your code
var params = getUrlVars("http://localhost:13562/Student/RefreshStudents?sort=FirstName&sortdir=ASC&page=1");
console.log(params["sort"]) // FirstName

Synchronous javascript does not work

I have a script which generates an array of audio files to be played on the click of a button. I am trying to use synchronous JS in order to change the values of some global variables and have been testing for changes with alerts but I get 'undefined' as a result (or my popups do not show).
My code:
jQuery.ajaxSetup({async:false});
var s;
var group;
var curr_rec;
var curr_start = 1;
var curr_end;
var curr_s_obj;
var recs;
var sync = new Array();
var sync_group = new Array();
var check_rec;
var check_id;
var check_start;
var check_end;
var loaded = 0;
var s_obj;
function compare(a,b){
if(a.fields.start_time<b.fields.start_time)
return -1;
if(a.fields.start_time>b.fields.start_time)
return 1;
return 0;
}
function process_data(recs){
for(var i=0;i<recs.length;i++){
check_rec = recs[i];
check_id = check_rec.fields.file_ID;
check_start = check_rec.fields.start_time;
check_end = check_rec_fields.end_time;
if((curr_start.getTime() <= check_start.getTime() && check_end.getTime()<= curr_end.getTime()) ||
(curr_start.getTime()>=check_start.getTime() && curr_start.getTime()<=check_end.getTime()) ||
(curr_end.getTime()>=check_start.getTime() && curr_end.getTime()<=check_end.getTime())
)
{
//diff = (check_start.getTime() - curr_start.getTime())/1000;
//check_rec["difference"] = diff;
sync.push(check_rec);
}
}
}
function load_data(sync){
var diff;
var last = sync[sync.length-1];
for(var j=0;j<sync.length-1;j++){
s_obj = new buzz.sound(sync[i].fields.rec_file);
sync_group.push(s_obj);
diff = (last.fields.start_time.getTime() - sync[i].fields.start_time.getTime())/1000;
if(diff>=0){
s_obj.setTime(diff);
}
else{
alert("error");
}
}
loaded = 1;
}
function synchronise(id){
$.ajax({
type:"GET",
url:"/webapp/playSound:" + id,
success: function(data){
curr_rec = eval("(" + data + ")");
curr_start = curr_rec.fields.start_time;
curr_end= curr_rec.fields.end_time;
curr_s_obj = new buzz.sound(curr_rec.fields.rec_file);
});
alert("ggo");
$.ajax(
type:"GET",
url:"/webapp/getRecs",
success: function(data){
recs = eval("("+ data +")");
process_data(recs);
});
alert(curr_start);
sync = sync.sort(compare);
load_data(sync);
var s1 = new buzz.sound( "../../static/data/second_audio.ogg");
s = new buzz.sound( "../../static/data/" + id +".ogg"); //curr_rec.fields.rec_file
/*
sync_group.push(s);
s.setTime(20.5);
sync_group.push(s1);
*/
group = new buzz.group(sync_group);
}
function playS(id){
if(loaded==0)
synchronise(id);
group.togglePlay();
}
function stopS(){
group.stop();
}

if querystring value exists remove param and reset url

my url looks something like this
/myurl?code1=abcde&code2=fghijk&code3=lmnop&code4=qrstu&code5=vwxyz (up to max of 5 code variables)
I have an onclick event where I get the code variable, eg in example above it returns 'fghijk', but I don't know the param, eg code2. So I want to do two things:
1) find and remove the param & value from my url (if my onclick variable returns 'fghijk', in the above example my url becomes, /myurl?code1=abcde&code3=lmnop&code4=qrstu&code5=vwxyz)
2) after this I want to reset the param numbers so that my code params are sequential beginning from 1, so after number 1 above executes my url should become /myurl?code1=abcde&code2=lmnop&code3=qrstu&code4=vwxyz
$('.myelement').on('click', function() {
var url = $('.myelement a').attr('href');
var codevar = $('.myelement span').text();
if(url +'contains('+codevar+')') {
// strip the param and variable from the url here
// now reset the url so code params are in number sequence
}
});
you could do something like this:
$('.myelement').on('click', function() {
var url = $('.myelement a').attr('href');
var codevar = $('.myelement span').text();
if(url.match(codevar)) {
var queryString = url.substring(url.indexOf("?") + 1);
var params = queryString.split("&");
var codeIndex = 1;
var newQuery = "";
for (var i = 0; i < params.length; i++) {
if (!params[i].match(codevar)) {
newQuery += params[i].replace(/code[0-9]/, "code" + codeIndex);
codeIndex++;
if (i < params.length - 1) {
newQuery += "&";
}
}
}
url = url.replace(queryString, newQuery).replace(/&$/, ""); //new query string with the sequential parameters
}
});
Hope this helps.
Regards,
Marcelo
var codevar = 'fghijk';
var url = $('.myelement a').attr('href');
var param = '&'+url.substring(url.indexOf('?')+1);
url = url.substring(0,url.indexOf('?')+1);
if(param.indexOf(codevar) > -1) {
var arr = param.split("&code");
param = '';
for(var i = 1;i<arr.length;i++){
if(codevar == arr[i].substring(2))
arr.splice(i, 1);
param += 'code'+i+'='+arr[i].substring(2);
if(i != arr.length-1)
param +='&';
}
$('.myelement a').attr('href',url+param);
Example:
http://jsfiddle.net/trevordowdle/b9Hmb/1/
You could split the url with the param as key.
var el = $('.myelement'),
out = $("#output");
el.on('click', function (ev) {
ev.preventDefault();
var href = el.find("a").prop("href"),
param = el.find("span").text(),
idx = href.indexOf(param),
arr = [], url;
if (idx > -1) {
arr = href.split(param); // split href[0] param href[1]
url = arr.join("mynewvalue");
out.text(url);
}
});
DEMO : http://jsfiddle.net/tive/EAsw3/

Update javascript table: Uncaught TypeError: Object [object Object] has no method 'tableRow'

I'm making a contacts app that updates a table with the users input but can't seem to get the table to update once I input data I only get the error above. Not sure how what I've to change the method to, I've tried lots of different functions etc., but no luck.
var nameField, addressField, emailField, postcodeField;
function twoDigit(v){
if(v.toString().length < 2){
return "0"+v.toString();
} else {
return v.toString();
}
}
var Contact = function(name, address, email, postcode){
this.name = name;
this.address = address;
this.email = email;
this.postcode = postcode;
this.completed = false;
};
var contacts = [];
Contact.prototype.toString = function(){
var s = this.name + '\n' + this.address + '\n' + this.email + + '/n'
+ this.postcode.toString() + '\n';
if(this.completed){
s += "Completed\n\n";
} else {
s += "Not Completed\n\n";
}
return s;
};
var addContact = function(nameField, addressField, emailField, postcodeField){
a = new Contact(nameField.value, addressField.value,
emailField.value, postcodeField.value);
contacts.push(a);
};
var clearUI = function(){
var white = "#fff";
nameField.value = "";
nameField.style.backgroundColor = white;
addressField.value = "";
addressField.style.backgroundColor = white;
emailField.value = "";
emailField.style.backgroundColor = white;
postcodeField.value = "";
postcodeField.style.backgroundColor = white;
};
var updateList = function(){
var tableDiv = document.getElementById("table"),
table = "<table border='1'><thead><th>Name</th>
<th>Address</th><th>Email</th><th>Postcode</th><th>Completed</th></thead>";
for(var i=0, j=contacts.length; i<j; i++){
var contacts1 = contacts[i];
table += contacts1.tableRow();
}
table+="</table>";
tableDiv.innerHTML = table;
};
var add = function(){
addContact(nameField, addressField, emailField, postcodeField);
clearUI();
updateList();
};
var cancel = function(){
clearUI();
updateList();
};
window.onload = function(){
nameField = document.getElementById("name");
addressField = document.getElementById("address");
emailField = document.getElementById("email");
postcodeField = document.getElementById("postcode");
okButton = document.getElementById("ok");
okButton.onclick = add;
cancelButton = document.getElementById("cancel");
cancelButton.onclick = cancel;
clearUI();
};
var showTable = function(){
var tableDiv = document.getElementById("table"),
table = "<table border='1'><thead><th>Name</th>
<th>Address</th><th>Email</th> <th>Postcode</th></thead>";
for(var i=0, j=contacts.length; i<j; i++){
var contacts1 = contacts[i];
table += contacts1.tableRow();
}
table+="</table>";
tableDiv.innerHTML = table;
};

Categories

Resources