简体   繁体   中英

JQuery set custom attribute from value

Suppose this code:

<input id="myinpunt-name"  my_attribute="1"  class="myclass" ...
<checkbox id="myinpunt-name"  my_attribute="2"  class="myclass" ... 



$('.myclass').change(function() {
        dosomething($(this).attr('my_attribute'));
 });

and works correctly.

Now I have also another component

<select id="myselect-name" my_attribute = /* here I want to read Value*/ class="myclass"  ...

In this case my_attribute has to read $(this).val() .

In there a way to set value attribute to a custom attribute ?

thanks.

On either way (inline or separate), you will require to set / change custom_attribute's value based on the change event of drop-down as following:

Inline:

<select id="myselect-name" my_attribute="1"
    onchange="javascript: this.setAttribute('my_attribute', this.value);">
    <option>1</option>
    <option>2</option>
    <option>3</option>
</select>

DEMO - 1

Separate:

<select id="myselect-name" my_attribute="1" class="myclass">
    <option>1</option>
    <option>2</option>
    <option>3</option>
</select>

$('.myclass').change(function() {
    $(this).attr('my_attribute', $(this).val());
    alert($(this).attr('my_attribute'));
});

DEMO - 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM