JavaScript - Cannot Seem To Get Javascripts String.indexof To Work ???
0 down vote favorite
share [g+] share [fb] share [tw] I have a fairly large program that I have simplified to show the problem that I am having. I have 2 div's under which I have an image and some text. When I hover on the image, the jQuery hover over image event fires. Through all this, I am able to get the Id's of both the images & their parent div's. However, when I try to get the index value of the Id's in an array, it always returns -1 ie... not found. Can you please help. The code is enclosed below. I am new to javascript & jQuery and hence the need of some help. Maybe the solution is very trivial. Thanks in advance. Regards, sbguy <html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> var input_array = new Array("input1_Id", "input2_Id"); var div_array = new Array("div1_Id", "div2_Id"); window.onload=function(){ jQuery.ready(); img_hover_event_handler(); } //________________________________________________ function img_hover_event_handler() { var input_id = ""; var div_id = ""; var input_index, div_index; $("input.Lrollover").hover( function() { input_id = new String(this.id); input_index = new String(input_array.indexOf(div_id)); div_id = new String($(this).closest('div').attr('id')); // id of the parent div div_index = new String(div_array.indexOf(div_id)); alert(input_id + ", " + input_index + ", " + div_id + ", " + div_index); }, function() { }); } </script> </head> <body> <div id="div1_Id"> <input class="Lrollover" id="input1_Id" type="image" src="images/LGbtn_off.png" alt="Image1" /> <p id="myp1_Id">"Hello World 1"</p> </div> <br><br><br> <div id="div2_Id"> <input class="Lrollover" id="input2_Id" type="image" src="images/LGbtn_off.png" alt="Image2"/> <p id="myp2_Id">Hello World 2"</p> </div> </body> </html> Similar TutorialsHello there I'm trying to build a simple little bot that you can ask questions. I'm using the indexOf method but I'm not sure if this is the best option for what I'm trying to do. If you type 'hello' or 'how are you' it answers. Any other input results in 'Dreadfully sorry but I didn't catch that. Say again?'. Is there a way that I can search input for certain words or combinations of words and trigger a single answer? Any help appreciated. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Bot</title> <script type="text/javascript"> function bot(go){var a = go.getElementsByTagName('input');var q = a[0];var t = q.value.toLowerCase();document.go.reset();if(t.indexOf('hello')!=-1){document.getElementById('bot').innerHTML = "Hello to you.";return false;}if(t.indexOf('how are you')!=-1){document.getElementById('bot').innerHTML = "I am functioning within acceptable parameters, thank you.";return false;};go.action=document.getElementById('bot').innerHTML = "Dreadfully sorry but I didn't catch that. Say again?"; return false;}; </SCRIPT> </head> <body onLoad="document.go.q.focus()"> <div align="center"> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> <form name="go" onsubmit='return bot(go)' id="go" action=""><input name='q' type='text' /><input name='' type='hidden' /></form> <p> </p><div id="bot" align="center"></div> </div> </body> Hi, I am trying to build a bookmarklet to use on the swiss legislation website. All the pages are available in several languages and I want to be able to switch with one button from french to german and from german to french. As an example, the URLs are as follow for the same page: in French: http://www.admin.ch/ch/f/rs/311_0/index2.html in German: http://www.admin.ch/ch/d/sr/311_0/index2.html So I built quite easily two bookmarklets to switch FR-DE and DE-FR: Code: javascript: var str = window.location.pathname;str = str.replace("f/rs", "d/sr");window.location = str; Code: javascript: var str = window.location.pathname;str = str.replace("d/sr", "f/rs");window.location = str; But when I try to get a single script by using if/else, I cannot manage to have the "else" part working: Code: javascript: var str = window.location.pathname; if (location.pathname.indexOf("d/rs") < 0) { str = str.replace("f/rs", "d/sr"); window.location = str; } else { str = str.replace("d/sr", "f/rs"); window.location = str; } Thinking it might have to do with str.replace, I tried an easier variant, but even this one does not work, the "else" part is never called: Code: javascript: var str = window.location.pathname; if (location.pathname.indexOf("d/rs") < 0) { str = str.replace("f/rs", "d/sr"); window.location = str; } else { alert('no'); }; I would appreciate any help on the matter... thanks in advance, RJ This is a snippet from a project I'm working on involving XML DOM, but the question is really about javascript. This is the problematic code. Code: else if (nodeOccurance.IndexOf('each:') == 0) { . . . } I want the if statement to be true if the value of the variable "nodeOccurance" begins with "each:" For some reason, it's just stopping my whole script and doing nothing. Any help? Thanks, Julian Hi, I'm trying to match a text string within a textarea node and then use a text range to set the users cursor highlighting over the word.My code for this is as follows: Code: function doHighlight(theWord, textAreaElement) { var text = textAreaElement.value; var theIndex = text.indexOf(theWord); setCaretPos(textAreaElement, theIndex, theIndex+theWord.length); } function setCaretPos(obj, start, end) { var range = obj.createTextRange(); range.moveStart('character', start); range.moveEnd('character', end - obj.value.length); range.select(); } I have a text area with the following html: Code: <TEXTAREA>blah blah sausage Frank Jones</TEXTAREA> (ie there are four lines visible to the user, the 3rd is blank). And I call the doHighlight method with 'blah blah', 'sausage' and 'frank jones' respectively. However the highlighting isnt working quite right - when I try to highlight 'blah blah', it highlights 'blah bl', when I try to highlight 'sausage' it highlights 'ausa' (the 2nd-5th characters) and when I try to highlight 'frank jones', it highlights 'nk jones'. This code seems to work fine when there is only a single line of text in the text area though - so I'm guess it's something to do with newline characters. Can anybody point me in the right direction as to how to fix this bug please? Thanks. hi all, my indexof() function is not being recognized when I enter an email address for an unsubscribe form I have on one of my pages. Additionally, the confirmation message is also not showing up when the email address IS valid. Here is my code that I am using on a PHP page: PHP Code: function Unsubscribe() { var IsValid = document.getElementById("email").value; alert(IsValid.indexOf("@")); exit; if (document.getElementById("email").value.length == 0 || IsValid.indexOf("@")) == -1) { alert("Enter a valid email address"); exit; } else { <?php $handle = @fopen("../logs/unsubscribes.txt", "a"); fputs($handle, $_POST["email"] . " " . "\r\n"); fclose ($handle); ?> alert(IsValid &&" has been unsubscribed."); <?php if (! $_POST["email"]) { //DO NOTHING } else { header("Location: http://www.google.com/"); } ?> } } //--> </script> </head> <body> <form action="" method="post" name="frm" onsubmit="Unsubscribe()"> <center><br /> Enter Your Email Address:<br /> <input type="text" id="email" name="email" /> </center> <p> <label> <center><input type="submit" id="unsubscribe" value="Unsubscribe Me" /></center> </label> </p> </form> </body> </html> to those PHP experts, I am aware of the RegEx function for validation, but I don't understand it, which is why I don't use it (in case anyone points that out). The other thing that is problematic is that the PHP code is automatically using HEADER() regardless of "email"'s value Hi there! OK I need a little help as I'm not sure how to integrate this function into my form. First of all I should explain that my form doubles as a Google Search box. If you select the Google Search radio button it submits the input text to Google. It also defaults to Google if anything else other than "red", "green" or "blue" are entered. Now what I'd like to do is add a function so that if someone enters "purple is my favorite color" it recognizes the "purple" part of the string using something like .indexOf('purple'); and calls something like if(function==-1) { theForm.action = "Other choice "+ q.value; . How can I add this to my form? Thank you for any help. My form code: Code: <script> function convert(theForm){ var els = theForm.getElementsByTagName('input');// store inputs var q = els[0], color = els[1]; if(els[4].checked){// submit to google theForm.action = 'http://www.google.com/search'; return true; }; color.value = "Chosen "+ q.value +" color"; switch(q.value){// check the query case 'red': case 'green': case 'blue': location.href = color.value; return false; break; default: theForm.action="http://www.google.com/search"; break; }; return true; }; </script> <form name= "myform" onsubmit='return convert(this)'> <input name='q' type='text' /> <input name='color' type='hidden' /> <input type='submit' value=" Enter " /> <br /> <input name="searchType" type="radio" value="" checked="checked" > <label for="all"> My Form </label> <input name="searchType" type="radio" value="google" onclick="document.myform.action='http://www.google.com/search';" /> <label for="google"> Google Search </label></form> hello .. - I want ask about function in js file , when is it start work ? after calling in somewhere ? or in sequence - can I call function in js file from another js file ? thank you . . Hey, I've been trying to make two javascript files kiss and make up in my web site code. I tried the "noconflict" function, but either I did it wrong, or it didn't work out. Here is the page with the conflict. Help? Hi All, I know this has been covered many times on this site, but I just cannot figure out what I'm doing wrong. I've got a jquery slideshow and some lightbox galley images that I'm trying to get to work together. I thought I had taken out the parts that were conflicting but I apparently haven't. Any help would be much appreciated. Here's the page I'm working on: oneeightyone.com/new/index.html I have a page with several javascript (.js files) in the header, is it possible to preload all of these before the actual page content is loaded? I want to hide the javascript execution from taking place after the page has loaded. Any ideas? Thanks! So I am not great at Javascript, but i have 2 scripts that i want to work with each other. When i use one by itself, they each work fine, but when i add them together it does not work. I have a user form with a bunch of fields on it. If they choose an option on the drop down menu, some fields either show or disappear. Those fields have an "On Change" event that subtracts one field form another and gives us a total. ////////////////////////////////////// Drop Down Menu ///// rel sets to show the Code: <tr> <select name="checkout_by" class="textLeft" id="checkout_by" value="<?php if($cont == 'no') { echo $checkout_by; } ?>" > <option value="serial" selected rel="show">Item Series / Serial Number</option> <option value="isbn" rel="none">Barcode / ISBN Number</option> //////////////////////////////////// Fields used to subtract Code: <input name="serial_start" onChange="updatesum()" type="text" class="textLeft" id="serial_start" value="<?php if($cont == 'no') { echo $serial_start; } ?>" size="15"> Code: <input name="serial_end" onChange="updatesum()" type="text" class="textLeft" id="serial_end" value="<?php if($cont == 'no') { echo $serial_end; } ?>" size="15"> //////////////////////////////////// Field used to add the total up from above Code: <input name="org_quantity" type="text" id="org_quantity" value="<?php if($cont == 'no') { echo $orig_quantity; } ?>" size="10"> ///////////////////////////////////////Update total script Code: <script type="text/javascript"> function updatesum() { document.form1.org_quantity.value = (document.form1.serial_end.value -0) - (document.form1.serial_start.value -0); } </script> //////////////////////////////////// Hide Filed Script Code: var containerTag = 'TR'; var compatible = ( document.getElementById && document.getElementsByTagName && document.createElement && !(navigator.userAgent.indexOf('MSIE 5') != -1 && navigator.userAgent.indexOf('Mac') != -1) ); if (compatible) { document.write('<style>.accessibility{display: none}</style>'); var waitingRoom = document.createElement('div'); } var hiddenFormFieldsPointers = new Object(); function prepareForm() { if (!compatible) return; var marker = document.createElement(containerTag); marker.style.display = 'none'; var x = document.getElementsByTagName('select'); for (var i=0;i<x.length;i++) addEvent(x[i],'change',showHideFields) var x = document.getElementsByTagName(containerTag); var hiddenFields = new Array; for (var i=0;i<x.length;i++) { if (x[i].getAttribute('rel')) { var y = getAllFormFields(x[i]); x[i].nestedRels = new Array(); for (var j=0;j<y.length;j++) { var rel = y[j].getAttribute('rel'); if (!rel || rel == 'none') continue; x[i].nestedRels.push(rel); } if (!x[i].nestedRels.length) x[i].nestedRels = null; hiddenFields.push(x[i]); } } while (hiddenFields.length) { var rel = hiddenFields[0].getAttribute('rel'); if (!hiddenFormFieldsPointers[rel]) hiddenFormFieldsPointers[rel] = new Array(); var relIndex = hiddenFormFieldsPointers[rel].length; hiddenFormFieldsPointers[rel][relIndex] = hiddenFields[0]; var newMarker = marker.cloneNode(true); newMarker.id = rel + relIndex; hiddenFields[0].parentNode.replaceChild(newMarker,hiddenFields[0]); waitingRoom.appendChild(hiddenFields.shift()); } setDefaults(); addEvent(document,'click',showHideFields); } function setDefaults() { var y = document.getElementsByTagName('input'); for (var i=0;i<y.length;i++) { if (y[i].checked && y[i].getAttribute('rel')) intoMainForm(y[i].getAttribute('rel')) } var z = document.getElementsByTagName('select'); for (var i=0;i<z.length;i++) { if (z[i].options[z[i].selectedIndex].getAttribute('rel')) intoMainForm(z[i].options[z[i].selectedIndex].getAttribute('rel')) } } function showHideFields(e) { if (!e) var e = window.event; var tg = e.target || e.srcElement; if (tg.nodeName == 'LABEL') { var relatedFieldName = tg.getAttribute('for') || tg.getAttribute('htmlFor'); tg = document.getElementById(relatedFieldName); } if ( !(tg.nodeName == 'SELECT' && e.type == 'change') && !(tg.nodeName == 'INPUT' && tg.getAttribute('rel')) ) return; var fieldsToBeInserted = tg.getAttribute('rel'); if (tg.type == 'checkbox') { if (tg.checked) intoMainForm(fieldsToBeInserted); else intoWaitingRoom(fieldsToBeInserted); } else if (tg.type == 'radio') { removeOthers(tg.form[tg.name],fieldsToBeInserted) intoMainForm(fieldsToBeInserted); } else if (tg.type == 'select-one') { fieldsToBeInserted = tg.options[tg.selectedIndex].getAttribute('rel'); removeOthers(tg.options,fieldsToBeInserted); intoMainForm(fieldsToBeInserted); } } function removeOthers(others,fieldsToBeInserted) { for (var i=0;i<others.length;i++) { var show = others[i].getAttribute('rel'); if (show == fieldsToBeInserted) continue; intoWaitingRoom(show); } } function intoWaitingRoom(relation) { if (relation == 'none') return; var Elements = hiddenFormFieldsPointers[relation]; for (var i=0;i<Elements.length;i++) { waitingRoom.appendChild(Elements[i]); if (Elements[i].nestedRels) for (var j=0;j<Elements[i].nestedRels.length;j++) intoWaitingRoom(Elements[i].nestedRels[j]); } } function intoMainForm(relation) { if (relation == 'none') return; var Elements = hiddenFormFieldsPointers[relation]; for (var i=0;i<Elements.length;i++) { var insertPoint = document.getElementById(relation+i); insertPoint.parentNode.insertBefore(Elements[i],insertPoint); if (Elements[i].nestedRels) { var fields = getAllFormFields(Elements[i]); for (var j=0;j<fields.length;j++) { if (!fields[j].getAttribute('rel')) continue; if (fields[j].checked || fields[j].selected) intoMainForm(fields[j].getAttribute('rel')); } } } } function getAllFormFields(node) { var allFormFields = new Array; var x = node.getElementsByTagName('input'); for (var i=0;i<x.length;i++) allFormFields.push(x[i]); var y = node.getElementsByTagName('option'); for (var i=0;i<y.length;i++) allFormFields.push(y[i]); return allFormFields; } /** ULTRA-SIMPLE EVENT ADDING **/ function addEvent(obj,type,fn) { if (obj.addEventListener) obj.addEventListener(type,fn,false); else if (obj.attachEvent) obj.attachEvent("on"+type,fn); } addEvent(window,"load",prepareForm); /** PUSH AND SHIFT FOR IE5 **/ function Array_push() { var A_p = 0 for (A_p = 0; A_p < arguments.length; A_p++) { this[this.length] = arguments[A_p] } return this.length } if (typeof Array.prototype.push == "undefined") { Array.prototype.push = Array_push } function Array_shift() { var A_s = 0 var response = this[0] for (A_s = 0; A_s < this.length-1; A_s++) { this[A_s] = this[A_s + 1] } this.length-- return response } if (typeof Array.prototype.shift == "undefined") { Array.prototype.shift = Array_shift } Hi, I am using several Javascripts into a html file. Individually all scripts working fine, however when I put them on the onclick event someof them not works. Example: <html> <head> <script> function one; </script> <script> function two; </script> <script> function three; </script> </head> <body> <form type=post action=newfile.asp> .................... ................... ................... <input type=submit onclick="one(); two(); three();"> </form> </body> </html The schema is right? How is the best way to force many scripts working fine? Bob So i have this one problem and its been a major pain for a while. I have both a light box function and a fade into page intro on my website. The issue i have is when i put in the lightbox, lightbox seems to not work whats so ever. So i made another page and first put in the lightbox...that worked like a charm but once i put in the fade in intro it basically gets me back to lightbox not working...So...any way to solve this? Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Untitled Document</title> <link href="css/lightbox.css" rel="stylesheet" type="text/css" /> <link href="layout.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="js/prototype.js"></script> <script type="text/javascript" src="js/scriptaculous.js?load=effects,builder"></script> <script type="text/javascript" src="js/lightbox.js"></script> <script type="text/javascript" src="jquery-1.4.2.min.js" ></script> <script type="text/javascript"> $(document).ready(function() { // fade in content. $( '#wrapper' ).fadeIn("slow"); }); </script> </head> <body> <div id="wrapper"> <table><tr><td><a href="air_pollution copy.jpg" rel="lightbox" ><img src="air_pollution.jpg" /></a></td></tr></table></div> </body> </html> i have been tryin for a long time to get both of the javascripts(for the thumbnail to main img swap and the navigational arrow swap) to work in synch http://***.com/nn.html it needs to be so that after clicking on a thumbnail then on an arrow, the correct image in the correct order appears. as of now they are running separately and one has no influence on the other. forgive me if im not being clear. i keep trying to replace the id that one script is looking for with the same id from the other but this will not work..why? please help me...believe me ive tried to help myself by reading all i can understand on the web about this but im in the dark thanks I'm sure people have answered this question multiple times but I have done all the research and tried everything but nothing works. My problem: I'm building a website for my gaming clan and I want a Javascript news ticker/date & time and a Javascript navigation bar. However, when I put these codes in, they don't run with each other on the same page. Possibly an onload issue but like I said, I tried all the solutions. Note: they use jquery. I'll post the html and javascript files as txt files since I can't attach them in their normal form. Index.txt is my HTML Sliding_effect.txt is the Javascript for the menubar Newsticker.txt is the Javascript for the ticker that goes at the bottom of the <body> The actual ticker.js code that runs with newsticker.js was too large to attach. It's 7000 lines long. Any help is appreciated Hello, A client asked me to create this site with modals that each contain a small gallery. I used Colorbox to create the windows and Highslide for the galleries. See link; http://www.garrigan.net/Furryteeth/ Then he saw an example of a script named Mosaic and wanted it incorporated into the original design. Mosaic creates sliding boxes that pop up with captions when you rollover an image. Working from the base html file I got everything to work perfectly locally on my machine. After I uploaded everything to my site to test it out things went very wrong. See link; http://www.garrigan.net/Nakata/ Everything works until you click on one of the images to launch a gallery. Then the entire site seems to fall to pieces. Any idea what I did wrong or where I can correct my mistake? I am assuming there is a server issue since it works on my machine. Thanks for any help you can offer. These are the JQuery scripts I used; http://buildinternet.com/project/mosaic/ http://highslide.com/ http://colorpowered.com/colorbox/ Hey guys, well first of all i'm new at the forum and very, very new to javascript so pleas go easy on me for asking dumb questions. Second of all i'm Rutger, from the netherlands, hi folks! So, here's my problem. I'm rebuilding my portfolio webpage and i'm doing it all by my self to learn html and css. Thats going great so far but i'm having problems using javascripts. In all pages i use a javascript for a dropdown menu, this works great exept for the homepage. There i also use a javascript for a slideshow to show recent work. The slideshow works but because i add the slideshow the dropdown stops working comepletely and i can't figure out why... I've been searching google and i keep finding the window.onload solution but both scripts don't use that command.... Anyone's got a clue? Please help cause i'm about to pull my hair out! Haha, just kidding but it's pretty frustrading! Rutger P.S. Here are both codes: Here is the slideshow: Code: Object.prototype.addEvent = function(evtType, func) { if (this.addEventListener) { this.addEventListener(evtType, func, true); } else if (this.attachEvent) { this.attachEvent('on' + evtType, func); } else { this['on' + evtType] = func; } } function slideshow(slideel, faddingSpeed, stopTime, stopOnMouseOver) { var mouseIsOver = false; if (stopOnMouseOver) { slideel.addEvent('mouseover', function() { mouseIsOver = true; }); slideel.addEvent('mouseout', function() { mouseIsOver = false; self.next(); }); } this.next = function() { if (mouseIsOver) return; this.current.fadeOut(); this.current = this.current.nextSlide; this.current.fadeIn(); } function createSlides() { var imgs = slideel.getElementsByTagName('img'); var slides = []; for (var i = 0; i < imgs.length; i++) { slides[i] = new slideshowImage(imgs[i], self); } for (var i = 0; i < slides.length; i++) { if (i == slides.length - 1) slides[i].nextSlide = slides[0]; else slides[i].nextSlide = slides[i + 1]; } self.current = slides[0]; slides[0].fadeIn(); function slideshowImage(img, slideshow) { img.style.opacity = '0'; this.fadeIn = function() { var i = 0; while (++i <= 40) { window.setTimeout(function() { img.style.opacity = parseFloat(img.style.opacity) + 0.025; }, i * faddingSpeed); } window.setTimeout(function() { slideshow.next(); }, 150 * faddingSpeed + stopTime); } this.fadeOut = function() { var i = 0; while (++i <= 40) { window.setTimeout(function() { img.style.opacity = parseFloat(img.style.opacity) - 0.025; }, i * faddingSpeed); } } } } var self = this; createSlides(slideel); } The dropdown: Code: $(document).ready(function(){ //Fix Errors - http://www.learningjquery.com/2009/01/quick-tip-prevent-animation-queue-buildup/ //Remove outline from links $("a").click(function(){ $(this).blur(); }); //When mouse rolls over $("li").mouseover(function(){ $(this).stop().animate({height:'150px'},{queue:false, duration:600, easing: 'easeOutBounce'}) }); //When mouse is removed $("li").mouseout(function(){ $(this).stop().animate({height:'50px'},{queue:false, duration:600, easing: 'easeOutBounce'}) }); }); Object.prototype.addEvent = function(evtType, func) { if (this.addEventListener) { this.addEventListener(evtType, func, true); } else if (this.attachEvent) { this.attachEvent('on' + evtType, func); } else { this['on' + evtType] = func; } } And these are files that came with the dropdown that need to be included: - jquery.js - jquery-1.txt This is just a library right? |