Search code examples
jqueryformsinputedit-in-place

Edit in-place multiple input fields


I'm building a page where users can place multiple containers with input fields that can be edited in place. My script at the moment allows me to edit in place the input fields on click but I'm running into 2 issues:

  1. I need to edit each form individually. At the moment when click on Edit all of the fields in the other containers become editable as well.

  2. When click cancel nothing should be saved if anything was typed.

See DEMO

JQuery

var readonly = true;
$(".edit").on("click", function(e) {
  $('input[type="text"]').attr("readonly", !readonly);
  readonly = !readonly;
  $(".edit").hide();
  $(".button-group").show();
});
$(".save, .cancel").on("click", function() {
  $(".button-group").hide();
  $(".edit").show();
  $('input[type="text"]').attr("readonly", !readonly);
  readonly = !readonly;
});

Thank you!


Solution

  • You need to target the parent of the parent element from this then you can scope your elements correctly. Move .cancel to its own listener, and then share the code to close the inputs for both .cancel and .save listeners.

    You also don't need to keep the readonly attribute. You can simply remove it. See below for full example.

    var closeInputs = function(selector, type) {
      var parent = $(selector).parent().parent();
      parent.find(".button-group").hide();
      parent.find(".edit").show();
      // loops through each input
      parent.find('input[type="text"]').each(function() {
        // gets the value from the input if 'save', else get the value of the data-value attribute;
        // default to empty string if either is undefined
        var value = (type === 'save' ? $(this).val() : $(this).attr('data-value')) || '';
        // update this input to readonly, set the data-value attribute with a value, then set the input value
        $(this).attr("readonly", true).attr('data-value', value).val(value);
      });
    };
    $(".edit").on("click", function(e) {
      var parent = $(this).parent().parent();
      parent.find('input[type="text"]').removeAttr("readonly");
      parent.find(".edit").hide();
      parent.find(".button-group").show();
    });
    $(".save").on("click", function() {
      closeInputs(this, 'save');
      alert('Going to save.');
    });
    $(".cancel").on("click", function() {
      closeInputs(this, 'cancel');
      alert('Not going to save.');
    });
    

    JS Fiddle: https://codepen.io/anon/pen/zLWLXM