Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

hasegawa posted:

Alright, I'm trying to do a simple form validation for a drop box. I want it to give a "Hey choose something stupid" if the value is still "Select One" when the user clicks submit. With the current code, it allows the user to go to the next page regardless of what they choose in the dropdown box. I've tried several different javascript validators, but none of them seem to work with this.

I'm not sure why it isn't working, is it something related to using php ECHO statements instead of regular html <select><option> to create the dropdown list?

How would the browser know what document.term is?

Make sure you are putting in LOTS of debug when learning / trying something new. If you added stuff to your code like so:
code:

function validateForm(){
 window.console.log("Function called");
 window.console.log("I think document.term is", document.term );
window.console.log("I think document.term.selectedIndex  is", document.term.selectedIndex );
 if(document.term.selectedIndex=='0')
 {
    alert("Please select an Item.");
    document.term.focus();
    return false;
  }
  window.console.log("I would have submitted" );
  return false;
}
You'd quickly see what the problem is.

EDIT with solution:

code:
9	<script>
10	function validateForm(){
11	 var el = document.getElementById('termSel');
12    // now we have a reference to that SELECT element
13	 if(el.selectedIndex=='0')
14	 {
15	    el.focus();
16	    return false;
17	  }
18	  return true;
19	}
20	</script>


23	 <form onsubmit="return validateForm()" action="" method="post">
24	  <select name="term" id="termSel">
25	   <option>Pie</option>
26	   <option>Cake</option>
27	   <option>Poop</option>
28	   </select>
29	  <input type="submit" />
30	 </form>

Lumpy fucked around with this message at 22:52 on Apr 25, 2010

Adbot
ADBOT LOVES YOU

Blinkz0rz
May 27, 2001

MY CONTEMPT FOR MY OWN EMPLOYEES IS ONLY MATCHED BY MY LOVE FOR TOM BRADY'S SWEATY MAGA BALLS
Doing some fun javascript with Google Maps v3. Currently I have it set up so that if you click a marker, it issues an AJAX request and loads info about that marker into a div next to the map. What I want to do is highlight the marker that is associated with the report being displayed.

My first thought was to use a maps event listener to trap the click and swap the icon, like so:
code:
google.maps.event.addListener(marker, 'click', function() {
    marker.setIcon(newIcon);
    fillDiv(idt, id); // Call the AJAX function
});
The problem that I'm having is that I can't figure out a way to hold that particular marker (marker1) in a way so that if a new marker (marker2) is clicked, I can swap marker1 back to the old icon.

Thoughts?

I'm also using jQuery in other parts of the page, so I'm open to suggestions that use it.

hasegawa
Dec 30, 2008

Wedge Regret

Lumpy posted:

How would the browser know what document.term is?


Ooh, I see! I wasn't sure how specific I had to be...if merely stating name=term would work or if I needed more precise. Thanks a million!

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

hasegawa posted:

Ooh, I see! I wasn't sure how specific I had to be...if merely stating name=term would work or if I needed more precise. Thanks a million!

No problems. There was a push by MS back when IE6 was new to have any named element be acessable that way ( or something similar like document.all.someName i forget exact syntax ) but the standard is that you have to use document methods to get a reference to elements.

jupo
Jun 12, 2007

Time flies like an arrow, fruit flies like a banana.
A more clean approach would be to pass the form to the validation function:

code:

function validateForm(form) {
    if(form.term.selectedIndex == 0)
    {
        alert("Please select an Item.");
        form.term.focus();
        return false;
    }
    return true;
}

<form onsubmit="return validateForm(this);" action="" method="post">
    <select name="term">
        <option>Pie</option>
        <option>Cake</option>
        <option>Poop</option>
    </select>
    <input type="submit" />
</form>

peepsalot
Apr 24, 2007

        PEEP THIS...
           BITCH!

Blinkz0rz posted:

