简体   繁体   中英

Handling the column of an HTML table using jQuery

I have the following table:

<table>
    <tr class="rowUpdate">
    <td>Corredor</td>
    <td>Id Corrdor
        <input type="text" value="dfdfgdf23231fg" class="validate" name="idcorreo" />
    </td>
    <td>Nombre
        <input type="text" value="rertretert" class="validate" name="nombre" />
    </td>
    <td>Email
        <input type="text" value="vikrambanand@gmail.com" class="validate" name="email" />
    </td>
    <td>Empressa
        <input type="text" value="dfdfdf" class="validate" name="Empressa" />
    </td>
    <td>Pagina Web
        <input type="text" value="dfdfdf" class="validate" name="paginaWeb" />
    </td>
    <td>Telefono
        <input type="text" value="34454355" class="validate" name="telephon" />
    </td>
    <td>Cellular
        <input type="text" value="2323" class="validate" name="cellular" />
    </td>
    <td>
        <input type="button" id="updateBtn" value="Update" name="Update" style="float:left" />
    </td>
</tr>
</table>

To handle this, I have the following jQuery code:

 $(document).on('click', '#updateBtn', function () {
    var locations = [],
        rows = [],
        content = {};
    $('.rowUpdate').each(function (i) {
        var feed = [];

        $(this).find('td').each(function (j, v) {
            var label = $(this).html();
            if (j == 0) feed = feed + label;
            if (j != 0) {

                var input = $("input", this),
                    name = input.attr("name").substring(0, input.attr("name").length),
                    value = input.val();
                //alert(value);
                content[name] = value;
                //alert(JSON.stringify(content));
            }
            if (j == 7) {
                feed = feed + '=' + JSON.stringify(content);
            }
        });
        alert(feed);
        rows.push(feed);
    });

});

Can there be a better script to handle this? What I am trying to do is to save the content of the row in a form of string in the array row .

JsFiddle

You can use

//create an array 
var rows = $('.rowUpdate').map(function (i) {
    var content = {};
    //iterate over each input element in the current row
    $(this).find('input:not(:button)').each(function () {
        //assign the value of the current input to `content`
        content[this.name] = this.value;
    })
    //create a string representation 
    return $(this).children('td:first-child').text() + '=' + JSON.stringify(content);
}).get();

console.log(rows)

Demo: Fiddle

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