简体   繁体   English

使用jQuery从动态创建的输入字段访问输入文本

[英]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 我的jQuery代码

<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: 您应该使用事件委托.on()函数来访问动态添加的内容。.这是实现该目的的示例,希望对此有所帮助:

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

    }}

  });
  </script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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