Doing some fun javascript with Google Maps v3. Currently I have it set up so that if you click a marker, it issues an AJAX request and loads info about that marker into a div next to the map. What I want to do is highlight the marker that is associated with the report being displayed.

My first thought was to use a maps event listener to trap the click and swap the icon, like so:
code:
google.maps.event.addListener(marker, 'click', function() {
    marker.setIcon(newIcon);
    fillDiv(idt, id); // Call the AJAX function
});
The problem that I'm having is that I can't figure out a way to hold that particular marker (marker1) in a way so that if a new marker (marker2) is clicked, I can swap marker1 back to the old icon.

Thoughts?

I'm also using jQuery in other parts of the page, so I'm open to suggestions that use it.
Can't you just use a global currentMarker variable?

roweski
Feb 8, 2010
Hey guys, completely new to Javascript. Using Flux for mac to create a tv based soundboard for shits and giggles. I've laid it all out, but have no idea how to even go about writing javascript, like, at all..
Help appreciated..

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

roweski posted:

Hey guys, completely new to Javascript. Using Flux for mac to create a tv based soundboard for shits and giggles. I've laid it all out, but have no idea how to even go about writing javascript, like, at all..
Help appreciated..

http://javascript.crockford.com/

Buy his book, and read this thread and look for all the other times people have asked this question and follow the suggestions there. Good luck, and have fun learning javascript. It's a neat little language.

Meshak
Apr 14, 2010
After searching for some sort of solution to rounded corners that worked cross-browser and could show image backgrounds behind elements with rounded corners, instead of just basing background color on the background color of the body and thus looking like poo poo, I came up with:

1) I still need to use images for this,
2) I have used GD Library in the past, I have to be able to generate these images automatically and have them inserted where needed
3) I could combine my need for this sort of functionality (gently caress you IE) with learning something.

So, I am trying to make my own code to create transparent rounded corner .gif images with some sort of PHP(GD Library) and AJAX combo. I am still at a "planning"/"find out poo poo" stage, so here are my questions:

Can you, with javascript, chop off the corners of an HTML element so that my fancy transparent, automatically generated .gif images will actually show the background of whatever element has round corners and not just the color of the square element? Is this even necessary? Is this a job for some other language instead, and in that case, any idea which?

To actually put this into action when this is more done, how would I go about it best? My initial idea is simply to wrap a div around whichever element needs round corners and position the corner images absolutely in their relevant corners.

epswing
Nov 4, 2003

Soiled Meat
I use http://www.roundedcornr.com/ which is a non-JS solution. You might want to take a look at the html/css they're generating, and how it works, before building your own.

Haystack
Jan 23, 2005





An alternative is to say "gently caress it" to IE and use the following CSS3 rule.

code:
.rounded {
    border-radius: 8px; //For forwards compatibility
    webkit-border-radius: 8px;  //For webkit based browsers
    -moz-border-radius: 8px; //For firefox
}
This creates nice rounded corners on most non-IE browsers.

Obviously your don't want to do this if a large proportion of your traffic uses IE, or if rounded corners are absolutely necessary for your presentation. However, if you don't mind showing your IE visitors a slightly uglier site, using the above CSS is by far the easiest, most standards compliant way to do rounded borders.

Also, Twitter does it.

Edit: If you're looking for a javascript approach, take a look at the jquery rounded corners tutorial

Haystack fucked around with this message at 04:40 on May 5, 2010

Meshak
Apr 14, 2010
I can't really say "gently caress it" to IE in this case. I figure that once I have this sort of functionality made once, I will never have to bother with this particular issue in IE again and can just wait it out until people get their asses in gear and update to some better browser. (Never)

I've already tried JQuery libraries for rounded corners, though. Generally they insert the CSS you mention if the browser supports it, but in IE they generate corners it seems. Unfortunately, they base the corner background on the background color of the page itself. Setting the background color of the page to transparent simply makes the rounded corners in IE have a white background.

