1
\$\begingroup\$

I have the following table:

<table>    <tr>    <td>Corredor</td>    <td>Id Corrdor        <input type="text" value="dfdfgdf23231fg" name="idcorreo" />    </td>    <td>Nombre        <input type="text" value="rertretert" name="nombre" />    </td>    <td>Email        <input type="text" value="[email protected]" name="email" />    </td>    <td>Empressa        <input type="text" value="dfdfdf" name="Empressa" />    </td>    <td>Pagina Web        <input type="text" value="dfdfdf" name="paginaWeb" />    </td>    <td>Telefono        <input type="text" value="34454355" name="telephon" />    </td>    <td>Cellular        <input type="text" value="2323" name="cellular" />    </td>    <td>        <input type="button" value="Update" name="Update" />    </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 arrayrow.

psaxton's user avatar
psaxton
9025 silver badges9 bronze badges
askedFeb 25, 2015 at 4:55
Vikram Anand Bhushan's user avatar
\$\endgroup\$
1
  • \$\begingroup\$Is there just one row in your table? Is there only one element of classrowUpdate? Is there a reason to not put the input controls in aform element?\$\endgroup\$CommentedFeb 27, 2015 at 6:09

1 Answer1

1
\$\begingroup\$
$(document).on('click', '#updateBtn', function () {    // See "Event Handler"    var locations = [],                                // See "Unused Variable"        rows = [],                                     // See "Improper Scope"        content = {};    $('.rowUpdate').each(function (i) {                // See "Exactly One" and "Parameters"        var feed = [];        $(this).find('td').each(function (j, v) {      // See "Parameters"            var label = $(this).html();            if (j == 0) feed = feed + label;           // See "Type Variance"            if (j != 0) {                var input = $("input", this),                                                       // See "Wait, what?"                    name = input.attr("name").substring(0, input.attr("name").length),                    value = input.val();                //alert(value);                        // See "Commented Code" and "Alert"                content[name] = value;                //alert(JSON.stringify(content));            }            if (j == 7) {                                                       // See also "JSON"                feed = feed + '=' + JSON.stringify(content);            }        });        alert(feed);        rows.push(feed);                               // See "Improper Scope"    });});

Event Handler -You've attached the event listener to the document which is fine, but you've used an Id selector to filter it to. There can be only one element with in the document referenced by that Id.1Unless the #updateBtn element is expected to be destroyed and recreated during the documents lifetime, it would be better to specify that element explicitly.

Unused Variable -Thelocations variable is never referenced after it is instantiated, remove it.

Improper Scope -Therows variable is pushed to, but never read from. If it is to be useful to other code it will need to be moved out of the event handler's scope.

Thecontent variable is never used at this level of the scope, move its declaration to the narrowest scope required.

Exactly One -According to the HTML snippet you've provided, the.rowUpdate contains the#updateBtn which forces me to assume means there will be only 1.rowUpdate. Update the markup to indicate this element is special by setting theid instead of theclass attribute.

Because we expect this.each function to be invoked once it can be flattened into the parent scope.

Parameters -JavaScript does not allow functions to be overloaded by parameters.2 thei andv parameters are never used and can be removed. Parameters are essentially variable declarations and should be named accordingly.j would be better namedindex.

Type Variance -feed is originally instantiated as an empty array, but you're now adding a string to it. I'm not sure what your intent is, but the effect will be to cast the empty array to an empty string and appendlabel. This is only being done for the 0th element so a simple assignment will do.

Wait, what? - First, nearly every string literal in your code is enclosed in single quotes ('). Suddenly you've begun using double quotes ("). Javascript will allow either, but keep your code consistent.

I'm not sure what the purpose of the.substring method call when your arguments are the full length of the string. this can be removed.

Commented Code -Remove code that is unused. Only comment out code for the purposes of debugging or experimenting and remove the comment (and code if necessary) when done.

Alert -alert should not be used for debugging purposes. Use the console methodstrace,debug,log,warn, etc..

JSON -JSON is a format used for serializing data. It should be used to save, restore, and transfer data. Your code should never manipulate JSON directly. Instead use the objects serialized from the JSON string.


After modifying the code based on the review, I end up with something like this:

var rows = [];$('#updateBtn').on('click', function {    var feed = {},        content = {},        label = $('.rowUpdate td').first().html();    $('tr.rowUpdate td input[type=text]', this).each(function(index, input) {        var $input = $(input),            name = $input.attr('name'),            value = $input.val();        console.debug('value', value);        content[name] = value;        console.debug('content', content);    });    feed[label] = content;    console.debug('feed', feed);    rows.push(feed);});

Then use the actual objects from the rows array if being consumed in other javascript code or send the rows JSON to wherever it is consumed. If for some reason your consumer cannot be modified to use a proper object and relies on the broken JSON string originally in the method, changefeed[label] = content tofeed = label + '=' + JSON.stringify(content).

answeredFeb 27, 2015 at 6:19
psaxton's user avatar
\$\endgroup\$
2
  • \$\begingroup\$what about in this scenariojsfiddle.net/grp3pxu2/1\$\endgroup\$CommentedMar 2, 2015 at 6:33
  • \$\begingroup\$That presents a different scenario... How should the multiple rows be handled? Post a follow up and I'll be happy to go in depth.\$\endgroup\$CommentedMar 4, 2015 at 21:09

You mustlog in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.