[英]How to get the value only from an input box that contains value out of multiple input boxes
[英]Get value from multiple input boxes that have incremental id's
我正在嘗試使用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);
});
而是這樣做:
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.