views:

473

answers:

2

I want to change text in table td from 1,1,1 to 1,2,3 with jQuery
But it not seem to work. what is wrong in my code?

This is my JavaScript function.

    function reorder(targetId){
        var i = 1;
        jQuery.find(targetId).each(function(){
            jQuery(this).attr("innerHTML", i);
            i ++;
        });
    }

My html code.

<form>
    <input type="button" onClick="reorder('#index');" value="test"/>
    <table>
        <tr><td id="index">1</td></tr>
        <tr><td id="index">1</td></tr>
        <tr><td id="index">1</td></tr>
    </table>
</form>
+2  A: 

You've got a bit of mixed up stuff there.. let me rewrite it for you

  function reorder(selector){

        jQuery.(selector).find('tr').each(function(i){
            jQuery(this).find('td:first').html(i + 1); // remove the +1 if you want it to start at 0

        });
    }

Here are some of the changes

  • Changed your argument variable to be clearer
  • You can use jQuery.('selector'), not jQuery.find()
  • You can use the html() method

It's worth mentioning too that if you're not using another jQuery library (or don't intend to), you can use $ which is shorter than jQuery.

I've also modified your HTML

<form>
    <input type="button" onclick="reorder('#my-table');" value="test"/>
    <table id="my-table">
        <tr><td>1</td></tr>
        <tr><td>1</td></tr>
        <tr><td>1</td></tr>
    </table>
</form>

You may have forgot that using multiple id attributes with the same value is not valid markup. You could use a class there, or better still omit it entirely. You may not care about valid markup, but browsers' CSS and JavaScript could do some funky stuff (now or in the future) when they expect an id attribute to unique.

alex
+1  A: 

I think you need change i values incrementation expression .

function reorder(targetId){
        var i = 1;
        jQuery.find(targetId).each(function(){
            jQuery(this).attr("innerHTML", i);
            i++; // Before that it was i ++ 
        });
    }
pavun_cool