从具有增量ID的多个输入框中获取值

时间:2017-01-08 07:42:54

标签: javascript jquery

我试图用jquery从select元素中获取值,但是console.log显示值为NaN。我认为这可能与我选择ID的方式有关,但我不确定。

//Here I am creating the select element with the options in a loop and giving them an incremental ID.
var div = $('<div class="containter">');
    $('.rForm').append(div);
    for(var x = 0; x < 10; x++)
    {

        var h3 = $('<h3 style="margin-bottom: 5px;">' + "Question" + " " + (x + 1) + '</h3>');

        var label = $('<label>').attr('id', 'q'+ (x + 1)).text(questions[x]);
        var br = $('<br>');
        div.append(label);
        div.append(br);
        var select = $('<select>').attr('id', 'q'+ (x + 1));

        for(var i = 0; i < 10; i++)
        {
            if(i === 0){
                select.append($('<option>').text(options[i]));
            }
            else{
                select.append($('<option>').attr('value', options[i].val).text(options[i].text));
            }

            console.log('hi')
        }
        $('.containter').append(select);

    }


$('#submit').on('click', function(){

            // var answers = [];


            var newProfile = {
                name: $('#name').val().trim(),
                photo: $('#link').val().trim(),
                scores: []
            }

            for(var x = 0; x < 10; x++){
                var num = $('#q' + (x+1)).val(); //Showing the value as NaN
                console.log("num", num)
                newProfile.scores.push(parseInt(num));
            }

            console.log('new', newProfile);
            console.log('scores' + newProfile.scores);

        });

1 个答案:

答案 0 :(得分:0)

而是这样做:

var questions = [{
  title: "Do you like jQuery ?",
  expected: [0],
  answers: [
    "yes",
    "no"
  ]
}, {
  title: "jQuery is :",
  expected: [1],
  answers: [
    "a language",
    "a library",
    "a framework"
  ]
}, {
  title: "What is the type of jQuery.map() ?",
  expected: [2],
  answers: [
    "[a] -> b",
    "[a] -> [b]",
    "[a] -> (a -> Int -> b) -> [b]"
  ]
}];

$("form").html($.map(questions, function (q, i) {
  return ""
  + "<div>"
  +   "<h3>" + q.title + "</h3>" 
  +   "<select "
  +     "multiple "
  +     "name=\"q" + i + "\""
  +     "size=\"" + q.answers.length + "\""
  +   ">" 
  +     $.map(q.answers, function (a, j) {
          return "<option value=\"" + j + "\">" + a + "</option>";
        }).join("") 
  +   "</select>"
  + "</div>";
}).join("") + (
  "<button type=\"button\">Submit</button>"
));

$("button").click(function () {
  var score = 0;
  var $sel = $("select");
  $sel.each(function (i) {
    var answers = $(this).val() || [];
    var expected = questions[i].expected;
    if (answers.join() == expected.join()) score++;
  });
  alert(score + "/" + questions.length);
});
body, h3, select, input {font: normal 12px Arial;}
select {overflow: hidden;}
div {margin-bottom: 1em;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form></form>