Javascript If Statement, not working - javascript

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";

Related

Javascript to verify specific String from textbox

Here what the textbox result looks like,
Please add the following DNS entries
144.68.238.87 name.domain
144.68.238.88 name.domain
144.68.238.89 name.domain
The goal is to validate name.domain by making sure that the user replace name.domain to server name on textbox before submit it. If the user doesn't replace name.domain with their server name, then it will send alert message and return false until user replace it correctly.
Here is my codes,
function DomainValidate() {
var arrayOfLines = document.getElementById('txt').value.split('/n');
arrayOfLines.shift(); //use shift to skip the first line
for (i = 0; i < arrayOfLines.length; i++) {
//somewhere here need to split to get name.domain and then verify it
var domainName = arrayOfLines[i].split(" ", 2);
if(domainName.Equals("name.domain")
{
alert("You must replace name.domain to your new server name");
return false;
}
}
}
I am not sure if these are correct since I couldn't debug the javascript.
First issue I can see is that your character for the newline is incorrect. It should be \n not /n. Second issue I see is that i is a global variable, when it should be local. Third issue is that arrayOfLines[i].split(' ', 2); returns an array, but you are treating it like it returns a string on the next line if (domainName.Equals('name.domain').
With those corrections your code would look more like this:
function domainValidate() {
var arrayOfLines = document.getElementById('txt').value.split('\n');
arrayOfLines.shift(); //use shift to skip the first line
for (var i = 0; i < arrayOfLines.length; i++) {
var line = arrayOfLines[i].trim();
// Grab the second part of the split line, which represents the domain name
var parts = line.split(' ');
var domainName = parts[parts.length - 1];
if (!domainName || domainName === 'name.domain') {
alert("You must replace name.domain to your new server name");
return false;
}
}
}
As far as I can tell without testing, this should work as expected. The best way to test this though is with jsfiddle. Add your html and this script and call it to see if it produces the expected result.
Easiest way that I think
Suppose the id of textbox is domainTxt
src = document.getElementById("domainTxt");
if(verifyInput(src.value)){
//submit your form here
} else
{
return false;
}
function verifyInput(txtVal){
if(txtVal.indexOf("name.domain") >-1){
return false;
}else {
return true;
}
}

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
}

jQuery get last part of URL

I have a series of pages where I need to get a specific code for a button.
I want to put the code which is in the url into a variable with jQuery.
An example URL is www.example.com/folder/code/12345/
I want to get the number part in a variable called (siteCode)
Thanks in advance for any answers.
jquery / Pseudo code:
var siteCode;
// start function
function imageCode(){
siteCode // equals number part of URL
$('.button').attr('src', 'http:www.example.com/images/'+siteCode+'.jpg');
}
You can use the following code to get the last part of the url.:
var value = url.substring(url.lastIndexOf('/') + 1);
I'd suggest:
var URI = 'www.example.com/folder/code/12345/',
parts = URI.split('/'),
lastPart = parts.pop() == '' ? parts[parts.length - 1] : parts.pop();
JS Fiddle demo.
var str="url";
str.split("/")[3]
you can use split
There is one best way to take last part of URL is like following which generally has been used in real implementation.
There are Some loopholes in previously given answer was:
1.Consider what if there is a url like www.example.com/folder/code/12345 (Without '/' forward slash) Than none of the above code will work as per expectation.
2.Consider if folder hierarchy increases like www.example.com/folder/sub-folder/sub-sub-folder/code/12345
$(function () {
siteCode = getLastPartOfUrl('www.example.com/folder/code/12345/');
});
var getLastPartOfUrl =function($url) {
var url = $url;
var urlsplit = url.split("/");
var lastpart = urlsplit[urlsplit.length-1];
if(lastpart==='')
{
lastpart = urlsplit[urlsplit.length-2];
}
return lastpart;
}
Also try using regex
var url = "www.example.com/folder/code/12345";
var checkExt = /\d$/i.test(url);
if (checkExt) {
alert("Yup its a numeric");
} else {
alert("Nope");
}

Javascript - Detecting the first character and alerting the user

I have a question. I'm wanting to run a basic function in Javascript which takes an input field from a form and checks the very first character to ensure it does not have a £ sign (GBP) infront of the value
I can't seem to find the right code anywhere to do this? - Anyone have any idea's... I'm a bit of a noob to all this programming to be honest so any help would be gratefully received.
If you have an input field and you want to get it's value and check the first character of the value, you can do so like this:
<input type="text" id="price">
var str = document.getElementById("price").value;
if (str.charAt(0) == "£") {
// do whatever you need to do if there's a £ sign at the beginning
}
If the £ sign isn't supposed to be there, perhaps you could just safely remove it or ignore it rather than make the end user remove it like this:
var el = document.getElementById("price");
if (el.value.charAt(0) == "£") {
el.value = el.value.substr(1);
}
Assuming your HTML is something like this:
<input type="text" id="my_input" />
<button onClick="checkInput();">Check input</button>
Then you want to build your script like this:
function checkInput() {
var inp = document.getElementById('my_input'); // get the input field
inp = inp.value; // get the value
inp = inp.charAt(0); // get the first character
if( inp == "£") {
// do something
}
}
That can be condensed into:
function checkInput() {
if( document.getElementById('my_input').value.charAt(0) == "£") {
// do something
}
}
The trick to any code-writing is breaking a big problem into smaller ones. Step by step.
charAt should do it
var str = "Foo";
var firstChar = str.charAt(0);

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

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
}

Categories

Resources