Udit Gupta
Udit Gupta

Reputation: 3272

Unable to dynamically add dropdown menu through Jquery

It may sound trivial but I am unable to do it.

Here is the simple code : what's wrong I am doing here ?

Is it like I have misunderstood the function? If yes, please correct me.

 <html>
  <head>
   <script type="text/javascript" src="jquery.js"></script>                             
    <script type="text/javascript">
      $(document).ready(function(){
       $(".button").click(function(){
        jQuery('#id').append('<select></select>');
       });     
      });
   </script>
  </head>

  <body >
    <input type="submit" class="button" id="id" value="submit"/>
  </body>

Upvotes: 0

Views: 1293

Answers (4)

Rahul
Rahul

Reputation: 988

considering your own code you can simply write

$('#id').after('<select></select>');

generally append works with a container since #id is associated with a button so it will not work. use div/span if you still want to use append, but if you don't want to .after() works fine.

Upvotes: 1

Ankush Jain
Ankush Jain

Reputation: 1527

fisrt thing don't use submit button because it will postback your page so jquery will not work. try this code

<html>
  <head>
   <script type="text/javascript" src="jquery.js"></script>                             
    <script type="text/javascript">
      $(document).ready(function(){
       $(".button").click(function(){
        $('#ddl').append('<select><option>abc</option><option>def</option></select>');
       });     
      });
   </script>
  </head>

  <body >
    <input type="button" class="button" id="id" value="submit"/>
    <div id="ddl">
    </div>
  </body>

Upvotes: 0

Atif
Atif

Reputation: 10880

Does #id exists in the document?

Do you want to add <option> to <select> ?

$(document).ready(function() {
    $(".button").click(function() {
        jQuery('body').append('<select><option value="1">One</option><option value="2">Two</option></select>');
    });
});​

Fiddle - http://jsfiddle.net/XVmuZ/

If you want to add it to #id then make sure it exists (like in rahul's answer)

Fiddle - http://jsfiddle.net/XVmuZ/1/

Upvotes: 1

rahul
rahul

Reputation: 7663

you have no container/element in your body that will hold the newly added select, add a container in your html like this with id="id"

<body >
     <div id="id">
     </div>
    <input type="submit" class="button" value="submit"/>
</body>

DEMO

Upvotes: 1

Related Questions