Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 14 of 14
  1. #1
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    3,020
    Thanks
    56
    Thanked 566 Times in 563 Posts

    passing plus or minus as a variable

    google is not my friend on this one

    if I wanted to set a variable with radio buttons to decide whether a function adds or subtracts, I know I can't do this:

    Code:
    <body>
    
    <input type="radio" name ="op" onclick="op='-'">count up: <input type="radio" name ="op" onclick="op='+'">
    
    <script type="text/javascript">
    
    var op;
    
    function calc() {
    start=start op 1000;
    	}
    </script>
    </body>
    but is there something I can do, without getting all if/elsey?

  • #2
    Regular Coder Apothem's Avatar
    Join Date
    Mar 2008
    Posts
    380
    Thanks
    36
    Thanked 25 Times in 25 Posts
    Yes. There is such a thing called eval (ref)

    Edit: Oh and, I would like to mention that there is nothing stopping people from altering your variable to anything that isn't '+' or '-' either. Though that shouldn't matter for this case.

  • #3
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    3,020
    Thanks
    56
    Thanked 566 Times in 563 Posts
    I don't really understand your edit, but anyway...

    are you talking about this:

    Code:
    start=eval(start op 1000);
    because I get a "missing ) after argument list" error with that...

  • #4
    Regular Coder Apothem's Avatar
    Join Date
    Mar 2008
    Posts
    380
    Thanks
    36
    Thanked 25 Times in 25 Posts
    Please refer to the reference link. Seeing what you have written has shown me that you've ignored it completely.

    Edit: My edit basically means that there is nothing stopping people from altering the "op" variable to any other string they want, and calling the calc() procedure. Of course, it is just food for thought for future reference when you work with things like AJAX.

  • #5
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    3,020
    Thanks
    56
    Thanked 566 Times in 563 Posts
    no, not completely - I just never used eval before because well, you know.... but anyway
    Code:
    start=eval("start op 1000");
    gives me "missing ; before statement"
    start op 1000

    [edit]: just out of curiosity, how would people change the string value?
    Last edited by xelawho; 12-26-2011 at 07:05 AM.

  • #6
    Regular Coder Apothem's Avatar
    Join Date
    Mar 2008
    Posts
    380
    Thanks
    36
    Thanked 25 Times in 25 Posts
    Maybe I am overthinking things, but you see to have quite a bit of posts (and thanks as well). So I assumed that you would just be able to look at something and understand. My apologies if this was a false assumption.

    Well op is a string. Therefore:
    eval("start = start" + op + "1000;");

    Edit: Well to change the value, people can use some script or input the JS in the browser URL, as such:
    javascript: op = '+ 1; do_what_an_evil_adversary_does;'; calc();
    Last edited by Apothem; 12-26-2011 at 07:15 AM.

  • #7
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    3,020
    Thanks
    56
    Thanked 566 Times in 563 Posts
    wow. eval() is kooky. does what you expect about half the time. no wonder people hate it so much. thanks anyway.

  • #8
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,310
    Thanks
    203
    Thanked 2,563 Times in 2,541 Posts
    eval() is to be used only in desperation! Is this what you want?

    Code:
    <html>
    <head>
    
    <input type="radio" name ="op" onclick="op='-1'; calc();">Count down: <input type="radio" name ="op" onclick="op='1'; calc()">Count up
    
    <script type="text/javascript">
    
    var op;
    var start = 100;
    
    function calc() {
    start= start * op;
    for (var i = 0; i<=9; i++) {
    document.write(Math.abs(start + i) +"<br>")
    }
    }
    
    </script>
    It's good to hear the union jack being played at all the European Championships. - Commentator BBC Radio 2
    Last edited by Philip M; 12-26-2011 at 09:55 AM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • Users who have thanked Philip M for this post:

    xelawho (12-26-2011)

  • #9
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    3,020
    Thanks
    56
    Thanked 566 Times in 563 Posts
    Quote Originally Posted by Philip M View Post
    eval() is to be used only in desperation!
    I think you might be preaching to the choir there

    Math.abs looks like it might be what I'm looking for, but I can't seem to get it working. This is what I'm working on. The if/else I'm trying to replace is in red:

    Code:
    <html>
    <head>
    
    </head>
    <body>
    
    Input the amount of time you want to count down or up from:<br>
    <input type="text" id ="hrs"> Hours<br> 
    <input type="text" id ="mins"> Minutes <br>
    <input type="text" id ="secs"> Seconds <br>
    count down: <input type="radio" checked="checked" name ="op" onclick="op='minus'">count up: <input type="radio" name ="op" onclick="op='plus'">
    <input type="button" value="start timer" onclick="calc()">
    
    <div id="days"></div>
    <div id="hours"></div>
    <div id="minutes"></div>
    <div id="seconds"></div>
    <script type="text/javascript">
    
    var int;
    var op="minus";
    function calc() {
    var hr=document.getElementById("hrs").value*3600000;
    var mi=document.getElementById("mins").value*60000;
    var se=document.getElementById("secs").value*1000;
    start=hr+mi+se;
    showDate();
    int=setInterval(showDate, 1000)
    }
    
    function showDate(){
    var dateString="Fri, 31 Dec 1999 00:00:00 GMT"
    var d = new Date(dateString);
    d.setUTCMilliseconds(start);
    var mytime=d.toUTCString();
    var day=mytime.substr(5,2);
    if (day=="31"){day="0"}
    var hour=d.getUTCHours();
    var minute=d.getUTCMinutes()
    var second=d.getUTCSeconds();
    
    document.getElementById("days").innerHTML="days: "+day;
    document.getElementById("hours").innerHTML="hours: "+hour;
    document.getElementById("minutes").innerHTML="minutes: "+minute;
    document.getElementById("seconds").innerHTML="seconds: "+second;
    
    if (start==0){
    alert("time's up!");
    clearInterval(int);
    		}
    op=="minus"?start=start - 1000:start=start + 1000;
    	}
    
    </script>
    
    </body>
    </html>

  • #10
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    3,020
    Thanks
    56
    Thanked 566 Times in 563 Posts
    never mind... turned out to be a lot simpler than I thought

    Code:
    count down: <input type="radio" checked="checked" name ="op" onclick="op='-1000'">count up: <input type="radio" name ="op" onclick="op='+1000'">
    
    var op="-1000";
    
    start=start+Number(op);

  • #11
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,664
    Thanks
    80
    Thanked 4,641 Times in 4,603 Posts
    But a more general answer:
    Code:
    <label><input type="checkbox" onclick="op=-1"/> Count down</label>
    <label><input type="checkbox" onclick="op=+1"/> Count up</label>
    ...
    
    start = start + ( op * increment );
    Did you not realize that if you multiply by either +1 or -1 then you achieve your goal of increment/decrementing by some value?

    Having said that, I *really* think a more straightforward answer is the one you used in your post #9.

    Though I would probably have done the following as even more straightforward:
    Code:
    var doIncrement = true;
    
    function() {
        ...
        if ( doIncrement ) { start += increment; } else { start -= increment; }
        ...
    }
    ...
    <label><input type="checkbox" onclick="doIncrement=false;"/> Count down</label>
    <label><input type="checkbox" onclick="doIncrement=true;"/> Count up</label>
    I'm much in favor of clear coding over clever coding. And I really think that JS programmers seem to avoid the simple use of boolean variables too much. There's nothing much simpler than if ( someBooleanVariable ) { ... } else { ... } so why make it more complex?

    Oh...and I don't really like your "final" solution, because if you ever have to change the increment/decrement value you have to (a) change the HTML, not just the JS and (b) change two places instead of just one. But it is at least a simple solution.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #12
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,664
    Thanks
    80
    Thanked 4,641 Times in 4,603 Posts
    Actually, I dislike your "final" solution for another reason: It misuses the trinary operator as an if...else.

    If you are going to use the trinary operator, use it as one:
    Code:
        start += ( op=="minus" ? -1000 : +1000 );
    But I still like the if...else... based on a simple boolean value better.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #13
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    3,020
    Thanks
    56
    Thanked 566 Times in 563 Posts
    Quote Originally Posted by Old Pedant View Post
    Did you not realize that if you multiply by either +1 or -1 then you achieve your goal of increment/decrementing by some value?
    Not really. I fact, looking back on this thread I realize that it was much more of a 7th grade math problem than a javascript problem that I was facing.

    I appreciate your comments about code maintenance, and I'll bear them in mind in the future. Being that this code is for counting seconds, though, I can't really imagine a circumstance where I would want to change that 1000 figure.

    thanks for the various approaches, though - it's always nice to see different ways you can do the same thing

  • #14
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,664
    Thanks
    80
    Thanked 4,641 Times in 4,603 Posts
    Being that this code is for counting seconds, though, I can't really imagine a circumstance where I would want to change that 1000 figure.
    What? You've never heard of having to adjust the calendar by a few milliseconds every year? <grin/>

    Okay, point conceded on the 1000 thing.

    The real problem here is that there are so darned many ways to solve the problem that in fact it boils down to picking one you like and understand. I will say that Apothem's suggestion to use eval() seems like the biggest case of overkill.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •