March 29, 2012

Add a Data-test-id attribute to a <td> in my Jquery

Question by Rammtin Avar

I have a Table, Textarea and a Button. When a user types inside the Textarea and then clicks on my Button the text gets added to the Table as a row with following code:

<script type="text/javascript">
 $(function() {
    $('#CustomButton').click(function() {
        $('#CustomPickedTable tbody').append(
            $('<tr/>',
             {
            click: function() {
                    $(this).remove();
                    },
                html: $('<td/>', {
                    text: $('#CustomQuestionText').val()
                })
            })
        );
        return false;
    });
});
</script>

When a user types inside the TextArea and then clicks on the Button is that my Table Tbody gets this <td>What user typed..</td> What I would like is that my table gets <td data-test-id="5">what user typed..</td>.

Is there any solutions for that in my jquery so my <td> gets an data-test-id attribute?

Thanks in advance!

Answer by Starx

You can do it this way

$('#CustomButton').click(function() {
    $('#CustomPickedTable tbody').append(
        $('<tr/>', {
            html: $("<td />", {
                html: $("#CustomQuestionText").val(),
                'data-attr-id': 5

            })
        })
    );
    return false;
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!