简体   繁体   中英

Access input text from dynamically created input field using jquery

I am trying to build an online exam system. To make question paper i am creating two types of input fields dynamically. One is for question, and another is for options of the question. My jquery codes

<div id="q_paper"></div>
<br/><button type="button" id="go2">Ok</button>

for(var i=0;i<total_question;i++){
                var nw="<div class='q'>("+(i+1)+".)<textarea class='text_area'>Question"+(i+1)+"</textarea><br/>";
                for(var j=0;j<option_number;j++){
                    nw+="<input type='radio'/><input type='text' class='opt' value='option"+(j+1)+"' onfocus='this.value="+null+"'/>"+'<br/>';
                }
                nw+="</div>";
                $("#q_paper").append(nw);
            }

            $(".text_area").click(function(){
                $(this).text("");
            });

But i cann't access the input text from the both input field fields. I have tried a number of times but failed. How to get input text when a ok button is clicked ?

You should have use event delegation .on() function to access dynamically added content.. Here is the example to achieve that, hope this help:

<script>
 $(function(){
    $(document).on('click','#go2', function(){
        $('input.opt').each(function(){
              alert($(this).val());
         });

    }}

  });
  </script>

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