Jquery retrieve values of Dynamically created elements

一曲冷凌霜 提交于 2019-12-12 04:25:11

问题


I have a html page with a form.
The form has Div which gets populated dynamically with Input elements like text box,radio,checkbox etc.

Now I want to retrieve the values of these dynamically created elements in the Html page,so that i can submit it to a page.

//HTML PAGE

<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>

//Question DIV generation script example radio buttons

//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:


You are creating the same input multiple times, since you're splitting the option array, you're making this:

<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'>

You are currently fetching by ID with the #, instead you want to fetch by name and get the :checked item, like this:

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


来源:https://stackoverflow.com/questions/2461343/jquery-retrieve-values-of-dynamically-created-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!