Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use JavaScript to set the 'name' attribute?

According to SitePoint (and my own experiments), the IE implementation of "setAttribute()" is buggy and unreliable.

Also according to SitePoint, the name attribute is read-only.

Is there another way I can set the name attributes on elements? I need this for use with radio buttons. If possible, I'd like a solution without jQuery, as I'm currently not using the library.

Thanks in advance!

like image 901
John B Avatar asked Sep 01 '09 13:09

John B


People also ask

How do you input a name in JavaScript?

In JavaScript, we can get user input like this: var name = window. prompt("Enter your name: "); alert("Your name is " + name); The code above simply prompts the user for information, and the prints out what they entered in.

What is name attribute in JavaScript?

The name attribute is used to reference elements in a JavaScript, or to reference form data after a form is submitted. Note: Only form elements with a name attribute will have their values passed when submitting a form.

Can JavaScript change HTML attributes?

Javascript can be used to change the attribute(s) of a HTML element, such as a paragraph, a header, an image, or a list, or any various HTML elements. For example, by changing the src attribute of an img tag, we can change the image entirely to something else with Javascript.

What is set attribute in JavaScript?

setAttribute() Sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value.


1 Answers

Sitepoint liesis talking about a different usage of ‘name’ (see Anthony's comment). It's not read-only, it's just there's a long-standing IE bug (up to v7) where setting ‘name’ on form fields is only partially effective. Radio buttons in particular don't accept it properly.

The Microsoft-endorsed solution, as detailed here is to use a horrific misfeature of IE's version of the createElement call to set attributes at the same time:

var radio= document.createElement('<input type="radio" name="test" value="a" />');

Probably a better way would simply be to use good old innerHTML, eg.:

var div= document.createElement('div');
div.innerHTML= '<input type="radio" name="test" value="a" />';
var radio= div.firstChild;
like image 54
bobince Avatar answered Sep 28 '22 03:09

bobince