I Have Written This Code For Link Redirection But The Problem With The Code It Triggered Only First Case It Omits Other Cases In The Switch Statement
<script type="text/javascript">
window.onload = function () {
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
var string = links[i].href; //href value
var str = string;
var spl = string.split("/");
switch (spl[2]) {
case 'www.google.com':
var str1 = "http://yahoo.com";
links[i].target = "_blank";
var m = links[i].addEventListener("mouseup", function () {
window.open(str1)
}, false);
return (m);
break;
case 'www.ebay.com':
var str1 = "http://yahoo.com";
links[i].target = "_blank";
var m = links[i].addEventListener("mouseup", function () {
window.open(str1)
}, false);
return (m);
break;
default:
links[i].href = string;
}
}
}
</script>
HTML:
www.google.com</br>
www.ebay.com</br>
Remove return(m) from above code. It should work fine. It's return after first call.
Since you have return(m); here, it returns from there and do not execute the rest of the code. you can test it by putting alert("Hi"); after the return statement. This alert should not work for your code.
<script type="text/javascript">
window.onload = function () {
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
var string = links[i].href; //href value
var str = string;
var spl = string.split("/");
switch (spl[2]) {
case 'www.google.com':
var str1 = "http://yahoo.com";
links[i].target = "_blank";
var m = links[i].addEventListener("mouseup", function () {
window.open(str1)
}, false);
break;
case 'www.ebay.com':
var str1 = "http://yahoo.com";
links[i].target = "_blank";
var m = links[i].addEventListener("mouseup", function () {
window.open(str1)
}, false);
break;
default:
links[i].href = string;
}
}
}
</script>
Related
Javascript match function not working in my for loop properly. The match function works only once.
Not functioning code:
<script type = 'text/javascript' >
var numposts = 5;
function labelthumbs(json) {
for (var i = 0; i < numposts; i++) {
var entry = json.feed.entry[i];
var posttitle = entry.title.$t;
var postcontent = entry.content.$t;
url = postcontent.match(/pname='(.+?)'/);
if (url){
document.write('<td>'+url[1]+'</td>');
}else {
document.write('<td> bb</td>');
}
}
}
</script>
<script type="text/javascript" src="https://www.ibpsonline.in/feeds/posts/default/-/IBPS?published&alt=json-in-script&callback=labelthumbs"></script>
It does work on all the post, however only one of the post has pname defined with single quote. You can change your regex to the check for double quote too like postcontent.match(/pname=['"](.+?)['"]/i);
<script type = 'text/javascript' >
var numposts = 5;
function labelthumbs(json) {
for (var i = 0; i < numposts; i++) {
var entry = json.feed.entry[i];
var posttitle = entry.title.$t;
var postcontent = entry.content.$t;
url = postcontent.match(/pname=['"](.+?)['"]/i);
if (url){
document.write('<td>'+url[1]+'</td>');
}else {
document.write('<td> bb</td>');
}
}
}
</script>
<script type="text/javascript" src="https://www.ibpsonline.in/feeds/posts/default/-/IBPS?published&alt=json-in-script&callback=labelthumbs"></script>
Just trying to make a random password generator and I'm not getting any output in my alert I'm using to test. Not getting any errors so I'm not sure what my mistake is.
"use strict";
var $ = function(id) { return document.getElementById(id); };
var getRandomNumber = function() {
var num = parseInt$("num").value = "";
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < num.length; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
alert(text).toString());
};
var clearFields = function() {
$("num").value = "";
$("password").value = "";
$("num").focus();
};
window.onload = function() {
$("generate").onclick = getRandomNumber;
$("clear").onclick = clearFields;
$("num").focus();
};
You do have an error.
There is an extra ) in this statement alert(text).toString());.
I'm trying to get page speed score for both: desktop and mobile and then pass them to #pgscore && #pgscorem inputs.
Problem is that at the end of script I get always var device == 'mobile'. It looks like it skips for loop. Any idea how could I fix it?
for (var r = 0; r < 2; r++) {
var API_KEY = 'mykey';
var device = '';
switch (r) {
case 0: device='desktop'; break;
case 1: device='mobile'; break;
};
alert(device);
var URL_TO_GET_RESULTS_FOR = 'http://www.stackoverflow.com' + '&strategy=' + device;
var API_URL = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?';
var CHART_API_URL = 'http://chart.apis.google.com/chart?';
var callbacks = {}
function runPagespeed() {
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
var query = [
'url=' + URL_TO_GET_RESULTS_FOR,
'callback=runPagespeedCallbacks',
'key=' + API_KEY,
].join('&');
s.src = API_URL + query;
document.head.insertBefore(s, null);
}
function runPagespeedCallbacks(result) {
if (result.error) {
var errors = result.error.errors;
for (var i = 0, len = errors.length; i < len; ++i) {
if (errors[i].reason == 'badRequest' && API_KEY == 'yourAPIKey') {
alert('Please specify your Google API key in the API_KEY variable.');
} else {
alert(errors[i].message);
}
}
return;
}
for (var fn in callbacks) {
var f = callbacks[fn];
if (typeof f == 'function') {
callbacks[fn](result);
}
}
}
setTimeout(runPagespeed, 0);
callbacks.displayPageSpeedScore = function(result) {
var score = result.score;
Function countinues down there. Problem is here... Why I can't get variable device == 'desktop' first and then in second for loop 'mobile'? I get always 'mobile'.
switch (device) {
case 'desktop': $('#pgscore').val(score); break;
case 'mobile': $('#pgscorem').val(score); break;
};
};
};
Since I need only score, I'm using php
$jsonurl="https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url=$url&locale=pl_pl&$key";
$json = file_get_contents($jsonurl);
$json_output = json_decode($json, true);
/* print_r(array_values($json_output));*/
echo $json_output['score'];
I have a html tag like this.
<a class="employee_details" target="_blank" href="index1.php?name=user1&id=123">User</a>
I need to get the two parameter values in jquery
<script type="text/javascript">
$(function () {
$('.employee_details').click(function () {
var status_id = $(this).attr('href').split('name');
alert(status_id[0]);
});
});
</script>
Any help in getting both the parameter values in two variables in javascript.
I want to get user1 and 123 in two variables using jQuery
Thanks
Kimz
You can use URLSearchParams as a most up-to-date and modern solution:
let href = $(this).attr('href');
let pars = new URLSearchParams(href.split("?")[1]);
console.log(pars.get('name'));
Supported in all modern browsers and no jQuery needed!
Original answer:
Try this logic:
var href = $(this).attr('href');
var result = {};
var pars = href.split("?")[1].split("&");
for (var i = 0; i < pars.length; i++)
{
var tmp = pars[i].split("=");
result[tmp[0]] = tmp[1];
}
console.log(result);
So you'll get the parameters as properties on result object, like:
var name = result.name;
var id = result.id;
Fiddle.
An implemented version:
var getParams = function(href)
{
var result = {};
var pars = href.split("?")[1].split("&");
for (var i = 0; i < pars.length; i++)
{
var tmp = pars[i].split("=");
result[tmp[0]] = tmp[1];
}
return result;
};
$('.employee_details').on('click', function (e) {
var params = getParams($(this).attr("href"));
console.log(params);
e.preventDefault();
return false;
});
Fiddle.
$(function() {
$('.employee_details').on("click",function(e) {
e.preventDefault(); // prevents default action
var status_id = $(this).attr('href');
var reg = /name=(\w+).id=(\w+)/g;
console.log(reg.exec(status_id)); // returns ["name=user1&id=123", "user1", "123"]
});
});
// [0] returns `name=user1&id=123`
// [1] returns `user1`
// [2] returns `123`
JSFiddle
NOTE: Better to use ON method instead of click
Not the most cross browser solution, but probably one of the shortest:
$('.employee_details').click(function() {
var params = this.href.split('?').pop().split(/\?|&/).reduce(function(prev, curr) {
var p = curr.split('=');
prev[p[0]] = p[1];
return prev;
}, {});
console.log(params);
});
Output:
Object {name: "user1", id: "123"}
If you need IE7-8 support this solution will not work, as there is not Array.reduce.
$(function () {
$('.employee_details').click(function () {
var query = $(this).attr('href').split('?')[1];
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
var varName = decodeURIComponent(pair[0]);
var varValue = decodeURIComponent(pair[1]);
if (varName == "name") {
alert("name = " + varValue);
} else if (varName == "id") {
alert("id = " + varValue);
}
}
});
});
It's not very elegant, but here it is!
var results = new Array();
var ref_array = $(".employee_details").attr("href").split('?');
if(ref_array && ref_array.length > 1) {
var query_array = ref_array[1].split('&');
if(query_array && query_array.length > 0) {
for(var i = 0;i < query_array.length; i++) {
results.push(query_array[i].split('=')[1]);
}
}
}
In results has the values. This should work for other kinds of url querys.
It's so simple
// function to parse url string
function getParam(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(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
// your code
$(function () {
$('.employee_details').click(function (e) {
e.preventDefault();
var qs = getParam($(this).attr('href'));
alert(qs["name"]);// user1
var status_id = $(this).attr('href').split('name');
});
});
here is some JavaScript that I am testing:
var filters;
$(".arrow-up").unbind("click").click(function (event) {
var clickedArrow = $(this);
var id = clickedArrow.attr('data-id');
var select = document.getElementById(id);
var option = select.options[select.selectedIndex];
var filters;
$(".search").each(function () {
var SearchText = this.value;
var id;
if (!checkEmpty(SearchText)) {
switch (this.id) {
case "one":
id = 1;
break;
case "two":
id = 2;
break;
case "three":
id = 3;
break;
case "four":
id = 4;
break;
case "five":
id = 5;
break;
case "six":
id = 6;
break;
case "seven":
id = 7;
break;
case "eight":
id = 8;
break;
}
var filter = document.getElementById(id);
var filterOption = filter.options[filter.selectedIndex].text;
filters += '&col=' + filterOption;
filters += '&col=' + SearchText;
}
});
var cols;
/* Get all of the drop downs for the columns */
for (var i = 1; i <= 8; i++) {
var txt;
var colVal = document.getElementById(i);
txt = colVal.options[colVal.selectedIndex].text;
cols += '&col=' + txt;
}
var url = '/AccountManagement/SortAscend';
var formData = {
option: option,
filters: filters,
cols: cols
}
var posting = $.post(url, formData, function (data, textstatus) {
//spinner = new Spinner(opts).spin(target);
StartSpinner();
}, "json");
posting.done(function (data) {
ReloadTable(data);
StopSpinner();
});
});
When I debug this in chrome, it skips the $(".search").each(function() { part - it just skips to the end of the method, therefore it never goes over any of the eight items and the filters variable remains "undefined" I am not sure why.
Please try these changes and tell me if that still just goes by the each. Because I am using each just as you do and it works perfectly. Maybe I would also change the switch to an "associative array"
var numbers = {"one":1,"two":2...};
And then
id = numbers[$(this).attr("id")]
But first try the code below.
var filters;
$(".arrow-up").unbind("click").click(function (event) {
var clickedArrow = $(this);
var id = clickedArrow.data('id');
var select = $('#'+id);
var option = $(select + '> option:selected');
var filters;
$(".search").each(function () {
var SearchText = $(this).val();
var id;
if (!checkEmpty(SearchText)) {
switch ($(this)attr("id")) {
case "one":
id = 1;
break;
case "two":
id = 2;
break;
case "three":
id = 3;
break;
case "four":
id = 4;
break;
case "five":
id = 5;
break;
case "six":
id = 6;
break;
case "seven":
id = 7;
break;
case "eight":
id = 8;
break;
}
var filter = document.getElementById(id);
var filterOption = filter.options[filter.selectedIndex].text;
filters += '&col=' + filterOption;
filters += '&col=' + SearchText;
}
});
var cols;
/* Get all of the drop downs for the columns */
for (var i = 1; i <= 8; i++) {
var txt;
var colVal = document.getElementById(i);
txt = colVal.options[colVal.selectedIndex].text;
cols += '&col=' + txt;
}
var url = '/AccountManagement/SortAscend';
var formData = {
option: option,
filters: filters,
cols: cols
}
var posting = $.post(url, formData, function (data, textstatus) {
//spinner = new Spinner(opts).spin(target);
StartSpinner();
}, "json");
posting.done(function (data) {
ReloadTable(data);
StopSpinner();
});
});