We help IT Professionals succeed at work.

Send SelectedOptionValue parameter from menu to inline js on HTML page - for swapping div content

highab
highab asked
on
313 Views
Last Modified: 2012-05-08
Hi I'm trying to find a quicker way of loading different text refs (external.js files) into a div on a web-base application for a multimedia player (so no bells and whistles). I'm piecing together various code snippets from the internet.

This code is part of the menu that I have changed slightly... it gives me the text I want, dependent on what items I select on the menu, but not where I want it - it seems like it loads the text as a page in its own right, and that's not what I want.

************************************************************************************[code]
function goListGroup(){
for (i=arguments.length-1;i>=0; i--){
if (arguments[i].selectedIndex!=-1){
var selectedOptionvalue=arguments[i].options[arguments[i].selectedIndex].value
if (selectedOptionvalue!=""){

 var scr = document.createElement("script");
              scr.type="text/javascript";
              scr.src= selectedOptionvalue+".js";
             
       var div=document.getElementById("myDiv");
           div.appendChild(scr)
             


break
}
}
}
}

************************************************************************************[/code]


Here is the code on the html page that does get the text I want where I want it... but I have to hard code it in, which means its not practicable for the 1187 files I want to be able to flick between!

************************************************************************************[code]
<div class=text id=myDiv>
<script language="JavaScript1.2" >
myvalue="ManuallyEnteredValue"
insertText(myvalue);
</script>
</div>

function insertText(param){
var scr = document.createElement("script");
            scr.type="text/javascript";
       scr.src= param+".js";
      document.getElementById("myDiv").appendChild(scr);
      }
************************************************************************************[/code]

Is there any way I can get the selectedOptionvalue from the menu (external js) sent to the myvalue parameter (inline js, because it doesn't work if that script isn't in the right place), thus changing the content of my div without having to reload all the menu etc all the time?

I'd appreciate any help, thanks
Comment
Watch Question

Hi highab,

I think that the answer is to pull in the external script via an ajax call.  Then you setup an event handler to do the processing once the script has loaded.  Here is an article that describes this using prototype.js (can be easily ported to jQuery or whatever framework you use):

http://stackoverflow.com/questions/21294/how-do-you-dynamically-load-a-javascript-file-think-cs-include

The idea is to load the content of the ext. js file via ajax, then eval the response from a global scope (window.eval).  Obviously take precautions when releasing this code into production - unsecured window.eval() can potentially be a security weakness.

TheFoot

Author

Commented:
Thanks, but as I said I have no bells and whistles on my PMP... I don't think ajax will work on it and the jquery tree menu I tried just didn't collapse... everything was visible all the time, defeating the point of a space-saving menu!

Author

Commented:
OK I've found this ... it does what I want IF it is on a remote server.... but I want this to be a local thing, I'm a little frazzled by the few explanations I've found about how to change it....


