How to add JavaScript if the URL has a certain word? - javascript

I want to add the the following jQuery to the following pages only.
http://www.mywebsite.com/check-8.asp
http://www.mywebsite.com/edit-8.asp
http://www.mywebsite.com/cart-8.asp
So this means I want to add it where URL string contains either check-8, cart-8 or edit-8.
What is the best way with jQuery or JavaScript?
var text = $('#system td.td-main').html();
if (text != null)
{
var newtext = text.replace("Pris","<div id=\"pricebox\">Pris").replace("mva\)","mva\)</div>");
$('#system td.td-main').html(newtext);
}
Thanks in advance.

if(location.pathname.indexOf('check-8') > 0 || location.pathname.indexOf('cart-8') > 0 || location.pathname.indexOf('edit-8') > 0){
//your code here
}

Or you can use the following:
function testForCheckEditCart() {
var patt = /(check|edit|cart)-8/i;
return patt.test(location.href);
}

If you want a pure JavaScript solution, use the window.location property:
if (window.location.href.match(/(check|cart|edit)-8/).length > 0) {
// do your stuff
}
You can use the string.match method to check if it matches a Regex. You can also factor it out if you need to know which one it is:
var matches = window.location.href.match(/(check|cart|edit)-8/);
if (matches.length > 0) {
var action = matches[1]; // will be check, cart or edit
}

Related

Check for open tag in textarea

I'm making a Ukrainian phonetic keyboard. People type in English, and the letters automatically change to the corresponding Ukrainian characters. However, when I'm using it, I sometimes need to write myself notes in English (they serve the same purpose as comments in code- for other people and for myself).
I'd like to indicate the start of a comment with a tag ("<"). How can I check if there's currently an open tag?
I'm thinking something like this:
if (number of "<" is greater than ">") {//if a tag has been opened and not closed
//disable translation, type in English
}
I understand how to disable the translation- however, I'm unsure about the
"if"
How can I check if
number of "<" is greater than ">"
Thanks!
You can count number of specific characters using .match()
In your case
var string = "<<<>>";
if ((string.match(/</g)||[]).length > (string.match(/>/g)||[]).length) {
console.log("More");
}
else {
console.log("Less or equal");
}
counting each of them is like below
var countGreaterThan = (temp1.match(/</g) || []).length;
var countLessThan = (temp1.match(/</g) || []).length;
and temp is the string value of the textarea
Depending on where your data is, you can do:
var data = document.querySelector('#data-container').innerHTML;
var isOpenTagPresent = getSymbolCount('<') > getSymbolCount('<');
if(isOpenTagPresent) {
//execute your logic
}
function getSymbolCount(symbol) {
var count = 0;
for(var i = 0; i < data.length; ++i) {
if(data[i] === symbol) {
count++;
}
}
return count;
}
Hope this helps, cheers!

using indexof on query string parameter with multiple values

