<script language="javascript">
function frompost()
{
var string=$('#indexsearch').val();
var url=string.split('=');
if(url==""){
var url=string.split('video/');
}
var finalurl='http://watchvideos.tv/watch/'+url[1];
window.location = finalurl;
//$('#srchFrm').attr('action',finalurl);
//document.srchFrm.submit();
}
</script>
I have a problem with this script - it's Ok as long as indexsearch field contains = and fails when it's supposed to work as well - with video/ in the field
Try it like this:
function frompost()
{
var str = $('#indexsearch').val(),
url = str.split(/=|video\//),
finalurl = 'http://watchvideos.tv/watch/'+url[1];
window.location = finalurl;
}
Related
I'm looking for a filter to replace "href" in a TextEntity of an API. The "text" can contains 3 different kind of URLs. After the replacement I want to open the corrected URLs in a new separate window.
I receive from the textvalue the following information:
1. link - this is an example for a all kind of external links. Can be mysite.com/mypage.html or any other valid url. Like everything with a http://, https://, ftp:// in the startof the url.
2. internal page - Can includes all other files. like mypdf.pdf or mydoc.doc or other stuff, but without http://mydomain.tdl
3. mymail#domain.tdl
I tried something but it doesn't work.
.filter('parseText', function ($sce, $sanitize) {
var mydomain = 'http://www.mydomain.tdl';
return function (text) {
var newStringUrlReplace = $sanitize(text).replace('href="','href="'+mydomain);
var regex = /href="([\S]+)"/g;
var newString = newStringUrlReplace.replace(regex, "class=\"externalURL\" onClick=\"cordova.InAppBrowser.open('$1', '_blank', 'location=yes')\"");
return $sce.trustAsHtml(newString);
}
});
I need this output the "text" ran went through the filter:
1. link
2. internal page
3. mymail#domain.tdl
To make it easier to understand:
I need a function which turns this types of URLs.
URL TO A EXTERNAL PAGE
internal page of the CMS
into
URL TO A EXTERNAL PAGE
internal page
Here's a version working based on your original code:
(function() {
angular
.module('app', ['ngSanitize'])
.controller('MainCtrl', MainCtrl)
.filter('parseText', parseText);
function MainCtrl($scope) {
$scope.array = [
'link',
'internal page',
'mymail#domain.tdl',
'URL TO A EXTERNAL PAGE',
'internal page of the CMS'
];
}
function parseText($sce) {
var myDomain = 'http://www.mydomain.tdl/';
var externalRegex = /([http|https|ftp]+:\/\/[^"]*)/g;
var internalRegex = /(href=)"([^"]*)/g;
return function(input) {
if (!input) return;
if (input.indexOf('mailto: ') !== -1) return input;
var url = '';
if (externalRegex.test(input)) {
url = input.replace(externalRegex, '$1" class="externalURL" onClick="cordova.InAppBrowser.open(\'$1\', \'_blank\', \'location=yes\')');
} else {
url = input.replace(internalRegex, '$1 ' + myDomain + '$2' + ' class="externalURL" onClick="cordova.InAppBrowser.open(\'' + myDomain + '$2' + '\', \'_blank\', \'location=yes\')');
}
return $sce.trustAsHtml(url);
}
}
})();
<!DOCTYPE html>
<html ng-app="app" >
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular-sanitize.min.js"></script>
</head>
<body ng-controller="MainCtrl">
<p ng-repeat="url in array track by $index">
<span ng-bind-html="url | parseText"></span>
</p>
</body>
</html>
Hm,
well i have a solution now...
.filter('parseText', function ($sce, $sanitize) {
return function ( text ) {
var mydomain = 'http://www.mydomain.tdl';
text = $sanitize(text);
var source,sear,repl;
var newString;
var regex = /href="([\S]+)"/g;
var extMatch = /http|https|\/\//g;
var mtMatch = /mailto:/g;
var div = document.createElement("div");
div.innerHTML = text;
var aList = div.getElementsByTagName("a");
var aListNew = new Array();
var href,t;
if(aList.length>0){
for(var i = 0; i<aList.length; i++ ){
href = aList[i].getAttribute("href");
t = aList[i].outerHTML;
t = $sanitize(t);
if(href.match(extMatch)!=null){
newString = t.replace(regex, "class=\"externalURL\" onClick=\"cordova.InAppBrowser.open('$1', '_blank', 'location=yes')\"");
} else if(href.match(mtMatch)!=null){
newString = t;
} else{
newString = t.replace(regex, "class=\"externalURL\" onClick=\"cordova.InAppBrowser.open('"+mydomain+"$1', '_blank', 'location=yes')\"");
}
source = text;
sear = t;
repl = newString;
text = text.replace(t,newString);
}
}
return $sce.trustAsHtml(text);
};
});
I have the following code working to pass a URL parameter to a form tag:
<script type="text/javascript">
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
}
function onLoad() {
var value = getQueryVariable("ID");
var e = document.getElementById('your-field');
e.value = value;
}
</script>
And...
<body onload="onLoad()">
<!-- your form and hidden field goes here -->
<input type="hidden" name="your-field" id="your-field" />
How can I pass the same value to an HTML link so that the end result would be:
<a href="http://www.mysite.com?source=[ID]" >
Where [ID] is the whatever piece of code that is needed to add the parameter to the link?
Thanks in advance.
You should give an id to you link, like this:
<a id="YOUR_ID" href="#" >
And then you have two ways to solve the problem, use pure Javascript or use jQuery:
IF you use jquery you can use your onLoad function and inside inject the following:
var url = "http://www.mysite.com?source=" + value;
$("#YOUR_ID").attr("href",url)
OR using pure javascript:
var url = "http://www.mysite.com?source=" + value;
var element = document.getElementById('YOUR_ID');
element.setAttribute("href",url)
Change the function onload to this:
function onLoad() {
var value = getQueryVariable("ID");
var e = document.getElementById('your-field');
e.value = value;
var url = "http://www.mysite.com?source=" + value;
var element = document.getElementById('YOUR_<A>_ELEMENT_ID');
element.setAttribute("href",url)
}
I'm using the piece of code that Joao Almeida suggested so his example using jQuery works good too.
Good Luck!
Here is my code, I don't understand what's wrong.
<script type="text/jquery">
function gettotalAdult()
{
//Assume form with id="fsd-bucket-calc"
var theForm = document.forms["fsd-bucket-calc"];
//Get a reference to the # of Adults & Children
var quantity = theForm.elements["totalAdult"];
var caloriesAdult = theForm.elements["caloriesAdult"];
var adultcalTotal=0;
//If the totalAdult is not blank
if(totalAdult.value!="")
{
adultcalTotal = parseInt(totalAdult.value)*parseInt(caloriesAdult.value);
}
return adultcalTotal;
}
function gettotalChild()
{
//Assume form with id="fsd-bucket-calc"
var theForm = document.forms["fsd-bucket-calc"];
//Get a reference to the # of Children
var totalChild = theForm.elements["totalChild"];
var caloriesChild = theForm.elements["caloriesChild"];
var childcalTotal=0;
//If the totalChild is not blank
if(totalChild.value!="")
{
childcalTotal = parseInt(totalChild.value)*parseInt(caloriesChild.value);
}
return childcalTotal;
}
function gettotalCalories()
{
//Here we get the total calories by calling our function
//Each function returns a number so by calling them we add the values they return together
var totalCalories = gettotalAdult() + gettotalChild();
//display the result
document.getElementById('total-req-cal').innerHTML = "The total required calories are "+totalCalories;
}
</script>
This is my HTML:
<input type="text" name="totalAdult" id="totalAdult" onkeyup="gettotalCalories()" />
This is my error:
gettotalCalories is not defined
If it helps, the script is in the head of a WordPress page. Does anyone see what I'm doing wrong?
You have <script type="text/jquery"> you may need <script type="text/javascript"> instead.
I wrote simplest extension as an exercise in JS coding. This extension checks if some user (of certain social network) is online, and then outputs his/her small image, name and online status in notification alert. It checks profile page every 2 minutes via (setTimeout), but when user becomes "online", i set setTimeout to 45 minutes.(to avoid online alerts every 2 minutes).
It works, but not exactly as i expected. I have 2 issues:
1)When certain user is online and i change user id (via options page) to check another one, it doesnt happen because it waits 45 or less minutes. i tried the following code (in options.html), but it doesnt help.
2)When i change users, image output doesnt work correctly!! It outputs image of previous user!!
How do i fix these problems??
Thanks!
options.html
<script>
onload = function() {
if (localStorage.id){
document.getElementById("identifier").value = localStorage.id;
}
else {
var el = document.createElement("div");
el.innerHTML = "Enter ID!!";
document.getElementsByTagName("body")[0].appendChild(el);
}
};
function onch(){
localStorage.id = document.getElementById("identifier").value;
var bg = chrome.extension.getBackgroundPage();
if(bg.id1){
clearTimeout(bg.id1);
bg.getdata();
}
}
</script>
<body>
<h1>
</h1>
<form id="options">
<h2>Settings</h2>
<label><input type='text' id ='identifier' value='' onchange="onch()"> Enter ID </label>
</form>
</body>
</html>
backg.html
<script type="text/javascript">
var domurl = "http://www.xxxxxxxxxxxxxx.xxx/id";
var txt;
var id1;
var id2;
var imgarres = [];
var imgarr = [];
var imgels = [];
function getdata() {
if (id1){clearTimeout(id1);}
if (id2){clearTimeout(id2);}
var url = getUrl();
var xhr = new XMLHttpRequest();
xhr.open('GET',url, true);
xhr.setRequestHeader('Cache-Control', 'no-cache');
xhr.setRequestHeader('Pragma', 'no-cache');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
txt = xhr.responseText;
var r = txt.indexOf('<b class="fl_r">Online</b>');
var el = document.createElement("div");
el.innerHTML = txt;
var n = imgprocess(el,url);
var nam = el.getElementsByTagName("title")[0].innerHTML;
if (r != -1) {
var notification = webkitNotifications.createNotification(n, nam, 'online!!' );
notification.show();
var id1 = setTimeout(getdata, 60000*45);
}
else {
var id2 = setTimeout(getdata, 60000*2);
}
}}
xhr.send();
}
function imgprocess(text,url){
imgels = text.getElementsByTagName("IMG");
for (var i=0;i< imgels.length;i++){
if (imgels[i].src.indexOf(parse(url)) != -1){
imgarr.push(imgels[i]);
}
}
for (var p=0; p< imgarr.length; p++){
if (imgarr[p].parentNode.nodeName=="A"){
imgarres.push(imgarr[p]);
}
}
var z = imgarres[0].src;
return z;
}
function getUrl(){
if (localStorage.id){
var ur = domurl + localStorage.id;
return ur;
}
else {
var notif = webkitNotifications.createNotification(null, 'blah,blah,blah', 'Enter ID in options!!' );
notif.show();
getdata();
}
}
function init() {
getdata();
}
</script>
</head>
<body onload="init();">
</body>
</html>
In options instead of clearTimeout(bg.id1); try bg.clearTimeout(bg.id1);
For image problem looks like you never clean imgarres array, only adding elements to it and then taking the first one.
PS. You code is very hard to read, maybe if you made it well formatted and didn't use cryptic variable names you would be able to find bugs easier.
UPDATE
I think I know what the problem is. When you are setting the timeout you are using local scope variable because of var keyword, so your id1 is visible only inside this function and global id1 is still undefined. So instead of:
var id1 = setTimeout(getdata, 60000*45);
try:
id1 = setTimeout(getdata, 60000*45);
Because of this if(bg.id1){} inside options is never executed.
(bg.clearTimeout(bg.id1); should work after that, but it is not needed as you are clearing the timeout inside getdata() anyway)
This is a continuation from an existing question. Javascript - Goto URL based on Drop Down Selections (continued!)
I am using dropdown selects to allow my users to build a URL and then hit "Go" to goto it.
Is there any way to add an additional function that checks the URL before going to it?
My URLs sometimes include the "+" character which I need to remove if its the last character in a URL.
So it basically needs to be "if last character is +, remove it"
This is my code:
$(window).load(function(){
$('form').submit(function(e){
window.location.href =
$('#dd0').val() +
$('#dd1').val()+
$('#dd2').val()+
$('#dd3').val();
e.preventDefault();
});
});
var url = /* whatever */;
url = url.replace(/\+$/, '');
For example,
> 'foobar+'.replace(/\+$/, '');
"foobar"
function removeLastPlus (myUrl)
{
if (myUrl.substring(myUrl.length-1) == "+")
{
myUrl = myUrl.substring(0, myUrl.length-1);
}
return myUrl;
}
$(window).load(function(){
$('form').submit(function(e){
var newUrl = $('#dd0').val() +
$('#dd1').val()+
$('#dd2').val()+
$('#dd3').val();
newUrl = removeLastPlus(newUrl);
window.location.href = newUrl;
e.preventDefault();
});
});
Found another solution using str.endsWith("str")
var str = "Hello this is test+";
if(str.endsWith("+")) {
str = str.slice(0,-1);
console.log(str)
}
else {
console.log(str);
}
Also Matt Ball's Replace method looks good. I've updated it to handle the case when there are multiple + at the end.
let str = "hello+++++++++";
str = str.replace(/\++$/, '');
console.log(str);
<script type="text/javascript">
function truncate_plus(input_string) {
if(input_string.substr(input_string.length - 1, 1) == '+') {
return input_string.substr(0, input_string.length - 1);
}
else
{
return input_string;
}
}
</script>
$(window).load(function(){
$('form').submit(function(e){
var newUrl = $('#dd0').val() +
$('#dd1').val()+
$('#dd2').val()+
$('#dd3').val();
newUrl = newUrl.replace(/\+$/, '');
window.location.href = newUrl;
e.preventDefault();
});
});
Just seems easier.
function removeLastPlus(str) {
if (str.slice(-1) == '+') {
return str.slice(0, -1);
}
return str;
}