简体   繁体   中英

javascript/jquery - dynamically add data by id to an array

Attempting to build a resume creator as a project for codeacademy.

I'm using a button to "save" the user's input to an array so it can later be appended into the resume.

However, I'm failing at getting the data to "save" to the array. I've looked at similar questions here on stackoverflow and I cannot for the life of me figure out what I am doing wrong.

here's my fiddle

specific code block I'm having trouble with:

$('#experiencesave').click(function(){
for (var i = 0; i < jobs; i++){
jobtitle.push = $('#jobtitle'+i).val();
}
$('#morejobs').append(jobtitle);
});

Well, .push [MDN] is a function which has to be called:

jobtitle.push($('#jobtitle'+i).val());

As an alternative solution, instead of using a for loop, you might want to use .map to collect the values:

var jobtitle = $('input[id^=jobtitle]').map(function() {
    return this.value;
}).get();

I don't see a reason to give each of those input elements an ID though. Just give them a class. That makes it a bit easier to bulk-process them later. Eg the selector could then just be $('input.jobtitle') .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM