devssh
devssh

Reputation: 1186

Script to add attribute value(say name) to some attribute(like id) in multiple form elements with jquery

Eg:-

<input name="done"/>

after script jquery

<input name="done" id="done"/>

Cannot do this manually on every element. Many elements don't have name attribute. Leave them unaffected. I need it to submit forms & validate input via server side ajax(username)

 <script>
     $(document).ready(function(){
        $("*").filter("[name]").attr('id','$("[name]")');
     })
</script>

I added the name attribute to these inputs and then I realized they require an id attribute with the same value. I spent a while copy pasting until I realized it should be possible with jquery

Upvotes: 0

Views: 346

Answers (1)

markmoxx
markmoxx

Reputation: 1532

You want to be using jQuery's each() method, as follows:

$('[name]').each(function() {
    $(this).attr('id',$(this).attr('name'));
});

Note: this will add / overwrite ids in ALL elements containing a name attribute, including meta elements. If you don't want this, you can use the not() method, for example:

$('[name]').not('meta').each(function() {
    $(this).attr('id',$(this).attr('name'));
});

Upvotes: 1

Related Questions