function ahah(url, target) {
  document.getElementById(target).innerHTML = ' Fetching data...';
  if (window.XMLHttpRequest) {
    req = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    req = new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (req != undefined) {
    req.onreadystatechange = function() {ahahDone(url, target);};
    req.open("GET", url, true);
    req.send("");
  }
}  

function ahahDone(url, target) {
  if (req.readyState == 4) { // only if req is "loaded"
    if (req.status == 200) { // only if "OK"
      document.getElementById(target).innerHTML = req.responseText;
    } else {
      document.getElementById(target).innerHTML=" AHAH Error:\n"+ req.status + "\n" +req.statusText;
    }
  }
}

function load(name, div) {
	ahah(name,div);
	}

Open in new window

I think if you simply pass in your URL to this function:

ahah("/yourserver/path/file.js", "id-of-output-element");

You will need to eval the response within the ahahDone() function like:


function ahahDone(url, target) {
  if (req.readyState == 4) { // only if req is "loaded"
    if (req.status == 200) { // only if "OK"
      eval(req.responseText);
    } else {
      document.getElementById(target).innerHTML=" AHAH Error:\n"+ req.status + "\n" +req.statusText;
    }
  }
}

Open in new window

Author

Commented:
Sorry but no it doesn't work. I think you think I still want it on a server. I don't. I want to be able to run the whole thing from one PC on one PC and then transfer it to my PMP.
Hmm.. not sure I follow.

An external resource of any description has to be served up from a server somewhere.  Please describe the exact path top the file you want to load in..

Author

Commented:
file///C:/Users/...............

on MY PC

this is NEVER going to be on a webserver for other people to use... if that was it I'm home and dry already, this works on a remote server.
It can be referenced locally via relative paths.  So for example if your web page is in c:\users\highab\index.html and so is the javascript file, then you can still use ajax with a local relative path.

Please read through the following link, it may provide you with some further help:

http://www.linkedin.com/answers/technology/web-development/TCH_WDD/575359-11146766

.. particularly the third answer down by "Greg H"

Author

Commented:
Thanks but that's still not the answer, I believe XMLHttpRequest requires a server, so I'm looking for something, probably different, that does the same thing.
XMLHttpRequest does not require a server, so long as you use relative paths.  Further reading:

http://seattlesoftware.wordpress.com/2008/01/08/xmlhttprequest-and-local-testing/

There are a couple of caveats with different browsers, this article should outline them for you.

I do not know of any other method to read local files, it is this way for security reasons.  If you are using Internet Exploder, then perhaps you can use the ActiveX object " FileSystemObject"  to access local files..

Author

Commented:
Have been using that document. The code hangs if it is not on an external server.

This is where I got the code. Other people have had the same problem.

http://codesnippets.joyent.com/posts/show/602
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
OK, thanks, I'll play with that and let you know how I get on

Author

Commented:
OK, so I can load a named .js into a named div, but was having problems incorporating that with my 4-level menu.... there again that's a bit by the by because I've been got by the bells and whistles, my PMP, which runs its own version of Opera does not like AJAX so I get nothing more than the "load jquery.js" link

I don't suppose there's a way of loading an ajax library or something onto it is there? or would that be REALLY space-hungry?
What is a PMP?

Author

Commented:
Portable media player... in my case the Archos 605 wifi
Does the PMP not have a built-in web server?  Will your HTML page reside on the device, or are you browsing to this page on another device?

Author

Commented:
No, its a souped-up mp3 player that does fab videos, displays photos and just happens to surf the web via wifi. No reason for it to have a built-in server. Its built-in navigator is opera-branded but is not the same as what you'll find on a PC and yes as I've said before the thing is to be used locally i.e. on the device!
Sorry dude - I've no ideas left!

Best of luck...

Author

Commented:
Found something that said AJAX was supported. So went back to square 1.

Something must be wrong with my code somewhere.

Your extracted zip works on it
Thats good news!

Mind posting your entire page so I can take a look?

Author

Commented:
I'm just fiddling your code. I should be able to find my mistake if I take it one bit at a time.

How I combine it with my menu code, now that's another matter...


I'm assuming I need something like this


function goListGroup(){
for (i=arguments.length-1;i>=0; i--){
if (arguments[i].selectedIndex!=-1){
var selectedOptionvalue=arguments[i].options[arguments[i].selectedIndex].value
if (selectedOptionvalue!=""){


	
$('a#jquerylink').click(function(e){
				e.preventDefault();
				loadFile(selectedOptionvalue+".js", "output");
				return false;
			});
  

break
}
}
}
}

Open in new window

This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Glad I was able to help - thanks for the points..

Author

Commented:
OK, now I'm trying to be really clever.... how do I add a "next" and "back" button to the page, linked to the menu script?

All my js files have the form "text 1.js"

If I'm on "text 22.js" I want the next button to point to "text 23.js" and the back button to point to "text 21.js"
I've tried selectedOptionValue+1 but that gives me "text 221.js" !
var selectedOptionValue = "Text 22.js";
var v_next = "Text " + (parseInt(selectedOptionValue.replace('Text ', '')) + 1);

Author

Commented:
The text changes depending on what is selected.

Basically I want the function to start at the end of the string and look for the first space from the end (because the numbers come after the last space), and then extract the 1, 2 or 3 digit number that comes after the space, and either add 1 to it or subtract 1 from it.

so it finds selectedOptionValue is currently text 22.js   it ignores the .js and sees there is a space before the 22 it then pulls out the 22 and tells the next button to point to text 23.js.

That is possible, right?
The success of whatever algorithm you use to parse the filename, depends on the reliability of the filename rules.  If all filenames consist of TEXT then SPACE then NUMBER then PERIOD then "JS", then yes, your rule will work.  Use substr() and indexOf() to chop the string up to get the number.  You dont have to worry about anything after the NUMBER, so long as it is not numeric; parseInt() will discard the remainder, so loing as the start of the string you give it is numeric.

Good luck.

Author

Commented:
OK, managed to do that, finally!

Now it does what I want it to do for purpose 1.

I have since had another idea for what I can use this for.... so now would like to know how to change this code so that it opens the .js in the div in ANOTHER page that is NAMED

window = newwin

any ideas?
	var loadFile = function(v_filename, v_outputeleid){
			$.ajax({
				url			: v_filename,
				dataType	: "text",
				success		: function(o_data){
					$('#' + v_outputeleid).html(o_data).css({'color': '#000'});
				},
				error		: function(XMLHttpRequest, textStatus, errorThrown){
					$('#' + v_outputeleid).html(textStatus || errorThrown).css({'color': '#f00'});
				}
			});
		} // loadFile()
	 

Open in new window

Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.