I have a script that I am checking values from textbox against an array, the array are all values from a drop down list. Cant seem to get it to work. Thanks.
<script type = "text/javascript">
function chkName() {
var ddlArray = new Array();
var ddl = document.getElementById('DropDownList1');
for (i = 0; i < ddl.options.length; i++) {
ddlArray[i] = ddl.options[i].value;
}
var str = document.getElementById("TextBox1").value;
str = str.replace(/^\s+|\s+$/g, ""); // strip leading and trailing spaces
str = str.toLowerCase().replace(/\b[a-z]/g, function (w) {
return w.toUpperCase()
}); // reformat to lower-case with initial capital
var match = false;
for (var i = 0; i < ddlArray.length; i++) {
if (str == ddlArray[i]) {
match = true;
}
}
if (match) {
alert("The name " + str + " does match our list!");
document.getElementById("TextBox1").value = "";
return false;
} else {
return true;
}
}
</script>
Try this:
function chkName() {
"use strict";
var ddlArray = [],
ddl = document.getElementById('DropDownList1'),
str = document.getElementById("TextBox1").value,
match = false;
for (var i = 0; i < ddl.options.length; i++) {
ddlArray[i] = ddl.options[i].value;
}
str = str.replace(/^\s+|\s+$/g, "");
str = str.toLowerCase().replace(/\b[a-z]/g, function( w ) {
return w.toUpperCase();
});
for (i = 0; i < ddlArray.length; i++) {
if ( str === ddlArray[i] ) {
alert("The name " + str + " does match our list!");
document.getElementById("TextBox1").value = "";
return false;
}
}
return true;
}
Related
I am trying to match characters in an input, but when they write the wrong character it doesn't let you put it in the input. This is what I have so far.
Not sure what I am doing wrong in the non-matching area where I try to rebuild the string to put back in the input.
$(document).ready(function() {
$('#input1').keyup(function() {
var dInput = $('#input1').val().toLowerCase();
var a;
var b;
var word = "word";
var inputword;
word = word.toLowerCase();
for (var i = 0; i < dInput.length; i++) {
a = dInput.charAt(i);
b = word.charAt(i);
if (a == b) {
// alert("matches");
} else {
// alert("not matching");
console.log(i);
for (var j = 0; j <= i; j++) {
inputword = inputword + inputword.charAt(j);
}
$('#input1').val(inputword);
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="input1"></input>
You are currently not using inputword for anything other that to clear the field when wrong.
I think you mean this
$(document).ready(function() {
$('#input1').on("input",function() {
var dInput = $(this).val().toLowerCase();
var a;
var b;
var word = "word";
word = word.toLowerCase();
var inputword="";
for (var i = 0; i < dInput.length; i++) {
a = dInput.charAt(i);
b = word.charAt(i);
if (a == b) {
inputword += a;
}
$('#input1').val(inputword);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="input1"></input>
Shorter version
$(document).ready(function() {
$('#input1').on("input", function() {
const dInput = $(this).val().toLowerCase();
let word = "word";
word = word.toLowerCase();
let inputword = "";
[...dInput].forEach((char, i) => {
if (char === word.charAt(i)) inputword += char;
})
$('#input1').val(inputword);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="input1"></input>
EDITING to include solution based on Brian Hedlund's suggestion. Solution is at bottom.
I am getting this error in the console log
Syntax error, unrecognized expression: <h1>
This is the line generating the error
var substring = txt.find(tag).eq(i).text();
Sample data and code are below.
Why does that line throw that error and how can it be fixed?
I have verified that the function _mpactIdeation_countOccurrences() does execute properly as well as all lines in the function mpactIdeation_getTagContentsKeyphrase() above the line
var substring = txt.find(tag).eq(i).text();
Thanks for your time and consideration,
Tim
Sample Data:
The variable tag holds "<h1>".
The variable kp holds "fish".
The variable txt holds "<p>one.</p><h1>fish</h1><p>two fish. red fish. blue fish.</p>".
Code:
this.mpactIdeation_getTagContentsKeyphrase = function( tag, kp ) {
try {
var result = 0;
var num = 0;
var txt = this.oText;
var tagcount = this._mpactIdeation_countOccurrences( txt, tag, false );
txt = jQuery(txt);
for (i = 0; i < tagcount; i++) {
tag = this._mpactIdeation_escapeRegExp(tag);
var substring = txt.find(tag).eq(i).text();
result += this._mpactIdeation_countOccurrences(substring, kp, false);
}
return num;
} catch(e) {
console.log(e);
return false;
}
}
this._mpactIdeation_countOccurrences = function( string, subString, allowOverlapping ) {
try {
string += "";
subString += "";
if (subString.length <= 0) return (string.length + 1);
var num = 0,
pos = 0,
step = allowOverlapping ? 1 : subString.length;
while (true) {
pos = string.indexOf(subString, pos);
if (pos >= 0) {
++num;
pos += step;
} else break;
}
return num;
} catch(e) {
console.log(e);
return false;
}
}
SOLUTION:
this.mpactIdeation_getTagContentsKeyphrase = function( tag, kp ) {
try {
var result = 0;
var num = 0;
var txt = this.oText;
var tagcount = this._mpactIdeation_countOccurrences( txt, tag, false );
txt = jQuery(txt);
tag = this._mpactIdeation_tagToText(tag);
for (i = 0; i < tagcount; i++) {
var substring = txt.find(tag).eq(i).text();
result += this._mpactIdeation_countOccurrences(substring, kp, false);
}
return num;
} catch(e) {
console.log(e);
return false;
}
}
this._mpactIdeation_countOccurrences = function( string, subString, allowOverlapping ) {
try {
string += "";
subString += "";
if (subString.length <= 0) return (string.length + 1);
var num = 0,
pos = 0,
step = allowOverlapping ? 1 : subString.length;
while (true) {
pos = string.indexOf(subString, pos);
if (pos >= 0) {
++num;
console.log( "countOccurrences FOUND: " + subString + " INCREMENT");
pos += step;
} else break;
}
return num;
} catch(e) {
console.log(e);
return false;
}
}
this._mpactIdeation_tagToText = function(tag) {
try {
return tag = tag.replace(/[<>]/g, '');
} catch(e) {
console.log(e);
return false;
}
}
The correct find syntax is find('h1'), not find('<h1>')
This will fix your error, but not find your h1. find looks for descendants of the searched target, and since your txt has no root node, the intended target h1 is not a descendant, but a sibling. .siblings('h1') would do the trick.
Here is my code. What should I modify of this code to get the output as
"T-1
r-1
a-1
e-1 "
(other characters are repeating. So no need to print the others)
function different() {
var retureArr = [];
var count = 0;
var complete_name = "Trammell";
var stringLength = complete_name.length;
for (var t = 0; t < stringLength; t++) {
for (var s = 0; s < stringLength; s++) {
var com1 = complete_name.charAt(t);
var com2 = complete_name.charAt(s);
if (com1 != com2) {
retureArr[count] = com1;
count++;
}
}
count = 0;
}
}
I think this is what you want. You need to count the number of occurrences of each character in a dictionary. Then you can print them based on the count being equal to 1.
var retureArr = [];
var complete_name = "Trammell";
for (var i = 0; i < complete_name.length; i++)
{
var key = complete_name[i];
if (!(key in retureArr))
{
retureArr[key] = 1;
}
else
{
retureArr[key] = retureArr[key] + 1;
}
}
var output = "";
for (var key in retureArr)
{
if (retureArr[key] == 1)
{
output += key + "-" + retureArr[key] + " ";
}
}
alert(output);
This alerts the following string:
T-1 r-1 a-1 e-1
This works. but perhaps isn't the most efficient!
var string = "input string";
var stringList = [];
var outputString = "";
for (var i=0; i < string.length; i++){
var charObject = {"Char": string.charAt(i), "Passed": false};
stringList.push(charObject);
}
for (var i=0; i < stringList.length; i++){
if(!stringList[i].Passed && stringList[i].Char != " "){
var currentCount = countOccurrences(string, stringList[i].Char);
if(currentCount == 1){
outputString += stringList[i].Char+"-"+currentCount + " ";
}
stringList[i].Passed = true;
}
}
console.log(outputString);
function countOccurrences(string, char){
var count = 0;
for (var i=0; i < string.length; i++){
if(string.charAt(i) == char){
count++;
}
}
return count;
}
I am coding a template for eBay. However, eBay does not allow .replace. The code below is for a rollover tab section.When the user hovers over tab(a), the correspodning div div(a) is made to become visible.
Is there a workaround to get the code to work without using .replace?
var divs = new Array();
divs.push("contentPayment");
divs.push("contentShipping");
divs.push("contentWarranty");
divs.push("contentContact");
var navs = new Array();
navs.push("nav1");
navs.push("nav2");
navs.push("nav3");
navs.push("nav4");
///////////////////////////////////////
function hasClass(element, cls) {
return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}
///////////////////////////////////////////////////////////////////////
function toggleDisplay(id) {
for (var i = 0; i < divs.length; i++) {
var item = document.getElementById(divs[i]);
item.style.display = 'none';
}
var target = document.getElementById(id);
target.style.display = 'block';
///////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////PAYMENT IS HOVERED////////////////////////////////////////////////////////
if (id == "contentPayment") {
var CurrentTab = document.getElementById("nav1");
var AlreadyActive = hasClass(CurrentTab, "tabActive");
if (AlreadyActive === false) {
for (var i = 0; i < navs.length; i++) {
var otherTabs = document.getElementById(navs[i]);
otherTabs.className = otherTabs.className.replace(' tabActive', '');
}
CurrentTab.className += " " + "tabActive";
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////Shipping IS HOVERED////////////////////////////////////////////////////////
if (id == "contentShipping") {
var CurrentTab = document.getElementById("nav2");
var AlreadyActive = hasClass(CurrentTab, "tabActive");
if (AlreadyActive === false) {
for (var i = 0; i < navs.length; i++) {
var otherTabs = document.getElementById(navs[i]);
otherTabs.className = otherTabs.className.replace(' tabActive', '');
}
CurrentTab.className += " " + "tabActive";
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////Warranty IS HOVERED////////////////////////////////////////////////////////
if (id == "contentWarranty") {
var CurrentTab = document.getElementById("nav3");
var AlreadyActive = hasClass(CurrentTab, "tabActive");
if (AlreadyActive === false) {
for (var i = 0; i < navs.length; i++) {
var otherTabs = document.getElementById(navs[i]);
otherTabs.className = otherTabs.className.replace(' tabActive', '');
}
CurrentTab.className += " " + "tabActive";
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////Contact IS HOVERED////////////////////////////////////////////////////////
if (id == "contentContact") {
var CurrentTab = document.getElementById("nav4");
var AlreadyActive = hasClass(CurrentTab, "tabActive");
if (AlreadyActive === false) {
for (var i = 0; i < navs.length; i++) {
var otherTabs = document.getElementById(navs[i]);
otherTabs.className = otherTabs.className.replace(' tabActive', '');
}
CurrentTab.className += " " + "tabActive";
}
}
}
You may try this as an alternative of replace function
String.prototype.fakeReplace = function(str, newstr) {
return this.split(str).join(newstr);
};
var str = "Welcome javascript";
str = str.fakeReplace('javascript', '');
alert(str); // Welcome
DEMO.
For a more efficient, but slightly longer method, use this:
String.prototype.myReplace = function(pattern, nw) {
var curidx = 0, len = this.length, patlen = pattern.length, res = "";
while(curidx < len) {
var nwidx = this.indexOf(pattern, curidx);
console.log(nwidx);
if(nwidx == -1) {
break;
}
res = res + this.substr(curidx, nwidx - curidx);
res = res + nw;
curidx = nwidx + patlen;
}
return res;
};
alert("Glee is awesome".myReplace("awesome", "very very very awesome"));
See it in action: little link.
Hope that helped!
I have a function that performs a Luhn check on a card entry when a form is posted.
<script language="javascript">
function Calculate(Luhn)
{
var sum = 0;
for (i=0; i<Luhn.length; i++ )
{
sum += parseInt(Luhn.substring(i,i+1));
}
var delta = new Array (0,1,2,3,4,-4,-3,-2,-1,0);
for (i=Luhn.length-1; i>=0; i-=2 )
{
var deltaIndex = parseInt(Luhn.substring(i,i+1));
var deltaValue = delta[deltaIndex];
sum += deltaValue;
}
var mod10 = sum % 10;
mod10 = 10 - mod10;
if (mod10==10)
{
mod10=0;
}
return mod10;
}
function Validate(Luhn)
{
var LuhnDigit = parseInt(Luhn.substring(Luhn.length-1,Luhn.length));
var LuhnLess = Luhn.substring(0,Luhn.length-1);
if (Calculate(LuhnLess)==parseInt(LuhnDigit))
{
return true;
}
alert("\n\nYou have mis-typed your card number! \nPlease check and correct.\n\n")
return false;
}
I also have a function that removes any spaces that may have been entered in the card number onblur.
function stripChar(sValue, sChar) {
var i, tempChar, buildString;
buildString = ""
for (var i=0; i<sValue.length; i++) {
tempChar = sValue.charAt(i);
if (tempChar != sChar) {
buildString = buildString + tempChar;
}
}
return buildString;
How do I combine the functions so that the spaces are removed and the card number checked onblur.
In your onblur function you could use:
Validate(stripChar(sValue, sChar));