简体   繁体   中英

Javascript to edit table rows

I need help with a feature for my site. I just cant make the script work. I have this site: http://imgur.com/oMy69yx As you can see, there is one " Edit " button for each row. The goal here is that when the user press one of those, the row gets editable (except for the subject name) and the button changes to " Save ". Then the user can edit all he wants and save it. When he clicks " Save " I get all fields that were changed and update via SQL query. PS:The number of rows is undefined because the user can input as many rows as he wants.

So I thought in some script like this:

var button = document.getElementByClassName("clicker");
var buttonclicked = function(){
    button.textContent = "Save"; //And things get editable};
button.addEventListener("click", buttonclicked);

But this wont work because var button is an array of buttons, and the addEventListener wont work with that... What can I do to solve this?

This is the HTML generating the table: (Might be a little bit messy)

<?php $i = 0;?>
<?php foreach ($rows as $row): ?>
    <tr class="d1">
        <td><?php echo $row["subject"] ?></td>
        <td>
            <?php 
                if($row["G1"] != -1)
                    echo $row["G1"];      
            ?>
        </td>
        <td>
            <?php 
                if($row["G2"] != -1)
                    echo $row["G2"];      
            ?>
        </td>
        <td>
            <?php 
                if($row["G3"] != -1)
                    echo $row["G3"];      
            ?>
        </td>
        <td>
            <?php 
                if($row["G4"] != -1)
                    echo $row["G4"];      
            ?>
        </td>
        <td>
            <?php 
                $round = round($row["normal"],2);
                echo $round;
            ?>
        </td>
        <td><?= $row["creditos"] ?></td>
        <td><?php echo $row["criteria"];?></td>
        <td><?php echo "<button id = clicker.$i>Edit</button>"; ?></td>
    </tr>
    <?php $i++; ?>
<?php endforeach ?>

You can assign to each button via for loop:

var buttons = document.getElementsByClassName("clicker");

var buttonclicked = function(e){
    e.target.textContent = "Save"; //And things get editable};

for(var i = 0; i < buttons.length; i++)
{
    buttons[i].addEventListener('click', buttonclicked);
}

Also notice that I'm working on e.target in the buttonclicked function, rather than button , so that we get the right button each time.

The e is the event object that holds information about the onclick event. If you look at the buttonclicked variable you see it's assigned function(e) now instead of just function() .

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