复选框始终提供最后一个值

时间:2014-05-25 12:28:46

标签: javascript jquery checkbox

我正在尝试从您选择的框中获取名字和姓氏。问题是它只给了我最后一个值,你选择哪个框并不重要。

for (var i = 0; i<obj.length; i++) {
    firstname = obj[i].Firstname;
    lastname = obj[i].Lastname;

    var checkbox = document.createElement('input');

    checkbox.type = "checkbox";
    checkbox.name = "name";
    checkbox.value = "value";
    checkbox.id = "id";

    var divElement = document.createElement("div");  

    divElement.id = "myDiv";  
    divElement.className = "myDivClass";  
    divElement.style.border = "1px solid black";

    var userPar= document.createElement("p"); 

    userPar.innerHTML = firstname + " " +  lastname;
    document.getElementById("users").appendChild(divElement);  
    divElement.appendChild(userPar);
    divElement.appendChild(checkbox);
}

function save() {
    $('input[type=checkbox]').each(function () {
        if (this.checked) {
            var first = firstname;
            var last = lastname;
            console.log(firstname);
            console.log(lastname);
        }
    });
}   

1 个答案:

答案 0 :(得分:1)

试试这个,

for (var i = 0; i<obj.length; i++) {
    firstname = obj[i].Firstname;
    lastname = obj[i].Lastname;

    var checkbox = document.createElement('input');

    checkbox.type = "checkbox";
    checkbox.name = "name";
    checkbox.value = "value";
    checkbox.id = "id" + i;

    var divElement = document.createElement("div");  

    divElement.id = "myDiv" + i;  
    divElement.className = "myDivClass";  
    divElement.style.border = "1px solid black";

    var userPar= document.createElement("p"); 

    userPar.innerHTML = firstname + " " +  lastname;
    document.getElementById("users").appendChild(divElement);  
    divElement.appendChild(userPar);
    divElement.appendChild(checkbox);
}

function save() {
    $('input[type=checkbox]').each(function (index, val) {
        if ($(val).is("checked")) {

            var RawText = $(val).parent().find("p").text();
            var first = RawText.split(" ")[0];
            var last = RawText.split(" ")[1];
            console.log(firstname);
            console.log(lastname);
        }
    });
}