简体   繁体   中英

Updating second select option by php+ajax in a html table where adding new rows by javascript function

图像完全显示了我要做什么。

In this image i'm adding rows with that button by javascript code:

function addRow(dataTable) {
    "use strict";
    var table = document.getElementById("dataTable");
    var rowCount = table.rows.length;
    if(rowCount < 100) {
        var row = table.insertRow(rowCount);
        var colCount = table.rows[0].cells.length;
        for(var i=0; i<colCount; i++) {
            var newcell = row.insertCell(i);
            newcell.innerHTML = table.rows[0].cells[i].innerHTML;
        }   
     } else {
        alert("En fazla 100 satır ekleyebilirsiniz.");
    }
}

And also i'm changing option values of second select by these codes:

function fetch_select(val) {
    $.ajax({
        type: 'post',
        url: 'stoklari_cek.php',
        data: {get_option:val},
        success: function (response) {
            document.getElementById("sth_stok_kod").innerHTML=response; 
        }
    });
}

On first row of table I'm retrieving second options' values by changing first select. What i need to do is to make it workable in other rows too when i add with Add Row button. I mean when i add second row into the table and change the first select option value, FIRST ROW's SECOND SELECT OPTION VALUES are changing. But i need second rows second select options' values to be changed.

Try changing your addRow function to the following. The idea here is to ensure that every row you create will have unique id's for the dropdown lists (selects).

function addRow(dataTable) {
    var table = document.getElementById("dataTable");
    var rowCount = table.rows.length;
    if(rowCount < 100) {
        var row = table.insertRow(rowCount);
        var newrow = table.rows[0].cloneNode(true); // clone the first row
        var selects = newrow.getElementsByTagName('select'); // get all selects in row
        for(var i=0; i<selects.length;i++) {
            selects[i].id = Math.random().toString(36).slice(2); // generate random id's
        }
        table.appendChild(newrow);   
     } else {
        alert("En fazla 100 satır ekleyebilirsiniz.");
    }
}

In your function where you call fetch_select you will have to get the id of the second select you wish to change. You will then have to pass this id as an argument in fetch_select . Therefore, your fetch_select will also have to change to something like this.

function fetch_select(val, select_id) {
    $.ajax({
        type: 'post',
        url: 'stoklari_cek.php',
        data: {get_option:val},
        success: function (response) {
            document.getElementById(select_id).innerHTML=response; 
        }
    });
}

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