简体   繁体   中英

Javascript: how to put some value on the textfield data-id attribute

I have a textbox where I kept a empty textbox so on load of it I want to put some data on the attribute data-id

Ex.

I have <input id='shiftSel' data-id="" style="font-size: 11px; color:#3399FF; type="text" size="5">

So on load of page I want to put some some value to data-id="" this, how to do this?

I only know how to put value on the textbox value field Like

    $(document).ready(function() { $("#shiftSel").val(dateArr[0]); } );

Use .data() ---> http://api.jquery.com/data/

$("#shiftSel").data('id',dateArr[0]);

Note : .data() is not going to update actual data-id attribute, it just update data associated with your element which is maintained by browser. ( you will not be able to inspect the change in your browser console's element view )

Or an alternative way you can use .attr() also

$("#shiftSel").attr("data-id","5");
console.log($("#shiftSel").attr("data-id"));

EXAMPLE

使用数据

$('#shiftSel').data('id','idvaluehere')

使用.data()

$("#shiftSel").data('id','something here')

Use data


From this quote: i want to put some some value to data-id=""


$("#shiftSel").data('id',' ');

It's

 $("#shiftSel").attr("data-id",dateArr[0]);

or .data() (if you use newer jQuery >= 1.4.3)

$(this).data("id",dateArr[0]);

Please use attr .

May be data does not work with some jquery lib and browser not support HTML5

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