Some help for learner

Discussion in 'JavaScript' started by piri00, Jan 13, 2010.

  1. #1
    Hi
    I just would like to get some information in this script.
    Script works fine and I uderstand this script only thing is why in this code txt=txt + coffee.value + " "; need to be txt variable twice? if I delete txt like this txt=coffee.value + " "; script still works fine. I just don't understand what does second txt. txt=txt + coffee.value + " ";

    Thank you for help

    <html>
    <head>
    <script type="text/javascript">
    function createOrder()
    {
    coffee=document.forms[0].coffee;
    txt="";
    for (i=0;i<coffee.length;++ i)
    {
    if (coffee.checked)
    {
    txt=txt + coffee.value + " ";
    }
    }
    document.getElementById("order").value="You ordered a coffee with " + txt;
    }
    </script>
    </head>

    <body>
    <p>How would you like your coffee?</p>
    <form>
    <input type="checkbox" name="coffee" value="cream">With cream<br />
    <input type="checkbox" name="coffee" value="sugar">With sugar<br />
    <br />
    <input type="button" onclick="createOrder()" value="Send order">
    <br /><br />
    <input type="text" id="order" size="50">
    </form>
    </body>

    </html>
     
    piri00, Jan 13, 2010 IP
  2. dimitar christoff

    dimitar christoff Active Member

    Messages:
    882
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    90
    #2
    earlier txt is cast as an empty string, overwriting previous 'orders' - which then keeps the concatenation of the value + " " as string (latter which is not really needed as txt is already a string and values from fields are usually string too - "sugar" and "cream" are 100% string).

    to be honest, this will work as just txt = coffee.value; (as you've discovered) - there's no need to typecast the variable by adding a string to it on either side
     
    dimitar christoff, Jan 14, 2010 IP
  3. piri00

    piri00 Peon

    Messages:
    33
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks for help
     
    piri00, Jan 17, 2010 IP
  4. kipdlid

    kipdlid Member

    Messages:
    144
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    46
    #4
    also be sure to define the variable... var txt= ...
     
    kipdlid, Jan 22, 2010 IP