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>

3
  • 1
    Your code is working fine: 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') Commented Dec 18, 2017 at 10:34
  • In addition to @RoryMcCrossan's comment, if you want the data to be shown on HTML, you can use attr method. Commented Dec 18, 2017 at 10:35
  • Used .attr() to overcome the issue. Thanks :) Commented Dec 18, 2017 at 12:02

2 Answers 2

0
 var txtBox = $('<input/>', {
                "class" : "myCustomClass",
                "type" :"text",
                "data-index":""
            });
$('#wrapper').append(txtBox);           
txtBox.attr('data-index','ddddddddd');
Sign up to request clarification or add additional context in comments.

1 Comment

@Rory McCrossan is Right. But still if we want to confirm attr is also good option, data is html5 feature.
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

1 Comment

It is better to add the details from the link into your post in case it ever goes dead.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.