简体   繁体   中英

jQuery dynamic table inputs

I'm working on a school project with JS, and I've created a form where I enter the amount of forces in a problem and (through jquery) the HTML is edited so that a number of new input rows are added after the row where I entered my number of forces.

My issue: now that these new inputs are available, I am trying to set them equal to an array so I can use those values later. I've set up a for loop that works the same as my loop for my number of forces, and I am trying to get it to record each force through clicking the buttons in the new rows. The issue is that it is not recording.

Anyone have any ideas on how I can get these values in an array? It would be very much appreciated.

Also, if any of you know of a framework for a dynamic form or table which would make this easier.

function forceRecording(numofforces) {
    for(var i =0; i<numofforces; i++) {
        $('#button1').parent().parent().after("<tr><td>Force DFO " + i +":</td><td><form><input type='text' name='lengthMeasure'/></form></td><td><div class='button' id='lengthButton"+i+"'>Add!</div></td></tr>")
        $('#button2').parent().parent().after("<tr><td>Force " + i +":</td><td><form><input type='text' name='forceMeasure'/></form></td><td><div class='button' id='forceButton"+i+"'>Add!</div></td></tr>")
    }

    for(var i = 0; i < numofforces;i++) {
        $("#forceButton"+i).click(function(){
            force[i]= $('select[name=forceMeasure]').val();
        });
        $('#forceButton'+i).after("<p>"+force[i]+"</p>");  //only temporary to check if the force is actually in the variable
    }
};

You can use more general selectors to select all of the inputs of that you need in one event.

function forceRecording(numofforces){
for(var i =0; i<numofforces; i++){
    $('#somediv').after("<tr><td>Force DFO " + i +":</td><td><input type='text' id='lengthMeasure"+i+"'/></td><td><div class='button' id='lengthButton_"+i+"'>Add!</div></td></tr>")
    $('#someotherdiv').after("<tr><td>Force " + i +":</td><td><input type='text' id='forceMeasure_"+i+"'/></td><td><div class='button' id='forceButton_"+i+"'>Add!</div></td></tr>")
}
};   
$("div.button[id^='forceButton']").live("click",function(){
    var num = parseInt($(this).attr("name").split("_")[1]);
    force[num]=$('text[id=forceMeasure_'+num+']').val();
    console.log(force);
});

Live is a better function to use if you're generating new elements to attach events to. You only need to bind events once using live rather than every time an element is created. You also only need one form element per page. Name and ids should ideally always be unique.

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