Anyway, I could just get corner images from the services dotted around the net, but part of this is also a learning experience for me.

Necc0
Jun 30, 2005

by exmarx
Broken Cake
this is as much an ajax/java/html question as it is a javascript question but whatever. I'm trying to figure out how to dynamically populate a dropdown list with all the .xml files on the server's main directory. Here's what I have:

the html/javascript file:
code:
<html>
    <head>
        <title>Shakespeare Final Project</title>

        <script type="text/javascript">
            var XMLHttpRequestObject = false;

            var $ = function(id) {
                return document.getElementById(id);
            }

            var req = new XMLHttpRequest();

            var calcNum;

            var message;

            window.onload = function() {
                getPlays();
                
                
                alert("what");
            }

            function getPlays() {
                var url = "getPlayList?file=";
                req.open("GET", url, true);
                req.onreadystatechange = callbackPlayList;

                req.send(null);
            }

            function callbackPlayList() {
                if (req.readyState == 4) {
                    if (req.status == 200) {
                        message = req.responseText;
                        $("playList").innerHTML = message;

                    }
                    else
                    {
                        alert("There was a problem retrieving the XML data:\n" +
                            xmlHttp.statusText);
                    }
                }
            }

        </script>
    </head>

    <body>
        <h1>what</h1>
        <p><span id="playHeader">&nbsp;</span></p>
        <H1><span id="actorHeader">&nbsp;</span></H1>
        <H1><span id="sceneHeader">&nbsp;</span></H1>

        <select name="play" id="playList">
            <option></option>
        </select>

    </body>
</html>
and servlet in question:
code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class getPlayList extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String fname = request.getParameter("file");
        String[] fileNames;
        ServletContext sc = getServletContext();
        String filename = null;
        if (fname != null) {
            filename = sc.getRealPath(fname);
        }

        // Set content size
        PrintWriter out = response.getWriter();
        try {
            if (filename != null) {
                
                File file = new File(filename);

                fileNames = file.list();

                for(int i = 0; i < fileNames.length; i++) {
                    if(fileNames[i].endsWith(".xml")) out.println("<option>" + fileNames[i]+"</option>");
                }

        } finally {
            out.close();
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }
}
any help?

epswing
Nov 4, 2003