I'm showing hidden divs based on the contents of a query string parameter that's being parsed from another page, using indexof to check if a value is present - then displaying that value's corresponding div.
Query string: index.html?q1=bag1,bag2,bag3
var urlParams;
(window.onpopstate = function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
Then using indexOf to show divs based on the value:
if ((urlParams["q1"]).indexOf("bag1") >= 0) {
$(".content1").show();
} else
if ((urlParams["q1"]).indexOf("bag2") >= 0) {
$(".content2").show();
} else
if ((urlParams["q1"]).indexOf("bag3") >= 0) {
$(".content3").show();
}
However, it's only displaying the first div and not the second or third.
I know it'll be a simple solution - bit stuck on it. Any help appreciated!
You need to remove the else clauses, as the interpreter will stop after the first if is true. So your code should look like
if ((urlParams["q1"]).indexOf("bag1") >= 0) {
$(".content1").show();
}
if ((urlParams["q1"]).indexOf("bag2") >= 0) {
$(".content2").show();
}
if ((urlParams["q1"]).indexOf("bag3") >= 0) {
$(".content3").show();
}
I'd suggest using your bag1 etc values as IDs instead of classes to identify the separate content sections. If a class only identifies one element then you're doing it wrong.
You should then tag all of your content elements with the same class (e.g. content) so that you can .hide() on all of them before running .show on the ones that you want to remain visible. As written any elements that are already visible will remain visible when you pop state even if they weren't supposed to be.
Your parameter extracting code is OK, but having got your q1 value I would just do this:
var q1 = urlParams.q1;
if (q1 !== undefined) {
$('.content').hide(); // show nothing
q1.split(',').forEach(function(id) {
$('#' + id).show();
});
}
thereby removing all of the (broken) conditional logic.

Javascript If Statement, not working

I have a JavaScript function that I want to use to get the current URL and if there is any value after the = then it should placed in a textbox that has an ID of name. However at the moment, when I open the page, the full URL is displayed in the text box, so I want to have some kind of condition where it only displays if there is a value after the only =
function DisplayProdCod(value) {
var URLstring = window.location.href;
if (URLstring.indexOf('=')) {
var ProductCode = URLstring.split("=").pop();
document.getElementById('Name').value = ProductCode;
document.getElementById('Name').style.backgroundColor = #C8C8FF;
}
}
A typical URL could be
http://brmappsvr:7018/Enquiries/CMFRAME.html
or
http://brmappsvr:7018/Enquiries/CMFRAME.html?ProductCode=1BLK970/07
Change the condition to check if returns -1, like so:
function DisplayProdCod(value) {
var URLstring = window.location.href;
if (URLstring.indexOf('=') != -1) {
var ProductCode = URLstring.split("=").pop();
document.getElementById('Name').value = ProductCode;
document.getElementById('Name').style.backgroundColor = #C8C8FF;
}
}
The indexOf function returns -1 when the character you are searching for does not occur in the string. And as every number (except 0) is truthy the condition in your if-condition is met everytime. So you should better check if the index is greater than -1, i.e.
if (URLstring.indexOf('=') > -1) {
...
}
Just do URLstring.split('=') anyway, then check the length of the result. If it's 2, work with result[1], otherwise something went wrong.
Try this
Example
html
<input type="text" id="Name"/>
<input type="button" onclick="DisplayProdCod();" value="click"/>
JS
function DisplayProdCod() {
var URLstring = window.location.href;
alert(URLstring);
if (URLstring.indexOf("=") > -1) {
var ProductCode = URLstring.split("=").pop();
document.getElementById("Name").value = ProductCode;
document.getElementById('Name').style.backgroundColor ="#C8C8FF";
}
}
See the DEMO in this demo i am searching a string "fiddle" you can replace it with "=" in your program
Note:
in your code you are missed a double quotes when you setting a background colour
it should be like below
document.getElementById('Name').style.backgroundColor ="#C8C8FF";

How to check if a div contains a certain word and check if that certain word matchs a var?

So I am using Node.JS and doing a small multiplayer project.
Of course I'm using JavaScript for a lot of things.
I would like to check if a div contains a certain word and if that certain word matches a variable.
How would I do this with JavaScript?
I want something like:
var teststring = "hi";
if "<div id="test">" contents matches "teststring"
{
}
I also have jQuery so that's an option too!
I'm new to JavaScript so please fire away!
This was my attempt but it didn't work:
var socket = io.connect('http://*');
socket.on('field', function (data) {
if ($("#userid").text().indexOf(data) > -1)
{
window.alert('lol');
console.log(data);
$("#field").html(data);
}
else
{
window.alert("Something has gone wrong with the node server...");
}
});
Just check the contents of the div with the text() function of jQuery, like this:
var teststring = "hi";
if ($("#test").text().indexOf(teststring) > -1)
{
alert("Match!");
}
to get the value of the div you can use
var divValue = $('#test').text();
var teststring = "hi";
and to match with the variable;
if(divValue === teststring ){
alert('Two variables are matching !!');
}
and to search a String contains a substring you can use;
if (divValue.indexOf(teststring ) >= 0)
{
alert('Two variables are matching !!');
}
please visit http://jsfiddle.net/dennypanther/ojmyobL8/
In JavaScript u can do it lyk this :
var teststring = "hi";
var div=document.getElementById('test').innerHTML;
if(div.indexOf(testString) > -1 ){
// your code goes here
}

Regex to check if http or https exists in the string

So i have this code:
function validateText(str)
{
var tarea = str;
var tarea_regex = /^(http|https)/;
if(tarea_regex.test(String(tarea).toLowerCase()) == true)
{
$('#textVal').val('');
}
}
This works perfectly for this:
https://hello.com
http://hello.com
but not for:
this is a website http://hello.com asdasd asdasdas
tried doing some reading but i dont where to place * ? since they will check the expression anywhere on the string according here -> http://www.regular-expressions.info/reference.html
thank you
From the looks of it, you're just checking if http or https exists in the string. Regular expressions are a bit overkill for that purpose. Try this simple code using indexOf:
function validateText(str)
{
var tarea = str;
if (tarea.indexOf("http://") == 0 || tarea.indexOf("https://") == 0) {
// do something here
}
}
Try this:
function validateText(string) {
if(/(http(s?)):\/\//i.test(string)) {
// do something here
}
}
The ^ in the beginning matches the start of the string. Just remove it.
var tarea_regex = /^(http|https)/;
should be
var tarea_regex = /(http|https)/;
((http(s?))\://))
Plenty of ideas here : http://regexlib.com/Search.aspx?k=URL&AspxAutoDetectCookieSupport=1
Have you tried using a word break instead of the start-of-line character?
var tarea_regex = /\b(http|https)/;
It seems to do what I think you want. See here: http://jsfiddle.net/BejGd/

Categories

Resources