Jquery retrieve values of Dynamically created elem

2019-08-20 04:40发布

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条回答
劳资没心,怎么记你
2楼-- · 2019-08-20 05:40

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();
查看更多
登录 后发表回答