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.
Page 1 of 2 12 LastLast
Results 1 to 15 of 25
  1. #1
    New Coder
    Join Date
    Aug 2012
    Posts
    48
    Thanks
    18
    Thanked 0 Times in 0 Posts

    Loading and changing variables?

    I'm having a little problem getting the concept down for this.
    Lets say I have two boxes, and a button. When I click the button I want variable X to load in Box 1. If I click the button again and box 1 is full I want the variable to be loaded in box 2.

    That's just to start. In anycase I know I'm getting this completely wrong, but I was wondering if anyone could point me in the right direction of reading materials or could give me a short run down.

    Code:
    function boxWrite2(){
    var x="";
    var x2=2;
    
    
    if (x2<1)
    { 
    x="2df";
     document.getElementById("datz2").innerHTML=x;
    }
    else if (x2=<2
    {
    x=32;
    x2=0;
     document.getElementById("datz3").innerHTML=x;
    }
    else {
    x=8;
    document.getElementById("datz2".innerHTML=x;
    }
    }
    I get that this is completely wrong. I'm having a bit of an issue understanding how to create constant variable, then manipulate it so future code sees the updated variable, and then how to toggle it from the same button in a sense :S
    Last edited by 7Blake; 06-06-2013 at 07:32 PM.

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    You weren't too far off. One line wrong:
    Code:
    else if (x2 <= 2 )
    And then your var x2 = 2 ahould be var x2 = 0 and it must be moved *OUT* of the function.

    That is, any time you declare a var inside a function, it lasts only so long as that function is "live". When the function ends, the variable goes away. And the next time you call the function, the variable is re-created from scratch.

    However...that doesn't really meet the specs you posted: To wit, "...box 1 is full...".
    How do you know some *OTHER* completely unrelated code didn't stuff something into box 1 in the meantime? To do what you stated, you would need to actually test the *contents* of box 1, not just some flag. And if you did that, then you wouldn't need to worry about having a global vs. local variable.
    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.

  • Users who have thanked Old Pedant for this post:

    7Blake (06-06-2013)

  • #3
    New Coder
    Join Date
    Aug 2012
    Posts
    48
    Thanks
    18
    Thanked 0 Times in 0 Posts
    Wow thanks for the reply I'm still a bit fuzzy over what you wrote so I'm reading it a few dozen more times.

    So when the function ends, the variable is returned to it's previous state of being x="";. I sorta get that.

    So does that mean I have to find a way of testing the content of Box 1 in a new function to see if the content should then be loaded in Box 2 if Box 1 is "full". Would that be similar to string length testing in a sense? And if it is could that be applied to the same button?

    Like in concept, "button1" is pressed, loads data into box1. "button1" is pressed again, reads data in box1, then proceeds to write to box2.

    Is that effectively an if/elseif/else function with a toggle? :S

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    So when the function ends, the variable is returned to it's previous state of being x="";.
    Actually, the variable simply disappears. It has no state of being, whatsoever.

    *EACH* time you call the function, all local variables (where the var keyword is used inside the function) are created from scratch.

    *********
    Yes, you can test the contents of box1, looking for empty or (for that matter) any specific content.

    So let's say box1 is not empty. So you will then proceed to put something in box2.

    But what happens if box2 is not empty? Do you move on to box3? Go back to box1? Or just then do nothing?

    If you truly want a toggle--going back and forth and back and forth--then you won't be able to just base it on content/no-content. Because once box 2 is filled, you will always end up then changing box 1. So in this case, using a variable for the toggle makes sense.
    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.

  • Users who have thanked Old Pedant for this post:

    7Blake (06-08-2013)

  • #5
    New Coder
    Join Date
    Aug 2012
    Posts
    48
    Thanks
    18
    Thanked 0 Times in 0 Posts
    Thanks, I figured it out now

    I was wondering is there a way to get javascript to just detect content inside of a HTML element?
    Like getElementById("")innerHTML, and for example it's a image

    Then using the if to make javascript compare the content? I only know how to do it with numbers and strings, but im unsure how to do it with images.
    Also is there a way to in a single if statment have two compared equations?

    Like ' if (x==3 OR x==5) ' Is this possible?

  • #6
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,730
    Thanks
    202
    Thanked 2,508 Times in 2,486 Posts
    if (document.getElementById("myimage").src = "someimage.jpg") {
    // do something

    if (x==3) || (x==5) {
    // do something

    All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit.
    Last edited by Philip M; 06-08-2013 at 11:58 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:

    7Blake (06-08-2013)

  • #7
    New Coder
    Join Date
    Aug 2012
    Posts
    48
    Thanks
    18
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Philip M View Post
    if (document.getElementById("myimage").src = "someimage.jpg") {
    // do something

    if (x==3) || (x==5) {
    // do something

    All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit.
    blah it's so simple :P I was for some reason assuming only arithmetic could be used,... despite defining and comparing variables earlier :P thanks Phillip for both parts

  • #8
    Senior Coder
    Join Date
    Mar 2005
    Location
    Portsmouth UK
    Posts
    4,466
    Thanks
    3
    Thanked 495 Times in 482 Posts
    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" xml:lang="en" lang="en">
    
    <head>
      <title></title>
    </head>
    
    <body>
    <img id="myimage" src="http://www.vicsjavascripts.org.uk/StdImages/Egypt5.jpg" />
    
    <script type="text/javascript">
    
    // this will not work
    //if (document.getElementById("myimage").src = "Egypt5.jpg") {
    //}
    
    // this is closer but will not work
    if (document.getElementById("myimage").src == "Egypt5.jpg") {
     alert('found 1')
    }
    
    // but as the src is the full file path + file name we need to identify just the file name
    var src=document.getElementById("myimage").src;
    if (src.slice(src.lastIndexOf('/')+1) == "Egypt5.jpg") {
     alert('found 2')
    }
    
    </script>
    </body>
    
    </html>
    JScript Language Reference

    --------------------------------------------------------------------------------

    slice Method (String)
    Returns a section of a string.

    stringObj.slice(start, [end])

    Arguments
    stringObj

    Required. A String object or literal.

    start

    Required. The index to the beginning of the specified portion of stringObj.

    end

    Optional. The index to the end of the specified portion of stringObj.

    Remarks
    The slice method returns a String object containing the specified portion of stringObj.

    The slice method copies up to, but not including, the element indicated by end. If start is negative, it is treated as length + start where length is the length of the string. If end is negative, it is treated as length + end where length is the length of the string. If end is omitted, extraction continues to the end of stringObj. If end occurs before start, no characters are copied to the new string.

    Example
    In the following example, the two uses of the slice method return the same result. In the second example, negative one (-1) points to the last character in str1 as the ending point.

    str1.slice(0)
    str2.slice(0,-1)
    Requirements
    Version 3

    See Also
    Array Object | slice Method (Array) | String Object Methods

    Applies To: String Object


    --------------------------------------------------------------------------------
    ©2000 Microsoft Corporation. All rights reserved.
    Vic

    God Loves You and will never love you less.

    http://www.vicsjavascripts.org/Home.htm

    If my post has been useful please donate to http://www.operationsmile.org.uk/

  • Users who have thanked vwphillips for this post:

    7Blake (06-08-2013)

  • #9
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,730
    Thanks
    202
    Thanked 2,508 Times in 2,486 Posts
    Whoops! Sorry, Vic and 7Blake. Mea culpa!

    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.

  • #10
    New Coder
    Join Date
    Aug 2012
    Posts
    48
    Thanks
    18
    Thanked 0 Times in 0 Posts
    Hey thanks for that. I thought I'd note about the &&(and) ||(or) that I was having trouble getting it to work.

    I was going if (x=1) && (d=3); but it's (x=1 && d=3).

    I sorta got the image to work by varifying that the specific image is inplace.

    Code:
    <!DOCTYPE html>
    <html>
    <body>
    <script>
    function changeImage()
    {
    element=document.getElementById('myimage');
     var Y=document.getElementById("demo").innerHTML;
     if  (Y=="2" && element.src.match("Egypt5"))
      {
       document.getElementById("demo").innerHTML="x2";
      }
    
    else if (Y=="3"  && element.src.match("Egypt5"))
      {
       x="2";
       document.getElementById("demo").innerHTML=x;
      }
    
    else if(Y=="x2" && element.src.match("Egypt5"))
      {
       x="preludestop";
       document.getElementById("demo").innerHTML=x;
      }
    
    else if(Y=="test" && element.src.match("Egypt5"))
      {
       x="3";
       document.getElementById("demo").innerHTML=x;
      }
    else 
    {
       document.getElementById("demo").innerHTML="stop";
    }
    }
    </script>
    
    <img id="myimage" onclick="changeImage()"
    src="http://www.vicsjavascripts.org.uk/StdImages/Egypt5.jpg" width="100" height="180">
    
    <p id="demo">test</p>
    
    </body>
    </html>

    Is this appriopriate? And is there a way to just discover generic "image" content, or anyform of content? or should I write an opposing code to work with No content? (is that null or undefined? :S )

    Im going to have a look at the slice command(?) you've shown. Thanks

  • #11
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,730
    Thanks
    202
    Thanked 2,508 Times in 2,486 Posts
    The argument of a regex match() is a regular expression, not a string. If no match is found, returns null. You could certainly use a regex instead of Vic's slice method:-

    Code:
    <div = "mydiv">
    <img id = "myimage" src = "One.jpg">
    </div>
    
    <script type = "text/javascript">
    
    var src=document.getElementById("myimage").src;
    alert (src);  // for testing
    var n = src.match(/One\.jpg$/);  // note that the dot must be escaped to make it a literal
    alert (n); // for testing
    if (!n) {
    alert ("Not found");
    }
    
    </script>
    Note that the source of the image is the one specified, and it may not actually exist in that directory or at all. In other words, the path may not lead to an actual image.
    Last edited by Philip M; 06-08-2013 at 07:00 PM.

    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.

  • #12
    Senior Coder Logic Ali's Avatar
    Join Date
    Sep 2010
    Location
    London
    Posts
    1,028
    Thanks
    0
    Thanked 207 Times in 202 Posts
    Quote Originally Posted by Philip M View Post
    The argument of a regex match() is a regular expression, not a string.
    I'm afraid that is at variance with the actualité: A Link

  • #13
    New Coder
    Join Date
    Aug 2012
    Posts
    48
    Thanks
    18
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Philip M View Post
    The argument of a regex match() is a regular expression, not a string. If no match is found, returns null. You could certainly use a regex instead of Vic's slice method:-

    Code:
    <div = "mydiv">
    <img id = "myimage" src = "One.jpg">
    </div>
    
    <script type = "text/javascript">
    
    var src=document.getElementById("myimage").src;
    alert (src);  // for testing
    var n = src.match(/One\.jpg$/);  // note that the dot must be escaped to make it a literal
    alert (n); // for testing
    if (!n) {
    alert ("Not found");
    }
    
    </script>
    Note that the source of the image is the one specified, and it may not actually exist in that directory or at all. In other words, the path may not lead to an actual image.
    Starting to lose me... which is cool. I'll look into this once I just get this tid bit down. So essentially there are multipul ways of doing this, but some are going to be more limited than others?

    Is there a way to scan a Div tag for content? I've read there's a method with jQuery but is there something that can work in javascript?

    Like " if ( //div content= nothing ) ? I can't think of anything atm because I'm a bit unsure how javascript reads <div></div> when there's nothing in it vs <div>"string"</div> for example.


    *edit*

    Im starting have some trouble.
    Why is this not working now when I try to update a Divbox with an image? If on the first "if" statment I make it write a string or number it will read it that new string/number when I initate the function again. But when I load an image from the first "if" statment, it refuses to match the new image in the "else if".

    Is there some rule I'm unaware of?
    Last edited by 7Blake; 06-08-2013 at 11:38 PM.

  • #14
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    Quote Originally Posted by 7Blake View Post
    ...

    I was going if (x=1) && (d=3); but it's (x=1 && d=3).

    ...
    Ummm...that will never work.

    Even inside an if( ... ), JavaScript (and Java and C and C++ and PHP and C# and ...) *ALWAYS* treats the operator = as an ASSIGNMENT STATEMENT!

    So if you were to code
    Code:
        if ( x = 1 && d = 3 )
    then
    (a) After executing the if your variable x would *ALWAYS* contain the value 1 and your variable d would *ALWAYS* containg the value 3!!
    (b) Because of the assignments, your if ends up being equivalent to if ( 1 && 3 ) and so it is ALWAYS TRUE.

    *******

    One way to prevent mistakes like this is to always put the number or contstant value on the LEFT side of the == operator:
    Code:
        if ( 1 == x && 3 == d )
    That works just fine. But if you accidentally use =, then trying to execute
    Code:
        if ( 1 = x && 3 = d )
    would cause a syntax error.
    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.

  • Users who have thanked Old Pedant for this post:

    7Blake (06-09-2013)

  • #15
    New Coder
    Join Date
    Aug 2012
    Posts
    48
    Thanks
    18
    Thanked 0 Times in 0 Posts
    Interesting. I made a mistake when I wrote the correction, I should have used "==" instead of a single "=".

    Are you saying it's safer to write | if (2 == X && 3 == Y) as opposed to (X == 2 && Y == 3) ?

    Yeah. I'm starting to firmly grasp "=" means assignment not equals. Just a bad habit, but it's nice to start understanding and seeing it. So essentially if I had written (x = 3 && y = 5), I've assigned variable x to == 3 and variable y == 5. But are you saying that this assignment is permanent? So assignments inside the if (...) section are permanent, but assignments in if (..) { x = 3} only last as long as the function is active?

    Would that mean that during the Else if the y variable is changed from it's initial assignment of 2 to 1 permanently. But if the function is re-run, variable y is re-introduced back to 2?( with the same process initiating again? Does this logic apply to global variables? What if y was assigned outside of myFunction, but when myFunction initiates during the else/if re-assignment of Y, does this permanently re-assign y globally or only inside of the function itself?

    Code:
    var y = 5;
    function myFunction()
    {
    var x = 3;
    var y = 5;
    if ( x == 3)
    { document.getElementById("something").innerHTML="test";
    } 
    else if (x == 3 && y = 1)
    { document.getElementById("something").innerHTML="test2";
    } 
    else
    {...}
    }
    :P sorry to ask this again, but if you know, how does javascript read <div id="test"></div> ? Once div.test is converted to a variable, how does javascript read the lack of content inside the div tag so I can create an if statement to equate to nothing.?
    Last edited by 7Blake; 06-09-2013 at 01:41 AM.


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

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