Search code examples
javascriptjqueryjquery-data

Populating form text inputs with data-* data using jQuery


I've been trying to wrap my head around this particular issue for two days now. I feel like I'm close, but I can't crack it. I have a div with data-* attributes:

    <div class="pull-right" id="actions" data-ph-title="I am a title" data-ph-type="and a type" data-ph-source="from a source" data-ph-subject="with a subject">

When trying to alert - for instance - the value of "data-ph-title", I can do the following as apparently the dash between "ph" and "title" gets removed.

    var info = $("#actions").data();
    alert(info.phTitle);

That's great and it works (alerts: "I am a title"), but what I really want is to populate certain form fields with all of this data. I have named my form fields identical to the info object's properties, for example:

    <textarea id="placeholder-title" name="phName"></textarea>

I'm trying to come up with a loop that will put all of the info object's property values into the corresponding text inputs (or textareas). This is where I'm getting stuck. I currently have the following code:

    var info = $("#actions").data();

    $.each(info, function(field, val){
        $("[name='" + field + "']").val(val);
    });

Any help would be greatly appreciated!


Solution

  • Your code works, so I don't really know what the problem is, aside from you not having a field named 'phName'.