2
  1. So let us say i have a form with id #form which has two input fields, namely title & price.
  2. I click on the Edit button somewhere in the application which has data attributes (e.g data-title="Apple" data-price="10")that are to be assigned to the #form upon clicking the button.
  3. the obvious solution that works is $("#name").val($(this).data('name')); $("#price").val($(this).data('price'));
  4. This obviously looks bad when you have too many fields. So I am trying to get something like this to work $('#form').data($(this).data());, more or less in a single like
  5. Have tried this many ways with no success

Any help is appreciated

1
  • You need to be more specific. Your question have to contain at least a complete HTML example. Commented Jul 21, 2015 at 18:52

1 Answer 1

4

You could create a jquery plugin that you can call from the element that contains the data points and have it apply the data based on the key to elements within the form of that same name. Example below

$.fn.applyData = function(form) {
    $form = $(form);
    $.each($(this).data(), function(i, key) {
        $form.find('#' + i).val(key);
    });
};

JSFiddle: http://jsfiddle.net/LCM8S/43/

Sign up to request clarification or add additional context in comments.

1 Comment

this one works but I was trying to get something like $('#form').data($(this).data()); or does jquery does not support that to work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.