www.webdeveloper.com
Results 1 to 13 of 13

Thread: javascript drop down menu? help!

  1. #1
    Join Date
    Mar 2012
    Posts
    21

    javascript drop down menu? help!

    Hi all!

    I am making a program that will allow people to purchase tickets. I'm relatively new at this so I'm just practicing with with concert tickets and stuff before going into the real thing.

    I think I have the basis but I'm puzzled with my drop down menu's. I want to have a html drop down but populate the content of it with arrays. How would I go about doing that?

    my code so far..
    Code:
    <html>
    
    <center>
    <br>
    <br>
    <br>
    <h1><FONT COLOR="06799F">Oasis</FONT></h1>
    
    
    <head>
    <script type="text/javascript">
    
    
    //validate the form (name shouldn't be blank)
    
    
    function validate()
    {
    var x=document.forms["form1"]["Name"].value;										//validate the name field
    if (x==null || x=="")
      {
      alert("Please fill in your Name.");												//show message if empty
      return false;
      }
    
    
    var x=document.forms["form1"]["Email"].value;										//validate the email
    var atpos=x.indexOf("@");
    var dotpos=x.lastIndexOf(".");
    if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)								//check for the "@" and "."
      {
      alert("Not a valid e-mail address.");
      return false;
      }
    
    
    var x=document.forms["form1"]["Card"].value;										//validate the card field
    if (x==null || x=="")
      {
      alert("Please fill in your Card number.");										//show message if empty
      return false;
      }
    
    window.location= "thanks.html";
    
    }
    
    function calcTic(frm)
    {
    if (frm.dates.value=="")
    {
    alert("Please choose dates.")
    return;
    }
    else if (frm.tic.value=="")
    {
    alert("Please choose number of tickets.")
    return;
    } 
    else
    {
    var extra=frm.tic.value>3?10:0;
    frm.total.value=""+Number (frm.dates.value*frm.tic.value+extra);
    	}
    }
    
    //session expiry
    
    setTimeout( "_SessionExpired()", 10 * 60 * 1000 );			//expires after 10 mins
    
    function _SessionExpired()
    {
    alert("Session has expired!");						//alerts user
    location.href = "1.html";						//redirects to login page
    }
    
    
    </script>
    
    
    </head>
    
    
    <body>
    
    <!--offer choices-->
    
    <br>
    <br>
    <h4>Select Your Chosen Ticket: </h4>
    
    
    <!--drop down menus-->
    
    <form name = "form1">
    <select name="dates">
    
    <option value="">Select Ticket</option>
    
    <option value=25>Nottingham, 18th July - 25</option>
    <option value=45>Nottingham, 18th July - 45</option>
    <option value=60>Nottingham, 18th July - 60</option>
    <option value=25>Nottingham, 19th July - 25</option>
    <option value=45>Nottingham, 19th July - 45</option>
    <option value=60>Nottingham, 19th July - 60</option>
    
    <option> </option>
    
    
    <option value=45>Glasgow, 21st July - 45</option>
    <option value=60>Glasgow, 21st July - 60</option>
    
    
    <option> </option>
    
    <option value=45>London, 23rd July - 45</option>
    <option value=60>London, 23rd July - 60</option>
    <option value=45>London, 24th July - 45</option>
    <option value=60>London, 24th July - 60</option>
    
    </select>
    
    <!--number of tickets-->
    <br>
    <br>
    <br>
    <br>
    <h4>Select The Number of Tickets:</h4>
    (maximum of 6)
    <br>(Additional 10 fee for 4+ tickets)
    
    <br>
    <br>
    <select name="tic">
    
    <option value="">Select Ticket</option>
    
    <option value=1>1 </option>
    <option value=2>2 </option>
    <option value=3>3 </option>
    <option value=4>4 </option>
    <option value=5>5 </option>
    <option value=6>6 </option>
    
    </select>
    <br><br>
    <input type="button" value="Calculate Price" onclick="calcTic(this.form)"/> 
    
    <br><br><b>Total price:</b> <input name="total"type="text"/>
    <br><br><br><br><br>
    
    
    
    
    <!--form to enter details-->
    
    
    <h2>Please Enter Your Details Below.</h2>
    
    
    <b>Name:</b> <br /><input type="text" name="Name" value="" size="30" maxlength="50" /> <br><br>
    	
    <b>Address:</b><br>
    <input type="text" name="Address1" value="Line 1" size="30" maxlength="50" />
    <br><input type="text" name="Address2" value="Line 2" size="30" maxlength="50" />
    <br><input type="text" name="Address3" value="Town/City" size="30" maxlength="50" />
    <br><input type="text" name="Address4" value="Postcode" size="30" maxlength="50" />
    
    <br><br><b>Telephone:</b> <br /><input type="text" name="Phone" value="" size="30" maxlength="11" /> <br><br>
       
    <b>Email:</b><br><input type="text" name="Email" value="" size="30" maxlength="16" /><br><br>
    
    
    <b>Card Number:</b><br><input type="text" name="Card" value="" size="30" maxlength="16" />
    
    </form>
    
    
    <br><br>
    
    <input type="submit" value="Buy Tickets" onclick="validate();" />													<!--submit button-->
    
    </center>
    
    </body>
    </html>

    I am new to this so if anyone is able to show me how to go about this task and explain it'd be EXTREMELY helpful!


    Thanks in advance!

  2. #2
    Join Date
    Nov 2007
    Posts
    409
    http://www.w3schools.com/jsref/met_select_add.asp

    in a nutshell... (untested - writing it by hand. you'll need to define your array first, of course)

    Code:
    for (i=0;i<myArray.length;i++){
      var x=document.getElementById("mySelect");
      var option=document.createElement("option");
      option.text=myArray[i];
      try {
        // for IE earlier than version 8
        x.add(option,x.options[null]);
      } catch (e) {
        x.add(option,null);
      }
    }

  3. #3
    Join Date
    Mar 2012
    Posts
    21
    nap0leon, I'm not quite sure I understand.

    Is it possible for you to show me an example using my data? I am quite slow sorry ha!

  4. #4
    Join Date
    Nov 2010
    Posts
    978
    where are your arrays?

  5. #5
    Join Date
    Mar 2012
    Posts
    21
    I haven't done any arrays! That's my main area I'm stuck with.
    I'm unsure of how to start them in this context

  6. #6
    Join Date
    Nov 2010
    Posts
    978
    for the array to be useful in this context each element that you want t tyurn into an option should be a subarray and those subarrays should have one element for the text and one for the value of the option, like this:

    Code:
    var tickets=[["Nottingham, 18th July - 25",25],["Nottingham, 18th July - 45",45] ]
    once you have that it is simply a matter of looping through the array and creating new options:

    Code:
    <body>
    <select id="theselect"></select>
    
    <script type = "text/javascript">
    
    var tickets=[["Nottingham, 18th July - 25",25],["Nottingham, 18th July - 45",45] ]
    
    var sel=document.getElementById("theselect")
    for (var i = 0; i < tickets.length; i++) {
    sel.options[i]=new Option(tickets[i][0],tickets[i][1])
    } 
    </script>
    </body>

  7. #7
    Join Date
    Mar 2012
    Posts
    21
    I think I have it all joined up, apart from one part which is calculating the ticket price.

    Would you be able to suggest where I am going wrong with this..
    here's my code so far:
    Code:
    <html>
    <head>
    
    
    </head>
    
    <body>
    
    <select id="theselect"></select>
    
    
    <select id="theselect2"></select>
    
    <script type = "text/javascript">
    
    function calcTic(frm)
    {
    if (frm.theselect.value=="")
    {
    alert("Please choose dates.")
    return;
    }
    else if (frm.theselect2.value=="")
    {
    alert("Please choose number of tickets.")
    return;
    } 
    else
    {
    var extra=frm.theselect2.value>3?10:0;
    frm.total.value=""+Number (frm.theselect.value*frm.theselect2.value+extra);
    	}
    }
    
    
    var tickets=[["Select Ticket (s)"],[" "],["Nottingham, 18th July - 25",25],["Nottingham, 18th July - 45",45],["Nottingham, 18th July - 60",60],["Nottingham, 19th July - 25",25],["Nottingham, 19th July - 45",45],["Nottingham, 19th July - 60",60],[" "],["Glasgow, 21st July - 45",45],["Glasgow, 21st July - 60",60],[" "],["London, 23rd July - 45",45],["London, 23rd July - 60",60],["London, 24th July - 45",45],["London, 24th July - 60",60] ]
    
    var sel=document.getElementById("theselect")
    for (var i = 0; i < tickets.length; i++) {
    sel.options[i]=new Option(tickets[i][0],tickets[i][1])
    } 
    
    
    var ticket_num=[["Select Number of Ticket (s)"],[" "],["1",1],["2",2],["3",3],["4",4],["5",5],["6",6] ]
    
    var sel=document.getElementById("theselect2")
    for (var i = 0; i < ticket_num.length; i++) {
    sel.options[i]=new Option(ticket_num[i][0],ticket_num[i][1])
    } 
    
    
    </script>
    
    
    
    <input type="button" value="Calculate Price" onclick="calcTic(this.form)"/> 
    
    <br><br><b>Total price:</b> <input name="total"type="text"/>
    <br><br><br><br><br>
    
    </body>
    </html>
    Its designed so if there are 4 or more purchases of the ticket and extra 10 will be added to the cost.

  8. #8
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,633
    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>Tickets</title>
    <style type='text/css'>
    body{text-align:center;font-family:Georgia,Verdana,Arial;font-size:13px;background-color:#fff;color:#000;padding:0px 0px 0px 0px;margin:0px 0px 0px 0px;}
    select{padding-left:5px;padding-right:5px;}
    input{text-align:center;}
    </style>
    </head>
    <body>
    <center>
    <br /><br /><br /><br /><br />
    <form name="tickets">
    <select id="sel_1"><option value="">Select Ticket(s)</option></select>
    <select id="sel_2"><option value="">Select Number of Ticket(s)</option></select>
    <input type="button" value="Calculate Price" onclick="calcTic(this.form)" /> 
    <br /><br /><b>Total price(&pound;):</b> <input name="total"type="text" />
    </form>
    <br /><br /><br /><br /><br />
    </center>
    <script type = "text/javascript">
    var tickets=[
    [" "],
    ["Nottingham, 18th July",25],
    ["Nottingham, 18th July",45],
    ["Nottingham, 18th July",60],
    ["Nottingham, 19th July",25],
    ["Nottingham, 19th July",45],
    ["Nottingham, 19th July",60],
    [" "],
    ["Glasgow, 21st July",45],
    ["Glasgow, 21st July",60],
    [" "],
    ["London, 23rd July",45],
    ["London, 23rd July",60],
    ["London, 24th July",45],
    ["London, 24th July",60]
    ],
    sel_1=document.getElementById("sel_1"),
    sel_2=document.getElementById("sel_2");
    
    for(var i=1;i<tickets.length;i++){sel_1.options[i]=new Option(tickets[i][0]+' - '+tickets[i][1],tickets[i][1]);}
    for(var i=1;i<7;i++){sel_2.options[i]=new Option(i,i);}
    
    function calcTic(frm){
    if(frm.sel_1.value==""){alert("Please choose dates.");frm.sel_1.focus();return;}
    if(frm.sel_2.value==""){alert("Please choose number of tickets.");frm.sel_2.focus();return;} 
    else{
    var val_1=new Number(frm.sel_1.value),val_2=new Number(frm.sel_2.value),extra=val_2>3?10:0;
    frm.total.value=val_1*val_2+extra;
    }
    }
    </script>
    </body>
    </html>
    xxx: Guess Buddhist riddle: "What is the sound of one hand clapping?"
    yyy: facepalm

  9. #9
    Join Date
    Mar 2012
    Posts
    21
    Thanks!

    Can I ask if the why the javascript part has to be in the <body>? It's because I have other code for another input form validation and a session timer which refuses to work if I put those in the body section..

    my validation/session timer code is:
    Code:
    //validate the form (name shouldn't be blank)
    
    
    function validate()
    {
    var x=document.forms["form1"]["Name"].value;										//validate the name field
    if (x==null || x=="")
      {
      alert("Please fill in your Name.");												//show message if empty
      return false;
      }
    
    
    var x=document.forms["form1"]["Email"].value;										//validate the email
    var atpos=x.indexOf("@");
    var dotpos=x.lastIndexOf(".");
    if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)								//check for the "@" and "."
      {
      alert("Not a valid e-mail address.");
      return false;
      }
    
    
    var x=document.forms["form1"]["Card"].value;										//validate the card field
    if (x==null || x=="")
      {
      alert("Please fill in your Card number.");										//show message if empty
      return false;
      }
    
    window.location= "thanks.html";
    
    }
    
    
    
    //session expiry
    
    setTimeout( "_SessionExpired()", 10 * 60 * 1000 );			//expires after 10 mins
    
    function _SessionExpired()
    {
    alert("Session has expired!");						//alerts user
    location.href = "1.html";						//redirects to login page
    }

    and the form which I am validating is:
    Code:
    <h2>Please Enter Your Details Below.</h2>
    
    
    <b>Name:</b> <br /><input type="text" name="Name" value="" size="30" maxlength="50" /> <br><br>
    	
    <b>Address:</b><br>
    <input type="text" name="Address1" value="Line 1" size="30" maxlength="50" />
    <br><input type="text" name="Address2" value="Line 2" size="30" maxlength="50" />
    <br><input type="text" name="Address3" value="Town/City" size="30" maxlength="50" />
    <br><input type="text" name="Address4" value="Postcode" size="30" maxlength="50" />
    
    <br><br><b>Telephone:</b> <br /><input type="text" name="Phone" value="" size="30" maxlength="11" /> <br><br>
       
    <b>Email:</b><br><input type="text" name="Email" value="" size="30" maxlength="16" /><br><br>
    
    
    <b>Card Number:</b><br><input type="text" name="Card" value="" size="30" maxlength="16" />
    
    </form>
    
    
    <br><br>
    
    <input type="submit" value="Buy Tickets" onclick="validate();" />

  10. #10
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,633
    the code have to be in the body and below the form because this part operates with document elements which already exist:

    Code:
    ...
    sel_1=document.getElementById("sel_1"),
    sel_2=document.getElementById("sel_2");
    
    for(var i=1;i<tickets.length;i++){sel_1.options[i]=new Option(tickets[i][0]+' - '+tickets[i][1],tickets[i][1]);}
    for(var i=1;i<7;i++){sel_2.options[i]=new Option(i,i);}
    ...
    of course you can put these actions in a separate function which is called on page load - then all the js-code can be placed in the head section of the document. or you can just place the js-code in an external js-file to make the markup be less complicated.
    xxx: Guess Buddhist riddle: "What is the sound of one hand clapping?"
    yyy: facepalm

  11. #11
    Join Date
    Mar 2012
    Posts
    21
    thanks! this help me a lot!

  12. #12
    Join Date
    Mar 2012
    Posts
    21
    A small question guys.

    After I press the "buy tickets" button I want a pop up showing the tickets chosen, number of tickets and the total price so the user is able to confirm before moving onto the next page. Would I use a session cookie for this, or is there another way of going about this business?

    I know how to do the cookie but how would I select the two drop downs and total price field?

    Any ideas?

  13. #13
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,633
    i think it's going to be something like this

    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>Tickets</title>
    <style type='text/css'>
    body{text-align:center;font-family:Georgia,Verdana,Arial;font-size:13px;background-color:#fff;color:#000;padding:0px 0px 0px 0px;margin:0px 0px 0px 0px;}
    select{padding-left:5px;padding-right:5px;}
    input{text-align:center;}
    </style>
    </head>
    <body>
    <center>
    <br /><br /><br /><br /><br />
    <form name="tickets">
    <select id="sel_1"><option value="">Select Ticket(s)</option></select>
    <select id="sel_2"><option value="">Select Number of Ticket(s)</option></select>
    <input type="button" value="Calculate Price" onclick="calcTic(this.form)" /> 
    <br /><br /><b>Total price(&pound;):</b> <input name="total"type="text" />
    <div id="subm"></div>
    </form>
    <br /><br /><br /><br /><br />
    </center>
    <script type = "text/javascript">
    function soGetCookie(cookieName,cookieExists){cookieName=''+escape(cookieName)+'=';if((cookiePos=document.cookie.indexOf(cookieName))!=-1){valuePos=cookiePos+cookieName.length;valueEnd=document.cookie.indexOf(';',valuePos);if(valueEnd==-1)valueEnd=document.cookie.length;return unescape(document.cookie.substring(valuePos,valueEnd));}return(typeof(cookieExists)=='undefined'?'':false);}
    function soSetCookie(cName,cValue,cStck){domain='';path= '/';expire='; expires='+(cStck?new Date(new Date().getTime()+3600000*24*7200).toGMTString():-1);document.cookie=''+escape(cName)+'='+escape(cValue)+'; path='+path+expire+domain+';';}
    var tickets=[
    [" ",""],
    ["Nottingham, 18th July",25],
    ["Nottingham, 18th July",45],
    ["Nottingham, 18th July",60],
    ["Nottingham, 19th July",25],
    ["Nottingham, 19th July",45],
    ["Nottingham, 19th July",60],
    [" ",""],
    ["Glasgow, 21st July",45],
    ["Glasgow, 21st July",60],
    [" ",""],
    ["London, 23rd July",45],
    ["London, 23rd July",60],
    ["London, 24th July",45],
    ["London, 24th July",60]
    ],
    sel_1=document.getElementById("sel_1"),
    sel_2=document.getElementById("sel_2");
    sel_1.onchange=sel_2.onchange=function(){
    document.getElementById("subm").innerHTML='';
    document.tickets.total.value='';
    }
    
    for(var i=1;i<tickets.length;i++){sel_1.options[i]=new Option(tickets[i][0]+' - '+tickets[i][1],tickets[i][1]);}
    for(var i=1;i<7;i++){sel_2.options[i]=new Option(i,i);}
    
    function calcTic(frm){
    if(frm.sel_1.value==""){alert("Please choose dates.");frm.sel_1.focus();return;}
    if(frm.sel_2.value==""){alert("Please choose number of tickets.");frm.sel_2.focus();return;} 
    else{
    if(frm.sel_1.value==''){return;}
    var val_1=new Number(frm.sel_1.value),val_2=new Number(frm.sel_2.value),extra=val_2>3?10:0;
    frm.total.value=val_1*val_2+extra;
    var kukiline=sel_1.options[sel_1.selectedIndex].text.substring(0,sel_1.options[sel_1.selectedIndex].text.indexOf('-')-1)+'&#37;'+sel_1.options[sel_1.selectedIndex].value+'%';
    kukiline+=sel_2.options[sel_2.selectedIndex].value+'%'+frm.total.value;
    /* place,date % price % quantity % total */
    soSetCookie('buy_tickets',kukiline,-1);
    var getkuki=soGetCookie('buy_tickets','').split('%');
    document.getElementById("subm").innerHTML='<br /><br />where and when: '+getkuki[0]+'<br />price: '+getkuki[1]+'<br />quantity: '+getkuki[2]+'<br />total: '+getkuki[3]+'<br /><br /><input type="submit" value="I want to buy these tickets" />';
    }
    }
    
    
    </script>
    </body>
    </html>
    Last edited by Padonak; 06-05-2012 at 05:15 AM.
    xxx: Guess Buddhist riddle: "What is the sound of one hand clapping?"
    yyy: facepalm

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

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



Recent Articles