Javascript .Replace Alternative - javascript

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!

Related

Converting rTabs from bs3 to bs5

I want to make something awesome for Bootstrap 5.
As I search for week now, there aren't many good Tabs-responsive tabs solutions for Bootstrap 5 and most of them are not really good solution for mobile phones.
But in my search I encountered this one: https://codepen.io/Ayn_/pen/xdVBVg
https://github.com/Aynn/Bootstrap-Responsive-Tabs
So far my try with bs5: https://codepen.io/xkpx/pen/ExWXKRy
How can I convert this to work with bs5?
$(document).ready(function() {
rTab();
});
$(window).resize(function() {
rTab_resize();
});
function rTab()
{
$('.nav-tabs').each(function() {
var li = [];
var le = [];
var ddtab_w;
var currentw = $(this).outerWidth();
for(var i = 0; i < $(this)[0].children.length; i++)
{
li.push($(this)[0].children[i].outerHTML);
le.push($(this)[0].children[i].offsetWidth);
if(i == $(this)[0].children.length-1)
{
//$(this)[0].children[i].innerHTML = "<a href='#' data-toggle='tab'> Tab ("+ (i+1) +") <span class='caret'></span></a></a>";
ddtab_w = $(this)[0].children[i].offsetWidth;
}
}
var total_tabs = $(this)[0].children.length;
var wTracker = 0;
var tabs;
$(this).html('');
for(var i = 0; i < li.length; i++)
{
if((le[i] + wTracker) <= currentw)
{
wTracker += le[i];
tabs = i;
if (i == li.length-1)
{
for(var i = 0; i < li.length; i++)
{
$(this).append(li[i]);
}
}
} else {
i = li.length-1;
while(ddtab_w + wTracker >= currentw)
{
wTracker -= le[tabs--];
}
if(tabs < 0) { tabs = 0; }
for(var x = 0; x < tabs; x++)
{
$(this).append(li[x]);
}
var dropdown_tabs = ddTab(total_tabs-tabs, "Tabs");
$(this)[0].appendChild(dropdown_tabs[0]);
wTracker += $(this)[0].children[$(this)[0].children.length-1].offsetWidth;
while(tabs<li.length)
{
dropdown_tabs[1].innerHTML += li[tabs++];
}
}
}
if($(this)[0].children[$(this)[0].children.length-1].classList[1] == "pull-right")
{
isActive(dropdown_tabs, $(this)[0].children[$(this)[0].children.length-1]);
}
if($(this)[0].children.length == 1)
{
dropdown_tabs[0].style.paddingLeft = "10px";
dropdown_tabs[0].style.marginRight = "-10px";
dropdown_tabs[0].style.textAlign = "center";
dropdown_tabs[0].style.position = "relative";
dropdown_tabs[0].style.width = "100%";
dropdown_tabs[0].setAttribute("class","dropdown pull-right active");
dropdown_tabs[1].style.left = "7px";
dropdown_tabs[2].data = dropdown_tabs[1].children[0].innerText + " (" + dropdown_tabs[1].children.length + ")";
$(dropdown_tabs[1]).click(function() {
dropdown_tabs[2].data =event.target.text + " (" + dropdown_tabs[1].children.length + ")";
});
}
});
}
function rTab_resize()
{
reset();
rTab();
}
function reset()
{
$('.nav-tabs').each(function() {
if($(this)[0].children[$(this)[0].children.length-1].classList[1] == "pull-right")
{
var drop_down_tab = $(this)[0].children[$(this)[0].children.length-1].children[1];
var initial_value = drop_down_tab.children.length;
for(var i = 0; i < initial_value; i++)
{
$(this).append(drop_down_tab.children[0]);
}
$(this)[0].children[$(this)[0].children.length-(1+initial_value)].remove();
}
});
}
function ddTab(total_dropdown, tabName)
{
var n_li = document.createElement("li");
n_li.setAttribute("class","dropdown pull-right");
n_li.style.position = "relative";
n_li.style.right = "13px";
var n_a = document.createElement("a");
n_a.setAttribute("class","dropdown-toggle");
n_a.setAttribute("data-toggle","dropdown");
n_a.setAttribute("href","#");
var n_sp = document.createElement("span");
n_sp.setAttribute("class","caret");
var n_ul = document.createElement("ul");
n_ul.setAttribute("class","dropdown-menu");
var n_tx = document.createTextNode(tabName + " (" + total_dropdown + ")");
n_a.appendChild(n_tx);
n_a.appendChild(n_sp);
n_li.appendChild(n_a);
n_li.appendChild(n_ul);
return [n_li, n_ul, n_tx];
}
function isActive(dropdown_tabs, child)
{
for (var i = 0; i < dropdown_tabs[1].children.length; i++)
{
if(dropdown_tabs[1].children[i].classList[0] == "active")
{
child.setAttribute("class","dropdown pull-right active");
}
}
}

