SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Jan 2011
    0 Post(s)
    0 Thread(s)

    javascript dropdown list to show by default selected value

    Can someone tell me the code to display dropdown box showing a default value as selected which can vary as per the user’s condition using script..i,e by enclosing in document.write..
    Now i need to print a for loop counter variable's value as the default selected option if a condition satisfies as shown below..

    • <script type="text/javascript">
    • document.write("<SELECT NAME=\"choice\" >")
    • for (var counter=0; counter<10;counter++)
    • {
    • if(counter==6)
    • {<!—what should be the code here to display 6 as by default selected option-->
    • }
    • else
    • { <!-- what should be the code here to display the counter value other than 6 as an option in the dropdown box-->
    • }
    • }
    • document.write("</SELECT>");
    • </scriPT>


  2. #2
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Sydney, NSW, Australia
    25 Post(s)
    1 Thread(s)
    The following should do what you are asking for (unless I have made a typo). Just change the txt array to whatever you want the options to display as for the corresponding values 1 through 10 (or add a second array if you don't want the values to be 1 through 10).

    <span if="sel"></span>
    <script type="text.javascript">
    var txt = ['one','two','three','four','five','six','seven','eight','nine','ten'];
    var newS = document.createElement("select");
    for (var counter=0; counter<10;counter++)
       newS.options[counter-1] = new Option(txt[counter-1],counter);
    newS.options[5].selected = true; // sets the 6th entry to be selected by default
    Stephen J Chapman, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

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