venkat
venkat

Reputation: 131

How to change ID by unique in Jquery

I have input fields with randomly-ordered ids as follows:

<input type="text" id="start1" />
<input type="text" id="start5"/>
<input type="text" id="start3"/>

I need to change it as below, ordering by a 1 to 10 suffix at the end

<input type="text" id="start1" />
<input type="text" id="start2"/>
<input type="text" id="start3"/>
<input type="text" id="start4"/>

How to do it in jQuery?

Upvotes: 1

Views: 156

Answers (2)

Jeyachanthuruj
Jeyachanthuruj

Reputation: 11

<html>
<head>
<script type="text/javascript" src="jquery_1.5.2.js"></script>
<script type="text/javascript">
function reOrder (){
    var putVal = [];
    var put = [];
    var arr = $('.arr input[type=text]');
    for(var i=0; i < arr.length; i++){
        putVal[i] = $('input[id=start'+i+']').val();
        put[i] = "<input type='text' value='"+putVal[i]+"' id='start"+i+"' />"
    }

    $(".arr").empty();  
    for(var i=0; i < arr.length; i++){
        $(".arr").append(put[i]); 
    }



    }
$(document).ready(function() {

    reOrder();

});

</script>
</head>

<body>
<div class="arr">
<input type="text" id="start2" value="2" />
<input type="text" id="start3" value="3"/>
<input type="text" id="start0" value="0"/>
<input type="text" id="start1" value="1"/>
</div>
</body>
</html>

Hi, I did like this but this is working. Is this correct??

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337627

$(function() {
    var i = 1;
    $("INPUT[type=text]").each(function() {
        $(this).attr("id", "start" + i);
        i++;
    });
});

The above will work for you.

It needs to be said though, that changing IDs on the fly is a rather odd requirement to have. Is there a specific reason you need to achieve this?

Upvotes: 3

Related Questions