Blogger random post display to prevent no posts infinite loop

How can I get Blogger to display random posts, while preventing an infinite loop when there are no posts to display?
Here is my JavaScript code which I am attempting to use:
<script>
var dt_numposts = 10;
var dt_snippet_length = 100;
var dt_info = 'true';
var dt_comment = 'Comment';
var dt_disable = '';
var dt_current = [];
var dt_total_posts = 0;
var dt_current = new Array(dt_numposts);
function totalposts(json) {
dt_total_posts = json.feed.openSearch$totalResults.$t
}
document.write('<script type=\"text/javascript\" src=\"/feeds/posts/summary?max-results=100&orderby=published&alt=json-in-script&callback=totalposts\"><\/script>');
function getvalue() {
for (var i = 0; i < dt_numposts; i++) {
var found = false;
var rndValue = get_random();
for (var j = 0; j < dt_current.length; j++) {
if (dt_current[j] == rndValue) {
found = true;
break
}
};
if (found) {
i--
} else {
dt_current[i] = rndValue
}
}
};
function get_random() {
var ranNum = 1 + Math.round(Math.random() * (dt_total_posts - 1));
return ranNum
};
function random_list(json) {
a = location.href;
y = a.indexOf('?m=0');
for (var i = 0; i < dt_numposts; i++) {
var entry = json.feed.entry[i];
var dt_posttitle = entry.title.$t;
if ('content' in entry) {
var dt_get_snippet = entry.content.$t
} else {
if ('summary' in entry) {
var dt_get_snippet = entry.summary.$t
} else {
var dt_get_snippet = "";
}
};
dt_get_snippet = dt_get_snippet.replace(/<[^>]*>/g, "");
if (dt_get_snippet.length < dt_snippet_length) {
var dt_snippet = dt_get_snippet
} else {
dt_get_snippet = dt_get_snippet.substring(0, dt_snippet_length);
var space = dt_get_snippet.lastIndexOf(" ");
dt_snippet = dt_get_snippet.substring(0, space) + "…";
};
for (var j = 0; j < entry.link.length; j++) {
if ('thr$total' in entry) {
var dt_commentsNum = entry.thr$total.$t + ' ' + dt_comment
} else {
dt_commentsNum = dt_disable
};
if (entry.link[j].rel == 'alternate') {
var dt_posturl = entry.link[j].href;
if (y != -1) {
dt_posturl = dt_posturl + '?m=0'
}
var dt_postdate = entry.published.$t;
if ('media$thumbnail' in entry) {
var dt_thumb = entry.media$thumbnail.url
} else {
dt_thumb = "https://blogspot.com/"
}
}
};
document.write('<img alt="' + dt_posttitle + '" src="' + dt_thumb + '"/>');
document.write('<div>' + dt_posttitle + '</div>');
if (dt_info == 'true') {
document.write('<span>' + dt_postdate.substring(8, 10) + '/' + dt_postdate.substring(5, 7) + '/' + dt_postdate.substring(0, 4) + ' - ' + dt_commentsNum) + '</span>'
}
document.write('<div style="clear:both"></div>')
}
};
getvalue();
for (var i = 0; i < dt_numposts; i++) {
document.write('<script type=\"text/javascript\" src=\"/feeds/posts/summary?alt=json-in-script&start-index=' + dt_current[i] + '&max-results=1&callback=random_list\"><\/script>')
};
</script>
Expected output:
?
Actual output:
?
It looks like your post is mostly code; please add some more details.
It looks like you're trying to populate dt_current with dt_numposts = 10 elements. I modified getvalue() as follows, so that dt_numposts is capped at dt_total_posts, which may be 0. This allows the outer for loop to exit.
function getvalue() {
dt_numposts = (dt_total_posts < dt_numposts) ? dt_total_posts : dt_numposts;
// ...
I couldn't test this, because I don't have an example /feeds/posts/summary?max-results=100&orderby=published&alt=json-in-script&callback=totalposts JSON resource, but it works for zero posts. Whether is works for dt_numposts > 0, you'll need to test!

How to detect joy-con input/motion controls in HTML5 JavaScript

I am trying to create an HTML5 JavaScript game that uses Nintendo Switch Joy-Cons and motion controls. The problem is, I don't know how to detect motion controls from Joy-Cons when they are connected to my PC.
I've managed to achieve button inputs with Xbox controllers, PS4, and Joy Con using Gamepad API, but is it possible to do so with Joy-Con motion controls?
Here is the code for Gamepad API if you want to see it(Again, I'm aiming for Joy-Con motion controls):
var haveEvents = 'ongamepadconnected' in window;
var controllers = {};
function connecthandler(e) {
addgamepad(e.gamepad);
}
function addgamepad(gamepad) {
controllers[gamepad.index] = gamepad;
var d = document.createElement("div");
d.setAttribute("id", "controller" + gamepad.index);
var t = document.createElement("h1");
t.appendChild(document.createTextNode("gamepad: " + gamepad.id));
d.appendChild(t);
var b = document.createElement("div");
b.className = "buttons";
for (var i = 0; i < gamepad.buttons.length; i++) {
var e = document.createElement("span");
e.className = "button";
//e.id = "b" + i;
e.innerHTML = i;
b.appendChild(e);
}
d.appendChild(b);
var a = document.createElement("div");
a.className = "axes";
for (var i = 0; i < gamepad.axes.length; i++) {
var p = document.createElement("progress");
p.className = "axis";
//p.id = "a" + i;
p.setAttribute("max", "2");
p.setAttribute("value", "1");
p.innerHTML = i;
a.appendChild(p);
}
d.appendChild(a);
var start = document.getElementById("start");
if (start) {
start.style.display = "none";
}
document.body.appendChild(d);
requestAnimationFrame(updateStatus);
}
function disconnecthandler(e) {
removegamepad(e.gamepad);
}
function removegamepad(gamepad) {
var d = document.getElementById("controller" + gamepad.index);
document.body.removeChild(d);
delete controllers[gamepad.index];
}
function updateStatus() {
if (!haveEvents) {
scangamepads();
}
var i = 0;
var j;
for (j in controllers) {
var controller = controllers[j];
var d = document.getElementById("controller" + j);
var buttons = d.getElementsByClassName("button");
for (i = 0; i < controller.buttons.length; i++) {
var b = buttons[i];
var val = controller.buttons[i];
var pressed = val == 1.0;
if (typeof(val) == "object") {
pressed = val.pressed;
val = val.value;
}
var pct = Math.round(val * 100) + "%";
b.style.backgroundSize = pct + " " + pct;
if (pressed) {
b.className = "button pressed";
//Pressed down code here
} else {
b.className = "button";
//Release button code here
}
}
var axes = d.getElementsByClassName("axis");
for (i = 0; i < controller.axes.length; i++) {
var a = axes[i];
a.innerHTML = i + ": " + controller.axes[i].toFixed(4);
a.setAttribute("value", controller.axes[i] + 1);
}
}
requestAnimationFrame(updateStatus);
}
function scangamepads() {
var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
for (var i = 0; i < gamepads.length; i++) {
if (gamepads[i]) {
if (gamepads[i].index in controllers) {
controllers[gamepads[i].index] = gamepads[i];
} else {
addgamepad(gamepads[i]);
}
}
}
}
window.addEventListener("gamepadconnected", connecthandler);
window.addEventListener("gamepaddisconnected", disconnecthandler);
if (!haveEvents) {
setInterval(scangamepads, 500);
}
Using this link for reference
Wei Gao explained this in a React Knowledgeable meetup last week.
You can learn how she did it through her presentation or her slides.
You can visit the talk page for more information.

Other js function is ignoring my realtime calc function

I am at a lost here and have tried everything. My realtime calculation was being done into separate js file, but since I started using bootstrap template, it is not being executed. I have read through it and tried different thing but nothing is happening.
Php for calling realtime calc
<!-- ======================== PHONE INSURANCE ======================== -->
<select name="insurance" id='insurance' onChange="portInDatabase();">
<option disabled >Select Insurance</option>
<option value="None">None</option>
<option value="7">Yes</option>
</select><br>
<!-- ======================== PHONE CASE ======================== -->
<select name="case" id='case' onChange="portInDatabase()" onclick='portInDatabase()'>
<option disabled >Select Phone Case</option>
<option value="None">None</option>
<option value="25">Regular</option>
<option value="30">Wallet</option>
</select><br>
<!-- ======================== SCREEN PROTECTOR ======================== -->
<select name="screen" id='screen' onChange="portInDatabase();">
<option disabled >Select Screen Protector</option>
<option value="None">No</option>
<option value="15">Yes</option>
</select><br>
<!-- ======================== TOTAL FROM JS ======================== -->
<div id='total'></div>
Js for Real time calc(sorry for the long code)
// Array for plan prices
var plan_prices = new Array();
plan_prices["None"]= 0;
plan_prices["35"]=35;
plan_prices["50"]=50;
plan_prices["60"]=60;
// Array for insurance where "None" is the id from the html and it is equivalent
// to value 0 and so on
var insurance_phone = new Array();
insurance_phone["None"]=0;
insurance_phone["7"]=7;
//Array for phone case for price calculation
var phone_case = new Array();
phone_case["None"]=0;
phone_case["25"] = 25;
phone_case["30"] = 30;
//Array for screen protector
var screen_protector = new Array();
screen_protector["None"]=0;
screen_protector["15"] = 15;
// function for getting the plan price from the dropList
function getPlanPrice() {
var planSelected = 0;
var selectForm= document.forms["device"];
var selectedDevice3=selectForm.elements["plan"];
planSelected = plan_prices[selectedDevice3.value];
return planSelected;
}// end getPlanPrice
// function for getting the price when it is selected in the html dropList. This
// selection will single out the price we need for calculation.
function getInsurancePrice() {
var insuranceSelected = 0;
var selectForm= document.forms["device"];
var selectedDevice4=selectForm.elements["insurance"];
insuranceSelected = insurance_phone[selectedDevice4.value];
return insuranceSelected;
}// end getInsurancePrice
// Get the price for the selected option in the dropList to calculate.
function getCasePrice() {
var caseSelected = 0;
var selectForm= document.forms["device"];
var selectedDevice5=selectForm.elements["case"];
caseSelected = phone_case[selectedDevice5.value];
return caseSelected;
}// getCasePrice
// function to get the price for the screen.
function getScreenPrice() {
var screenSelected = 0;
var selectForm= document.forms["device"];
var selectedDevice6=selectForm.elements["screen"];
screenSelected = screen_protector[selectedDevice6.value];
return screenSelected;
}// getScreenPrice
// This function splits the data in the database to calculate the price for the
// device when port in is selected or when upgrade is selected and then it also checks
// whether anything else is selected in the form and does the real time calculation and
// outputs the result.
function portInDatabase(){
console.log("PortInDatabase started..")
debugger;
var price1, price2, price3, price4, price5, price6 = 0;
var port = 0;
var newAct = 0;
var up = 0;
var down = 0;
var act= 25; //Activation fee
// if the selection is a number then execute this
if(!isNaN(getPlanPrice())){
price2= getPlanPrice();
}
if(!isNaN(getInsurancePrice())){
price3= getInsurancePrice();
}
if(!isNaN(getCasePrice())){
price4= getCasePrice();
}
if(!isNaN(getScreenPrice())){
price5= getScreenPrice();
}
// This if statement is executed when Port is selected in the dropList and then
// it splits the rows which is connected to the device accordingly and then checks
// whether any of the other dropLists are selected so it can then calulate them and output it.
debugger;
if (document.getElementById('myport').selected == true){
var selDev = document.getElementById('selectDevice').value;
var port = selDev.split('#')[4]; // number of row in the database
port= parseFloat(port) +parseFloat(selDev.split('#')[1]*0.092)+price2 + price3 + price4 +price5+act;
port = port.toFixed(2); // rounds the decimal to 2
debugger;
document.getElementById('total').innerHTML= "Your Total: " +port;
}//end if
// for new Activation selection
else if(document.getElementById('srp').selected == true){
var selDev = document.getElementById('selectDevice').value;
var newAct = selDev.split('#')[1];
newAct= parseFloat(newAct) +parseFloat(selDev.split('#')[1]*0.092)+price2 + price3 + price4 +price5+act;
newAct = newAct.toFixed(2);
document.getElementById('total').innerHTML= "Your Total: " +newAct;
}//elseif
//for upgrade selection
else if(document.getElementById('upgrade').selected == true){
var selDev = document.getElementById('selectDevice').value;
var up = selDev.split('#')[2];
up = parseFloat(up) +parseFloat(selDev.split('#')[1]*0.092)+price2 + price3 + price4 +price5+act;
up = up.toFixed(2);
document.getElementById('total').innerHTML= "Your Total: " +up;
}//2nd elseif
//for down selection
else if(document.getElementById('down').selected == true){
var selDev= document.getElementById('selectDevice').value;
var down= selDev.split('#')[6];
down = parseFloat(port) +parseFloat(selDev.split('#')[1]*0.092)+price2 + price3 + price4 +price5+act;
down = down.toFixed(2);
document.getElementsById('total').innerHTML= "Your Total: " +down;
}//end 3rd elseif
else{
return false;
}//end else
}// end portInDatabase
JS of styling that is preventing real time calc
var CuteSelect = CuteSelect || {};
FIRSTLOAD = true;
SOMETHINGOPEN = false;
CuteSelect.tools = {
canRun: function() {
var myNav = navigator.userAgent.toLowerCase();
var browser = (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
if(browser) {
return (browser > 8) ? true : false;
} else { return true; }
},
uniqid: function() {
var n= Math.floor(Math.random()*11);
var k = Math.floor(Math.random()* 1000000);
var m = String.fromCharCode(n)+k;
return m;
},
hideEverything: function() {
if(SOMETHINGOPEN) {
SOMETHINGOPEN = false;
targetThis = false;
var cells = document.getElementsByTagName('div');
for (var i = 0; i < cells.length; i++) {
if(cells[i].hasAttribute('data-cuteselect-options')) {
var parent = cells[i].parentNode;
cells[i].style.opacity = '0';
cells[i].style.display = 'none';
}
}
}
},
getStyle: function() {
var css = '';
var stylesheets = document.styleSheets;
var css = '';
for(s = 0; s < stylesheets.length; s++) {
var classes = stylesheets[s].rules || stylesheets[s].cssRules;
for (var x = 0; x < classes.length; x++) {
if(classes[x].selectorText != undefined) {
var selectPosition = classes[x].selectorText.indexOf('select');
var optionPosition = classes[x].selectorText.indexOf('option');
var selectChar = classes[x].selectorText.charAt(selectPosition - 1);
var optionChar = classes[x].selectorText.charAt(optionPosition - 1);
if(selectPosition >= 0 && optionPosition >= 0 && (selectChar == '' || selectChar == '}' || selectChar == ' ') && (optionChar == '' || optionChar == '}' || optionChar == ' ')) {
text = (classes[x].cssText) ? classes[x].cssText : classes[x].style.cssText;
css += text.replace(/\boption\b/g, '[data-cuteselect-value]').replace(/\bselect\b/g, '[data-cuteselect-item]');
continue;
}
if(selectPosition >= 0) {
var character = classes[x].selectorText.charAt(selectPosition - 1);
if(character == '' || character == '}' || character == ' ') {
text = (classes[x].cssText) ? classes[x].cssText : classes[x].style.cssText;
css += text.replace(/\bselect\b/g, '[data-cuteselect-item]');
}
}
if(optionPosition >= 0) {
var character = classes[x].selectorText.charAt(optionPosition - 1);
if(character == '' || character == '}' || character == ' ') {
text = (classes[x].cssText) ? classes[x].cssText : classes[x].style.cssText;
css += text.replace(/\boption\b/g, '[data-cuteselect-value]');
}
}
}
}
}
return css;
},
createSelect: function(item) {
// Create custom select
var node = document.createElement("div");
if(item.hasAttribute('id')) { // Catch ID
node.setAttribute('id', item.getAttribute('id'));
item.removeAttribute('id');
}
if(item.hasAttribute('class')) { // Catch Class
node.setAttribute('class', item.getAttribute('class'));
item.removeAttribute('class');
}
// Hide select
item.style.display = 'none';
// Get Default value (caption)
var caption = null;
var cells = item.getElementsByTagName('option');
for (var i = 0; i < cells.length; i++) {
caption = cells[0].innerHTML;
if(cells[i].hasAttribute('selected')) {
caption = cells[i].innerHTML;
break;
}
}
// Get select options
var options = '<div data-cuteselect-title>' + caption + '</div><div data-cuteselect-options><div data-cuteselect-options-container>';
var cells = item.getElementsByTagName('option');
for (var i = 0; i < cells.length; i++) {
if(cells[i].hasAttribute('disabled')) { continue; }
if(cells[i].hasAttribute('class')) { var optionStyle = ' class="' + cells[i].getAttribute('class') + '"'; } else { var optionStyle = ''; }
if(cells[i].hasAttribute('id')) { var optionId = ' id="' + cells[i].getAttribute('id') + '"'; } else { var optionId = ''; }
if(cells[i].hasAttribute('selected')) { options += '<div data-cuteselect-value="' + cells[i].value + '" data-cuteselect-selected="true"' + optionStyle + optionId + '>' + cells[i].innerHTML + '</div>'; }
else { options += '<div data-cuteselect-value="' + cells[i].value + '"' + optionStyle + optionId + '>' + cells[i].innerHTML + '</div>'; }
}
options += '</div></div>';
// New select customization
node.innerHTML = caption;
node.setAttribute('data-cuteselect-item', CuteSelect.tools.uniqid());
node.innerHTML = options; // Display options
item.setAttribute('data-cuteselect-target', node.getAttribute('data-cuteselect-item'));
item.parentNode.insertBefore(node, item.nextSibling);
// Hide all options
CuteSelect.tools.hideEverything();
},
//settings of the options, their position and all
show: function(item) {
if(item.parentNode.hasAttribute('data-cuteselect-item')) { var source = item.parentNode.getAttribute('data-cuteselect-item'); }
else { var source = item.getAttribute('data-cuteselect-item'); }
var cells = document.getElementsByTagName('select');
if(item.hasAttribute('data-cuteselect-title')) {
item = item.parentNode;
var cells = item.getElementsByTagName('div');
}
else { var cells = item.getElementsByTagName('div'); }
for (var i = 0; i < cells.length; i++) {
if(cells[i].hasAttribute('data-cuteselect-options')) {
targetItem = cells[i];
cells[i].style.display = 'block';
setTimeout(function() { targetItem.style.opacity = '1'; }, 10);
cells[i].style.position = 'absolute';
cells[i].style.left = item.offsetLeft + 'px';
cells[i].style.top = (item.offsetTop + item.offsetHeight) + 'px';
}
}
item.focus();
SOMETHINGOPEN = item.getAttribute('data-cuteselect-item');
},
selectOption: function(item) {
var label = item.innerHTML;
var value = item.getAttribute('data-cuteselect-value');
var parent = item.parentNode.parentNode.parentNode;
var target = parent.getAttribute('data-cuteselect-item');
var cells = parent.getElementsByTagName('div');
for (var i = 0; i < cells.length; i++) {
if(cells[i].hasAttribute('data-cuteselect-title')) { cells[i].innerHTML = label; }
}
// Real select
var cells = document.getElementsByTagName('select');
for (var i = 0; i < cells.length; i++) {
var source = cells[i].getAttribute('data-cuteselect-target');
if(source == target) { cells[i].value = value; }
}
//CuteSelect.tools.hideEverything();
},
writeStyles: function() {
toWrite = '<style type="text/css">' + CuteSelect.tools.getStyle() + ' [data-cuteselect-options] { opacity: 0; display: none; }</style>';
document.write(toWrite);
}
};
CuteSelect.event = {
parse: function() {
var cells = document.getElementsByTagName('select');
for (var i = 0; i < cells.length; i++) { CuteSelect.tools.createSelect(cells[i]); }
},
listen: function() {
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.keyCode == 27) { CuteSelect.tools.hideEverything(); }
};
document.onclick = function(event) {
FIRSTLOAD = false;
if((!event.target.getAttribute('data-cuteselect-item') && !event.target.getAttribute('data-cuteselect-value') && !event.target.hasAttribute('data-cuteselect-title')) || ((event.target.hasAttribute('data-cuteselect-item') || event.target.hasAttribute('data-cuteselect-title')) && SOMETHINGOPEN)) {
CuteSelect.tools.hideEverything();
return;
}
//when selected the option dropdown list closes
var action = event.target;
if(event.target.getAttribute('data-cuteselect-value')) {
CuteSelect.tools.selectOption(action);
CuteSelect.tools.hideEverything();
}
else { CuteSelect.tools.show(action); }
return false;
}
},
manage: function() {
if(CuteSelect.tools.canRun()) { // IE Compatibility
CuteSelect.event.parse();
CuteSelect.event.listen();
CuteSelect.tools.writeStyles();
}
}
};
// document.onload(function() {
CuteSelect.event.manage();
// });
I did not want to post this long question, but I am lost and do not know what to do. Thanks and sorry.

Checking value in textbox against an array script not working

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

Categories

Resources