Home > Software engineering >  How to put to the jquery object the value from the input on the change event?
How to put to the jquery object the value from the input on the change event?

Time:11-05

In $singleDesignWrapper, there is an input. I need to retrieve the input value on change and put it in the content of <p ></p>

Something similar to what's done in the line:
$('.sidebar-design-number', $element).text('Design ' (i 1));

In general, the goal is as follows:
there are nested design forms, and I need to dynamically populate values in the sidebar from the input located in .field-name-field-design-name. The input is not a direct child of the .field-name-field-design-name

Code:

    const $singleDesignWrapper = $(
      ".field--name-field-design .field--name-field-design-name"
    );

    $singleDesignWrapper.each(function(i) {

      console.log($(this));

      // Object where I need to put the value  
      const $element =
        $('<div >\n'  
        '  <div >\n'  
        '    <div >\n'  
        '      <p ></p>\n'  
        '      <p ></p>\n'  
        '    </div>\n'  
        '    <p ></p>\n'  
        '  </div>\n'  
        '</div>');

      $('.sidebar-design-number', $element).text('Design '   (i 1));
      $sidebarDesignsWrapper.append($element);

    });

console.log($(this)); shows four objects.
console.log($(this).length); is === 1

Markup look like this:

<div >
  // some html here
  <div ></div>
  <div >
    <div >
      <div >
        <p ></p>
        <p ></p>
      </div>
      <p ></p>
    </div>
</div>

<div >
  <div >
    <div >
      <div >
        <input type="text" value="hello">
      </div>
    </div>
  </div>
  <div ></div>
</div>

CodePudding user response:

I'm not 100% sure that I understand exactly what you are trying to do but maybe this will help

const $singleDesignWrapper = $(
    ".field--name-field-design .field--name-field-design-name"
);
$singleDesignWrapper.each(function(i) {
    console.log($(this));
    // Object where I need to put the value  
    const $element =
        $('<div >\n'  
            '  <div >\n'  
            '    <div >\n'  
            '      <p ></p>\n'  
            '      <p ></p>\n'  
            '    </div>\n'  
            '    <p ></p>\n'  
            '  </div>\n'  
            '</div>');

    // $('.sidebar-design-number', $element).text('Design '   (i 1));
    // $sidebarDesignsWrapper.append($element);
    $(this).append($element);
    const $input = $("input", this);
    const $element_to_update = $(".sidebar-design-name", $element);
    $input
        // ADD EVT LISTENERS
        .on("change input", function(evt) {
            // UPDATE ELEMENT TEXT VALUE
            $element_to_update.text($(this).val());
        })
        // SET INITIAL VALUE OF INPUT
        .val("Design "   (i   1))
        // MANUALLY TRIGGER CHANGE EVENT
        .trigger("change");
});

Here's a link to the jsfiddle.

  • Related