0

I'm trying to clone the following HTML template and add class/text to it.

<template id="result">
    <section>
        <div class="alert">
            <p class="someText"></p>
        </div>
    </section>
</template>

So the user first submits a question:

<div id="answer"></div>

<section class="row">
    <form id="form" action="/" method="GET">
        <div>
            <input id="question" />
        </div>
    </form>
</section>

Then the script executes:

$(document).ready(function () {
    $('#form').on('submit', function (event) {
        $.ajax({
            data: {...},
            type: 'GET',
            url: '/result'
        }).done(myFunction);
    });
});

And finally it clones the template (ID #result), add a class to the element containing a class alert and add some text to the element containing a class someText, and appends it to the element containing ID #answer.

function myFunction(result) {
    clone = $('#result').clone();
    $('.alert', clone).addClass('myClass');
    $('.someText', clone).text('myText');
    clone.appendTo("#answer");
}

The function executes (I added a console.log() to the end of it to be sure) but nothing is appending.

fr0zie
  • 73
  • 8
  • 1
    I do not see where you clone the template. Also you would end up with multiple elements with the same ID. – Twisty Aug 26 '21 at 14:11
  • Well I do not use ```.clone()``` but I store my template in ```elt``` then copy it in ```clone```. – fr0zie Aug 26 '21 at 14:13
  • I see now that you are replicating the ` – Twisty Aug 26 '21 at 16:00
  • Are you doing anything from stopping your form from being submitted and reloading your page, wiping out all changes in the process? – j08691 Aug 26 '21 at 16:05

1 Answers1

2

Consider the following.

function create_message(result) {
  var section = $("#result").children().clone();
  $('.alert', section).addClass(result.status);
  $('.address', section).text(result.address);
  $('.extract', section).text(result.extract);
  $('.question', section).text(result.question);
  section.appendTo("#answer");
}

This creates a clone of all the HTML Elements inside the Template with ID result. It then finds specific classes inside the Object section and makes changes.

You can also do the following.

section.find(".alert").addClass(result.status);

See more: https://api.jquery.com/clone/

Update

Use <template> to hold some content that will be hidden...

So if you Clone the Template and append it, it will still be hidden.

Try the following:

function myFunction(result) {
  clone = $('#result > section').clone();
  $('.alert', clone).addClass('myClass');
  $('.someText', clone).text('myText');
  clone.appendTo("#answer");
}

Update 2

I don't use <template>, so I had to re-read some stuff. It has a content portion, so it has an HTML Fragment contained within and is not like other HTML Elements, more like an iFrame. So we need to collect the content versus cloning it.

See: How to use HTML template tag with jQuery?

Here is a working example: https://jsfiddle.net/Twisty/rpd9h0mf/20/

Your code will be something more like the following.

JavaScript

$(function() {
  function showResults(results) {
    var clone = $($('#result').html());
    $('.alert', clone).addClass(results.class);
    $('.someText', clone).text(results.answer);
    clone.appendTo("#answer");
  }

  $('#question-form').submit(function(event) {
    event.preventDefault();
    $.ajax({
      data: {
        q: $("#question").val()
      },
      type: 'GET',
      url: '/result',
      success: showResults
    });
  });
});

This creates a new jQuery Object based on the HTML Content of the Template. Now you can properly edit it and append it.

Twisty
  • 30,304
  • 2
  • 26
  • 45
  • With this code, ```section``` does not even append to ```answer```, I don't understand why... – fr0zie Aug 26 '21 at 14:25
  • Are you sure `#answer` exists at the time the code runs? To confirm, you can use: `console.log($('#answer').length);`. This should output a `length` of 1. – War10ck Aug 26 '21 at 14:27
  • Yes, ```answer``` is in the ```body``` but nothing is happening. – fr0zie Aug 26 '21 at 14:29
  • @fr0zie where is this function, `create_message()` get executed? – Twisty Aug 26 '21 at 14:35
  • ```$(document).ready(function () {$('#form').on('submit', function (event) {$.ajax({data: {...}, type: 'GET', url: '/result'}).done(create_message);});});``` – fr0zie Aug 26 '21 at 14:36
  • @fr0zie please check your Console and Network section and confirm that a Request is not failing. If `
    ` is not appearing, it sounds like the function is not running.So maybe your AJAX is not calling it.
    – Twisty Aug 26 '21 at 14:40
  • The function is running, I'm doing a ```console.log()``` at the end of it and when I submit the form, the console prints ```1```. – fr0zie Aug 26 '21 at 14:44
  • @fr0zie please go back and provide a Minimal, Reproducible Example: https://stackoverflow.com/help/minimal-reproducible-example – Twisty Aug 26 '21 at 14:45
  • @Twisty I modified my question to be as clear as possible. – fr0zie Aug 26 '21 at 15:15
  • Still nothing appending in the ```answer``` div after your update... It's a mystery. – fr0zie Aug 26 '21 at 16:17
  • @fr0zie please check your console and inspect the `answer` element to see if new items are being appended, yet not being shown. Maybe there is CSS that is preventing them from being seen. I also do not see where you prevent the Form from completing it's default action. ensure to include `event.preventDefault()` first. – Twisty Aug 26 '21 at 16:56
  • @fr0zie when you get the Results, are they a single Object or an Array of Objects? Please provide an example of the results in your post. – Twisty Aug 26 '21 at 17:05
  • @fr0zie see Update 2, I found the issue that was tripping us both up. – Twisty Aug 26 '21 at 17:28
  • @Twisty Working perfectly! Thanks for the help. – fr0zie Aug 26 '21 at 20:19