简体   繁体   中英

Update element index on select option selection using jQuery

I have a basic table:

<table>
    <tr>
        <td class="priority-select"><select></select></td>
    </tr>
    <tr>
        <td class="priority-select"><select></select></td>
    </tr>
    <tr>
        <td class="priority-select"><select></select></td>
    </tr>
    <tr>
        <td class="priority-select"><select></select></td>
    </tr>
</table>

For each of these ".priority-select select" elements, I need to append option tags, with values of the indexes, and the current index with the selected attribute. Example:

<table>
    <tr>
        <td class="priority-select">
           <select>
             <option value="1" selected>1</option>
             <option value="2">2</option>
             <option value="3">3</option>
             <option value="4">4</option>
           </select>
        </td>
    </tr>
    ............. to n rows
</table>

I'm using this snippet to do that:

var $selects = $(".select");
  var selCount = $selects.length;
  for(var i=1; i<=selCount; i++){
    $selects.append("<option value='" + i + "'>" + i + "</option>");
  };

I don't know how to begin the next part, which is updating the table rows based on the selection a user makes.

Ie the user selects in the third row's select, the row is removed from the order, set as the first row, and then all the rows are reordered and reindexed so on the next selection the user will be able to change the order and get it right. This would be done after selecting the option and not having to submit anything else.

Any help would be appreciated.

Your question implies that you are already selecting the appropriate number based on index, but I don't see that in your code. You can do that as follows:

function renumber() {
    // select the appropriate number for each
    $("select").val(function (i) {
        return i + 1;
    });
}

Then for the re-ordering:

$selects.change(function () {
    var $this = $(this);
    var val = $this.val();
    var $row = $this.closest("tr");
    var $parent = $row.parent();

    $row.detach();
    var $nextRow = $parent.find("tr:eq(" + (val-1) +")");

    if($nextRow.length > 0){
        $nextRow.before($row); 
    } else {
        $parent.append($row);
    }

    renumber();
});

http://jsfiddle.net/BKHcb/1

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