代码之家  ›  专栏  ›  技术社区  ›  Amitd

jquery检索动态创建元素的值

  •  0
  • Amitd  · 技术社区  · 15 年前

    我有一个带窗体的HTML页面。
    表单有DIV,它动态地用文本框、单选框、复选框等输入元素填充。

    现在我想 检索这些动态创建的元素的值 在HTML页面中,以便我可以将其提交到页面。

    /html页面

    <script type="text/javascript">
             $(function() {
                populateQuestions();
             });    
    
             $("#submit_btn").click(function() {
                 // validate and process form here
                //HOW TO ??retrieve values???
                 var optionSelected = $("input#OptionSelected_1").val();// doesn't work?
    
                // alert(optionSelected); 
                 postAnswer(qid,values);//submit values 
                 showNextQuestion() ;// populate Div Questions again new values
             });  
    
    
         </script>
    
        <form action="" name="frmQuestion">
        <div id="Questions" style="color: #FF0000">
    
        </div>
    

    //问题DIV生成脚本 示例单选按钮

    //questionText text of question
    //option for question questionOptions
    // **sample call**
     var question = createQuestionElement("1","MCQ", "WHAT IS ABCD??", "Opt1$Opt2$Opt3");
     question.appendTo($('#Questions'));
    
    
    function createQuestionElement(id, type, questionText, questionOptions) {
        var questionDiv = $('<div>').attr('id', 'Question');
        var divTitle = $('<div>').attr('id', 'Question Title').html(questionText);
        divTitle.appendTo(questionDiv);    
        var divOptions = $('<div>').attr('id', 'Question Options');     
        createOptions(id, "radio", questionOptions, divOptions);
        divOptions.appendTo(questionDiv);
        return questionDiv;
    }
    
    function createOptions(id, type, options, div) {
        var optionArray = options.split("$");
        // Loop over each value in the array.
        $.each(
     optionArray, function(intIndex, objValue) {
         if (intIndex == 0) {
             div.append($("<input type='" + type + "' name='OptionSelected_" + id + "' checked='checked'  value='" + objValue + "'>"));
         } else {
             div.append($("<input type='" + type + "' name='OptionSelected_" + id + "' value='" + objValue + "'>"));
         }
         div.append(objValue);
         div.append("<br/>");
     }
    
    1 回复  |  直到 15 年前
        1
  •  1
  •   Nick Craver    15 年前

    您要多次创建相同的输入,因为您要拆分选项数组,所以要进行以下操作:

    <input type='radio' name='OptionSelected_1' checked='checked'  value='Opt1'>
    <input type='radio' name='OptionSelected_1' value='Opt2'>
    <input type='radio' name='OptionSelected_1' value='Opt3'>
    

    您当前正在按ID提取 # ,而您希望通过 name 得到 :checked 项目,如:

    var optionSelected = $("input[name=OptionSelected_1]:checked").val();