Is it possible to change input tag name using javascript?

I want to know if it is possible to change the name of the input tag using javascript or jquery, for example in this code:

<input type="radio" name="some_name" value="">

I want to change the value of some_name when the user selects this switch.

the reason why I want to do this is described here: How can I calculate the sum of switch values ​​using jQuery?

+3
source share
6 answers

Just elem .name = "some other name"or elem .setAttribute("name", "some other name"), where elemis the element you want to change.

And to do this when selecting, use the onchange event:

<input type="radio" name="some_name" value="" onchange="if(this.selected) this.name='some other name'">

And apply this behavior to each switch with the same name:

var inputElems = document.getElementsByTagName("input");
for (var i=inputElems.length-1; i>=0; --i) {
    var elem = inputElems[i];
    if ((elem.type || "").toLowerCase() == "radio" && elem.name == "some_name") {
        elem.onchange = function() {
            if (this.selected) {
                this.name = "some other name";
            }
        };
    }
}

jQuery .

+8

jQuery

$('input:radio[name="some_name"]').attr('name', 'new name');

Gumbo JavaScript-

+4

, javascript. , IE 6 7 , javascript ( , ).

$('input:radio[name="some_name"]').attr('name', 'new_name');

: , , :

$("input:radio[name='some_name']").click(function() {
  if ($(this).attr('checked'))    $("input:radio[name='some_name']").attr('name', 'new_name');
  else                            $("input:radio[name='some_name']").attr('name', 'some_name');
});
+2

. jQuery - , :

$("input[name=some_name]").attr("name", "other_name");
+1

:

<input type="radio" name="some_name" value="" id="radios">

<script type="text/javascript" charset="utf-8">
$(document).ready(function()
{
    $("#radios").click(function()
    {
        $(this).attr("name", "other_name");
    });
});
</script>
0

, IE.

The best way to handle this is to replace the old switch with the new one. This post can help you. If you are using jQuery, you can do this with the replaceWith function.

Additional information on changing name attributes in IE .

0
source

Source: https://habr.com/ru/post/1715928/


All Articles