简体   繁体   中英

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>

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

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/

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM