0

Created a new input element and tried adding the data attribute using the data method in jquery but am not able to append the value

Js Fiddle to the above issue

var txtBox = $('<input/>', {
  "class": "myCustomClass",
  "type": "text"
});
$('#wrapper').append(txtBox);
txtBox.data('index', '1');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='wrapper'>Input Text Box : </div>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • 1
    Your code is working fine: https://jsfiddle.net/bb69fgbj/3/. The source of your confusion is most likely because `data()` does not update the DOM, so the `data-index` attribute will not appear in the inspector. So long as you use the getter of `data()` to retrieve the value, you will have no issues: `var index = txtBox.data('index')` – Rory McCrossan Dec 18 '17 at 10:34
  • In addition to @RoryMcCrossan's comment, if you want the data to be shown on HTML, you can use [`attr`](http://api.jquery.com/attr/) method. – 31piy Dec 18 '17 at 10:35
  • Used .attr() to overcome the issue. Thanks :) – Vijayakumar Natarajan Dec 18 '17 at 12:02

2 Answers2

0
 var txtBox = $('<input/>', {
                "class" : "myCustomClass",
                "type" :"text",
                "data-index":""
            });
$('#wrapper').append(txtBox);           
txtBox.attr('data-index','ddddddddd');
Anup Yadav
  • 2,825
  • 3
  • 21
  • 30
0

The Code is working fineI think the code you are looking for is txtBox.attr('data-index', '1');

for more info why the .data didn't work as you expected , check this answer here