Soiled Meat
First tell us where you're stuck. What is happening that you don't want to happen (or what's not happening that you want to happen)?

Necc0
Jun 30, 2005

by exmarx
Broken Cake
I want my servlet to pass back the appropriate code that will be assigned to the javascript variable $("playList") so that it will load the dropdown list with all the xml filenames. I don't know what the proper code is for my servlet to send back nor how my HTML should be handling it.

Necc0
Jun 30, 2005

by exmarx
Broken Cake
to be more specific i'm not sure what to do with the following sections:

how the dropdown list should handle the returning code:
code:
        <select name="play" id="playList">
            <option></option>
        </select>
how the code my servlet is returning should be formatted
code:
for(int i = 0; i < fileNames.length; i++) {
                    if(fileNames[i].endsWith(".xml")) out.println("<option>" + fileNames[i]+"</option>");
                }

LeeJam
Nov 24, 2009
Hi all.

Sorry for the :words:

I'm a bit confused with the question in one of my assignments. I'm not expecting anyone to do my homework for me, but a little nudge in the right direction would be really appreciated.

This is the script:
code:
<html>

<head>

<title>Activity 4.3</title>
<script type="text/javascript">
function validateform()

{

var element;
var flag;
var BikeMoney;
var TVMoney;
var IpodMoney;
var CarPrice;
var TotalMoney;

element=document.getElementsByTagName('input');

flag="OK";

for (counter=0; counter<element.length; counter++)

   	{

      	switch (element[counter].type)

      		{

             	case "submit":

                break;
             	default:
                	if(isNaN(element[counter].value)||(element[counter].value==""))

                  		{

                     		alert("You need to enter a number into " + element[counter].name);flag="NotOK";

                  		}
                  	else
                  		{

                   		BikeMoney=element[0].value;
                   		TVMoney=element[1].value;
                   		IpodMoney=element[2].value;
                   		CarPrice=element[3].value;

		                }
		break;
      		}
	}
if (flag=="OK")

   	{

	if ((BikeMoney<=0) || (TVMoney<=0)||(IpodMoney<=0) || (CarPrice<=0))

      		{

       		alert("Please enter numbers greater than zero");

      		}
      	TotalMoney = parseFloat(BikeMoney) + parseFloat(TVMoney)+ parseFloat(IpodMoney);

      	if (TotalMoney > CarPrice)

		{

        	alert("The total money is " + TotalMoney + " and the car price is " + CarPrice + " and you can afford the car");

      		}

      	else

      		{

        	alert("The total money is " + TotalMoney + " and the car price is " + CarPrice + " and you cannot afford the car");

      		}

    	}

 }
</script>
</head>
<body>
<script>

var NoOfInputs;
var Names = new Array("Bike Money", "TV Money", "Ipod Money", "Car Price");

document.write ("<form name='inputform'><br><table>");

NoOfInputs = 0;

while  (NoOfInputs<=3)

	{

       	document.write("<tr><td>Enter money from " + Names[NoOfInputs] + " sale</td><td>" + "<input type='text' name='" + Names[NoOfInputs] + "'></td></tr>");

      	NoOfInputs=NoOfInputs +1;

	}
document.write ("<tr><td></td><td><input type='submit'value='Submit Details' onclick=validateform()></td></tr></table></form>");
</script>

</body>

</html>

The script is supposed to allow me to input some numbers, while checking if there is any negative numbers. If there are some negative numbers, it pops up a box telling me to use numbers greater than zero.

Now, apart from deleting it and starting all over again, here's what I have to do.

Check for semantic errors and then fix them. Simple huh?

I'm a stupid newbie though and do not have a great idea of what the semantic errors could be.

If someone could point me in the right direction, I'm sure I could finish it, but I need a little help to get going.

Thanks

Lee

Necc0
Jun 30, 2005

by exmarx
Broken Cake
start at the beginning of the program and move an alert statement line by line to make sure everything is functioning how it should be.

javascript is kind of a pain that way, but it will work.

edit: I'm kind of wondering what your teacher means by 'semantic' errors as well

Jonnty
Aug 2, 2007

The enemy has become a flaming star!

Necc0 posted:

edit: I'm kind of wondering what your teacher means by 'semantic' errors as well

Errors where the syntax is correct, but the meaning isn't.

Syntax error:

code:
if (a > 0 { 
  alert("a is positive!"); 
}
Semantic error:

code:
if (a < 0) { 
  alert ("a is positive!"); 
}

LeeJam
Nov 24, 2009

Necc0 posted:

start at the beginning of the program and move an alert statement line by line to make sure everything is functioning how it should be.

javascript is kind of a pain that way, but it will work.

edit: I'm kind of wondering what your teacher means by 'semantic' errors as well

I'm sorry, but I'm not entirely sure how to do that. Is it something like
code:
alert('debug: a');
at the beginning of each function? (from a quick google)

I think semantic errors are supposed to be a bit like syntax errors?

^^efb

Necc0
Jun 30, 2005

by exmarx
Broken Cake

LeeJam posted:

I'm sorry, but I'm not entirely sure how to do that. Is it something like
code:
alert('debug: a');
at the beginning of each function? (from a quick google)

I think semantic errors are supposed to be a bit like syntax errors?

kind of. go through the code line by line and ask yourself what you think the code is supposed to be doing. after each line, put an alert statement that prints out the variable values to make sure they are actually what they're supposed to be.

this is a really monotonous way of checking the code but it will work.

Necc0
Jun 30, 2005

by exmarx
Broken Cake
i've already found a couple. you don't even have to do my 'alert' method just go through it slowly, line by line, and ask yourself what you think the code *should* be doing versus what it actually is.

Necc0
Jun 30, 2005

by exmarx
Broken Cake
I'll be honest I really need help with my problem this thing is due tomorrow and I'm only having a few issues I need resolved. I have no idea how to handle these few things though because I procrastinated and it's too late to ask my prof.

LeeJam
Nov 24, 2009

Necc0 posted:

I'll be honest I really need help with my problem this thing is due tomorrow and I'm only having a few issues I need resolved. I have no idea how to handle these few things though because I procrastinated and it's too late to ask my prof.

It's way too complicated for me :)

Thanks for the help though, I really appreciate it.

Peanut and the Gang
Aug 24, 2009

by exmarx

Necc0 posted:

this is as much an ajax/java/html question as it is a javascript question but whatever. I'm trying to figure out how to dynamically populate a dropdown list with all the .xml files on the server's main directory.

any help?

JS snip:
var url = "getPlayList?file=";

Java snip:
String fname = request.getParameter("file");

I don't know much about java servlets, but to me it looks like your not sending a filename through HTTP GET, so fname is evaluating to null.

Either way, try using addons such as Firebug or HttpFox and watch the ajax traffic to see if the java is returning a bunch of <option> tags like it should.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Necc0 posted:

start at the beginning of the program and move an alert statement line by line to make sure everything is functioning how it should be.

javascript is kind of a pain that way, but it will work.

edit: I'm kind of wondering what your teacher means by 'semantic' errors as well

Even better, use Webkit's built in javascript debugger ( or whatever the best add-on one for Firefox is these days.. still Firebug? ) and save yourself having to put alerts all over the place!

Also, the first "error" in that script is the formatting...

Lumpy fucked around with this message at 05:17 on May 6, 2010

LeeJam
Nov 24, 2009

Lumpy posted:

Even better, use Webkit's built in javascript debugger ( or whatever the best add-on one for Firefox is these days.. still Firebug? ) and save yourself having to put alerts all over the place!

Also, the first "error" in that script is the formatting...

Yeah, I know it's awful. I'm only working with what was given to me.

It's supposed to check for negative numbers and get you to re-enter the numbers if you have done so.

Necc0
Jun 30, 2005

by exmarx
Broken Cake

barbarianbob posted:

JS snip:
var url = "getPlayList?file=";

Java snip:
String fname = request.getParameter("file");

I don't know much about java servlets, but to me it looks like your not sending a filename through HTTP GET, so fname is evaluating to null.

Either way, try using addons such as Firebug or HttpFox and watch the ajax traffic to see if the java is returning a bunch of <option> tags like it should.

it's supposed to be null because all the xml files are located in the server's default directory. technically I could pass nothing at all and it would still work but I did that just for good design.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

LeeJam posted:

Yeah, I know it's awful. I'm only working with what was given to me.

It's supposed to check for negative numbers and get you to re-enter the numbers if you have done so.

Fun thing is, goofy braces can actually cause Bad Stuff in javascript. Take this example shamelessly stolen from Crockford's "java script: The Good Parts" talk...

code:
function returnSomeVal()

{
  return

  {
    someKey: "someVal:"
  }

}

alert( returnSomeVal() );
Guess what you see in your alert.

MononcQc
May 29, 2007

I'm writing the JS for a chat app I'm working on in my free time, and I need to have Ids that change according to user submitted data.

This is usually something retarded that I would not do, but I don't see myself having much of a choice.

code:
var txt = '<div class="chut">'+
            '<div class="log" id="chut_'+user_id+'"></div>'+
            '<textarea id="chut_'+user_id+'_msg"></textarea>'+
            '<label for="chut_'+user_id+'_to">To:</label>'+
            '<input type="text" id="chut_'+user_id+'_to" value='+user_id+' readonly="readonly" />'+
            '<input type="submit" id="chut_'+user_id+'_send" value="Message"/>'+
          '</div>';
What would be the best way to escape user_id to avoid any kind of XSS or avoid breaking HTML? Right now I'm using the built-in escape() function, but I'm not sure of how good this is supposed to be.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

MononcQc posted:

I'm writing the JS for a chat app I'm working on in my free time, and I need to have Ids that change according to user submitted data.

This is usually something retarded that I would not do, but I don't see myself having much of a choice.


What would be the best way to escape user_id to avoid any kind of XSS or avoid breaking HTML? Right now I'm using the built-in escape() function, but I'm not sure of how good this is supposed to be.

The "right" answer will depend on what you allow usernames to be. If usernames are email addresses, then you can do strict checking on that for instance. If it's arbitrary, you have a lot more work.

Here's a good little guide I have bookmarked: http://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet

MononcQc
May 29, 2007

Lumpy posted:

The "right" answer will depend on what you allow usernames to be. If usernames are email addresses, then you can do strict checking on that for instance. If it's arbitrary, you have a lot more work.

Here's a good little guide I have bookmarked: http://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet

Yeah, right now (as this is still a prototype), I expected any character to be valid, but using it in ID puts a restriction on what I can use. I couldn't do any efficient escaping or encoding (like base64) without breaking the HTML. Putting assumptions about what is allowed will be necessary.

From that point I figure it's more about filtering than escaping.

Theler
Aug 8, 2009
I having a javasript/jquery problem with Firefox.

These functions highlight and dehighlight all given classes on a page. It works in IE and Chrome, and it *used* to work in Firefox as well until now where it just doesn't. The function just isn't getting executed at all when I mouseover. Help is very much appreciated.
code:
        function highlight(c) {
            var s = "." + c;
             $(s).css("background-color", "aqua");
        }
        function deHighlight(c) {
            var s = "." + c;
            $(s).css("background-color", "");
        }

      <span onmouseover="highlight('rollbox')" onmouseout="deHighlight('rollbox')" class="rollbox"> Blahblah highlighted text </span>

peepsalot
Apr 24, 2007

        PEEP THIS...
           BITCH!

Theler posted:

I having a javasript/jquery problem with Firefox.

These functions highlight and dehighlight all given classes on a page. It works in IE and Chrome, and it *used* to work in Firefox as well until now where it just doesn't. The function just isn't getting executed at all when I mouseover. Help is very much appreciated.
code:
        function highlight(c) {
            var s = "." + c;
             $(s).css("background-color", "aqua");
        }
        function deHighlight(c) {
            var s = "." + c;
            $(s).css("background-color", "");
        }

      <span onmouseover="highlight('rollbox')" onmouseout="deHighlight('rollbox')" 
class="rollbox"> Blahblah highlighted text </span>
Works for me (click the preview button to test), are you including the jquery library?

Anyways, if you are going to use jQuery, you should really learn to not mix content with behavior. The events should be registered in your script, not via html attributes.

peepsalot fucked around with this message at 18:38 on May 12, 2010

Blinkz0rz
May 27, 2001

MY CONTEMPT FOR MY OWN EMPLOYEES IS ONLY MATCHED BY MY LOVE FOR TOM BRADY'S SWEATY MAGA BALLS

peepsalot posted:

Works for me (click the preview button to test), are you including the jquery library?

Anyways, if you are going to use jQuery, you should really learn to not mix content with behavior. The events should be registered in your script, not via html attributes.

Seriously.

JQuery makes event handlers a million times easier. Case in point, here's how you'd do what Theler is trying to do.

code:
$(".rollbox").mouseover(function() {
    $(this).css("background-color", "aqua");
  }).mouseout(function() {
    $(this).css("background-color", "");
  });
In addition to being a really easy way to add event handlers, jQuery makes it so you don't have to pass back the name of the element to the function. It's a much cleaner way of working with the DOM.

Theler
Aug 8, 2009
Thanks for the advice on using JQuery better as obvious I haven't really used it much. The problem was in fact though with the ASP.net test server that Visual Studio runs. It works everywhere but there.

Theler fucked around with this message at 11:42 on May 14, 2010

ElCondemn
Aug 7, 2005


I'm writing a little app that lets me make a list of all the ports on network/pdu/whatever equipment and I'm having a little trouble figuring out the recursion.

Basically I want to take input and spit it out into arrays like these examples

code:
input: 1 - 5
output: 1, 2, 3, 4, 5

input: 1/1 - 2/5
output: 1/1, 1/2, 1/3, 1/4, 1/5, 2/1, 2/2, 2/3, 2/4, 2/5

input: 1/0/1 - 1/0/5
output: 1/0/1, 1/0/2, 1/0/3, 1/0/4, 1/0/5
This isn't really a javascript specific question as much as it's a recursion question. Normally I know how deep the recursion needs to go and I can work with that but in this case it can recurse as many times as there are / delimiters and I'm stuck.

Edit: Ok, this wasn't that hard I was just not thinking properly. Now that it's in an array I can print it out in the correct format and I have the correct number of entries.
code:
function recurseArray(start, end) {
	var tempArray = new Array();

	for ( var i = 0; i <= (end[0] - start[0]); i++) {
		var startNum = start[0] * 1;
		var currNum = startNum + i;

		if (start.length > 1) {
			var startArray = start.slice(1);
			var endArray = end.slice(1);

			tempArray[currNum] = recurseArray(startArray, endArray);
		} else {
			tempArray[currNum] = currNum;
		}
	}

	return tempArray;
}
Edit 2 this adds an array with each port formatted as they're supposed to be:
code:
function recurseArray(start, end) {
	var itemList = new Array();
	var recurseList = new Array();
	
	for ( var i = 0; i <= (end[0] - start[0]); i++) {
		var startNum = start[0] * 1;
		var currNum = startNum + i;

		if (start.length > 1) {
			var startArray = start.slice(1);
			var endArray = end.slice(1);

			var recurseResult = recurseArray(startArray, endArray);
			recurseList[currNum] = recurseResult[0];
			
			for ( var n in recurseResult[1] ) {
				itemList.push( currNum + '/' + recurseResult[1][n] );
			}
		} else {
			recurseList[currNum] = currNum;
			itemList.push( currNum );
		}
	}
	
	return new Array( recurseList, itemList );
}

ElCondemn fucked around with this message at 01:55 on May 18, 2010

karms
Jan 22, 2006

by Nyc_Tattoo
Yam Slacker
php:
<?
<select id="a">
    <option>1</option>
    <option>2</option>
    <option>3</option>
</select>
<script>
obj = function()
{
    this.change_now = function()
    {
        console.log('Where does /this/ point to?');
        console.log(this);
        
        this.say_hooray(); // hj;alp
    }
    this.say_hooray = function()
    {
        alert('Hooray!');
    }
}

an_object = new obj();

document.getElementById("a").onchange = an_object.change_now;
</script>?>
I've got an object that has a function, an_object.change_now(). You can see that I call this function from an onChange event on the select element. I want to be able to call say_hooray() from change_now() but as you can see, this isn't easy. The reference to the object has become the reference to the select element.

I know I could do an_object.say_hooray(), but in the real world that doesn't work since I don't know the variable name beforehand.

Is there a way to grab a reference to the original instance of obj even if this points to something else?

karms fucked around with this message at 14:54 on May 21, 2010

Vanadium
Jan 8, 2005

document.getElementById("a").onchange = function() { return an_object.onchange(); }; :toot:

Adbot
ADBOT LOVES YOU

karms
Jan 22, 2006

by Nyc_Tattoo
Yam Slacker
Gah! :rolleye:

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply