Alexander Hein
Alexander Hein

Reputation: 990

Get data-attribute with jQuery

I like to take the data-color and output it inside the value of the hidden input field. This should happen if a radio button gets checked.

How could this be done?

<input type="hidden" id="color" name="color" value=""/>
<input type="radio" id="radio1" name="radio" value="" data-color="option1">
<label for="radio1">
option1
</label>
<input type="radio" id="radio1" name="radio" value="" data-color="option2">
<label for="radio1">
option2
</label>

Upvotes: 0

Views: 330

Answers (2)

gaetanoM
gaetanoM

Reputation: 42054

You may use the HTMLElement dataset.

In order to select all input type radio having the data-color attribute:

$(':radio').filter((i, e) => {return $(e).data('color')})

My snippet:

$(function () {
  $(':radio').filter((i, e) => {return $(e).data('color')}).on('change', function(e) {
    $('#color').val(this.dataset.color);
    console.log("$('#color').val('" + this.dataset.color + "')");
  })
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

<input type="hidden" id="color" name="color" value=""/>
<input type="radio" id="radio1" name="radio" value="" data-color="option1">
<label for="radio1">
    option1
</label>
<input type="radio" id="radio1" name="radio" value="" data-color="option2">
<label for="radio1">
    option2
</label>

Upvotes: 1

user94559
user94559

Reputation: 60153

Note: I made the #color input text instead of hidden just so you can see things working. I also gave both radio buttons a common class and gave them unique IDs. (All HTML elements on the page should have unique IDs.)

$(function () {
  $('.color-button').change(function (e) {
    e.preventDefault();
    $('#color').val($('.color-button:checked').data('color'));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="color" name="color" value=""/>


<input type="radio" id="radio1" class="color-button" name="radio" value="" data-color="option1">
<label for="radio1">
option1
</label>

<input type="radio" id="radio2" class="color-button" name="radio" value="" data-color="option2">
<label for="radio2">
option2
</label>

Upvotes: 0

Related Questions