Ruxie
Ruxie

Reputation: 69

Javascript change id from form input

I am working on a new project and I ran into one issue

I want to have a form where the user can enter their username so a 3d image is generated. The code for the image generator is:

<span class="mc-skin" data-minecraft-username="UsernameHere"></span>

and what I need is a input field that changed the data-minecraft-username to the input of the form.

Thanks for any help!

Upvotes: 0

Views: 249

Answers (3)

RobG
RobG

Reputation: 147513

Probably the most robust way to deal with data-* attributes is to use setAttribute and getAttribute. If the span has an id of Skin, then you might use:

var span = document.getElementById('Skin');
span.setAttribute('data-minecraft-username', newValue);

You can also use the element.dataset property:

span.dataset['minecraft-username'] = newValue;

Which will add a data-minecraft-unsername attribute with a value of whatever is in newValue. However, support may be lacking in older browsers (see MDN HTMLElement.dataset, which indicates fairly recent browsers such as IE 11, Safari 6, etc. are required).

Also see MDN Using data attributes.

To use the above script in a document, you might do something like:

<script>
function setDataAttribute(elID, attName, value) {
  var el = document.getElementById(elID);
  if (el) {
    el.setAttribute('data-' + attName, value);
  }
}

function setContent(elID, value) {
  var el = document.getElementById(elID);
  if (el) {
    el.innerHTML = value;
  }
}

</script>


<span id="Skin"></span>
<br>
<input type="text" onblur="
  setDataAttribute('Skin', 'minecraft-username', this.value);
  setContent('Skin', this.value);
">

Upvotes: 0

Suchit kumar
Suchit kumar

Reputation: 11869

you can try this:

var user="Zane";

document.getElementsByClassName("mc-skin")[0].setAttribute('data-minecraft-username',user);

But it will be better if you will use id for that particular span and set it like this: add id="spanId" then use

document.getElementById('spanId').setAttribute('data-minecraft-username', user);

Upvotes: 1

Jacob
Jacob

Reputation: 4031

You can use HTML 5

Example:

variable.setAttribute('data-minecraft-username','randomUserName');

variable beeing your span element

More reference here: http://html5doctor.com/html5-custom-data-attributes/

Upvotes: 0

Related Questions