Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript How to set values to custom attributes in Jquery

  • This topic is empty.
Viewing 10 posts - 1 through 10 (of 10 total)
  • Author
    Posts
  • #145807
    gowda24
    Participant

    How to set values to html custom attributes using jquery

    I am having an input tag
    <input type=”text” id=”id1″ value=”” data-parentID=””/>

    refering the html input tag above.

    How can i set value to data-parentID in jquery.

    #145812
    georgearnall
    Participant
    #145824
    gowda24
    Participant

    Hi george,

    $('input[type="text"]').attr('data-parentID', 'newvalue');

    This works but here you are adding newvalue as string.

    How if i am adding a jquery returned value.

    var val = $(“.id1”).find(‘td’).val();

    $(‘input[type=”text”]’).attr(‘data-parentID’, val);

    This statement is not working

    #145944
    sadunaresh
    Participant

    strangely the following is working for me..

    var x= $('div').find('td').attr("value");

    http://codepen.io/nareshsadu/pen/LCzqF

    need to see why .val() is not working with td…

    #145948
    Chris
    Participant

    .val() is used for form elements, for elements that can contain HTML you need to use .html()

    #146005
    georgearnall
    Participant
    #146100
    gowda24
    Participant

    Hi george,

    i want to add value to data-parentID. i want to store some value, in this attribute, which later can be used.

    I am storing the parent id in this data-parentID, and later fetching this vlaue when returning.

    In the above ex, when you inspect the input field dataparentId is empty

    #146113
    georgearnall
    Participant

    I hope I have made it clear for you here.

    It is strange that you could not see the data-attribute value.
    It was working for me.

    #146119
    Chris
    Participant

    I noticed that your pens are using the classic approach to targeting data attributes so I’ve forked the pen and update it to use the recommend code when working with data attributes.

    http://codepen.io/ChrisUpjohn/pen/FbpIu

    #146120
    georgearnall
    Participant

    Thanks,

    I’ve tried to use data() before but I could never get it to work.. :/

Viewing 10 posts - 1 through 10 (of 10 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.