Jump to content

Recommended Posts

I have this code (very cool)...

document.addEventListener('DOMContentLoaded', function() {
    const emojiSelect = document.getElementById('emojiSelect2');
    const inputText = document.getElementById('comment_text2');

    const emojis = [
        '(・ω・)', '(´・ω・`)', '(。♥‿♥。)', 'ヾ(⌐■_■)ノ♪', '(╯°□°)╯︵ ┻━┻'
    ];

    // Populate the select dropdown with emojis
    emojis.forEach(emoji => {
        const option = document.createElement('option');
        option.value = emoji;
        option.text = emoji;
        emojiSelect.appendChild(option);
    });

    // Event listener for emoji selection
    emojiSelect.addEventListener('change', function() {
        const selectedEmoji = this.value;
        if (selectedEmoji) {
            inputText.value += selectedEmoji;
            this.selectedIndex = 0; // Reset dropdown to default option after selection
        }
    });
});

</script>

Though I need to call it multiple times with no fixed number...

    <select id="emojiSelect2">
        <option value="">Select an kaomoji</option>
    </select>
 	<textarea name="comment_text" id="comment_text2" rows="2" cols="40" placeholder="Type comment reply here." required></textarea>

... here. This will loop a few times... say 30.. though my current code only allows the first iteration. I'm not very good at Javascript.,.. could someone show me how to write it to allow multiples inside the loop? Maybe gen an index(++) and drop that in. If so, how?

Thanks guys and gals!

Edited by oz11
Link to comment
https://forums.phpfreaks.com/topic/319920-multiple-function-calls-from-loop-help/
Share on other sites

  • oz11 changed the title to Multiple function calls, from loop. Help.

It would help if you explained what you are trying to achieve. Code that doesn't work only shows us what you don't want to do.

What do want to do (30?) times in a loop. For example...

  • Are you meaning there may be 30 emojis, or
  • there will be 30 select/input text pairs?

And how is the user expected to interact with it?

Can you

  • display a form with a select and an input text
  • user enters comment
  • user clicks "Save"
  • form is posted and comment saved
  • page reloads

Rinse and repeat as many times as required?

  1. user visits comment section
  2. user wants to input emoji via input/select
    - works on the first comment box, but there are multipul..
    - doesnt work on comment box 2, 3,4 etc..

    * seems to need a id of some sort inserted into the Javascript so that it can be used multi. Not sure how.

I like to use data attribute on these occasions.

NOTE: use a class name for the selects and another for the inputs. Don't use ids.

Maintain a count of how many comments the user adds and increment each time they add a new one.

When creating a new select and input, give them both a data-id attribute with the value of the count.

When emoji selected, get the value of the select's data-id. Look for the input with the same data_id and insert the emoji.

  • Thanks 1
8 minutes ago, oz11 said:

Can it not be done with iindex++ and function parameters?

Maybe. I have no way of knowing what you intend to do with the index and the function parameters.

Two things to bear in mind

  1. ID values must be unique - you cant have several inputs all with the id="comment_text2"
  2. When you define an event listener on page load, it is only attached to elements that exist when the page has loaded and not to elements you add dynamically.

When user selects emojiSelect2 ("select") it places the emoji into comment_text2..  but it only works on the first comment box..

 

I want to use the index increment to act as a unique identifier (indeed) and then use that in the functions parameter  the javascript... this should then allow me to use the select form (including dropdown and textarea) for all the other comments,,.. should work just don't know how.

Thanks for looking at it. I manged to solve it....

 

the code looks like this now....

 

<script>
// Function to initialize emoji selector for a comment section
function initializeEmojiSelector(sectionId) {
    const section = document.querySelector(`.comment-section[data-section-id="${sectionId}"]`);
    const textarea = section.querySelector('.comment-textarea');
    const emojiSelect = section.querySelector('.emoji-select');

        const emojis = [
        '(・ω・)', '(´・ω・`)', '(。♥‿♥。)', 'ヾ(⌐■_■)ノ♪', '(╯°□°)╯︵ ┻━┻'
    ];

    // Populate the emoji selector dropdown
    emojis.forEach(emoji => {
        const option = new Option(emoji, emoji); // Create a new option element
        emojiSelect.add(option); // Add option to the dropdown
    });

    // Event listener for emoji selection
    emojiSelect.addEventListener('change', function() {
        const selectedEmoji = this.value;
        if (selectedEmoji) {
            const cursorPos = textarea.selectionStart; // Get current cursor position
            const textBeforeCursor = textarea.value.substring(0, cursorPos);
            const textAfterCursor = textarea.value.substring(cursorPos);
            const newText = textBeforeCursor + selectedEmoji + textAfterCursor;
            textarea.value = newText; // Insert selected emoji at cursor position
            textarea.focus(); // Keep focus on textarea
        }
    });
}

// Initialize emoji selectors for all comment sections on DOMContentLoaded
document.addEventListener('DOMContentLoaded', function() {
    const commentSections = document.querySelectorAll('.comment-section');

    commentSections.forEach(section => {
        const sectionId = section.getAttribute('data-section-id');
        initializeEmojiSelector(sectionId);
    });
});
</script>

 


    <div class="comment-section" data-section-id="2">
        <textarea class="comment-textarea"></textarea>
        <select class="emoji-select"></select>
    </div>
  • 2 weeks later...

To dynamically create multiple instances of your emoji selector and text area pair, you can use a loop to generate unique IDs for each pair and then initialize the event listeners accordingly.

<!DOCTYPE html>
<html>
<head>
    <title>Dynamic Emoji Selector</title>
</head>
<body>
    <!-- Add a container where the emoji selector and text area pairs will be added -->
    <div id="emojiContainer"></div>

    <!-- Your original emoji selector and text area template -->
    <select id="emojiSelectTemplate">
        <option value="">Select a kaomoji</option>
    </select>
    <textarea name="comment_text_template" class="comment_text" rows="2" cols="40" placeholder="Type comment reply here." required></textarea>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const emojis = [
                '(・ω・)', '(´・ω・`)', '(。♥‿♥。)', 'ヾ(⌐■_■)ノ♪', '(╯°□°)╯︵ ┻━┻'
            ];

            // Get a reference to the emoji container
            const emojiContainer = document.getElementById('emojiContainer');
            
            // Loop to create multiple instances
            const numInstances = 30; // Change this to the number of instances you need
            for (let i = 0; i < numInstances; i++) {
                // Clone the template elements
                const emojiSelect = document.getElementById('emojiSelectTemplate').cloneNode(true);
                const inputText = document.getElementsByClassName('comment_text')[0].cloneNode(true);

                // Set unique IDs for each instance
                emojiSelect.id = 'emojiSelect' + i;
                inputText.id = 'comment_text' + i;

                // Append cloned elements to the container
                emojiContainer.appendChild(emojiSelect);
                emojiContainer.appendChild(inputText);

                // Populate the select dropdown with emojis
                emojis.forEach(emoji => {
                    const option = document.createElement('option');
                    option.value = emoji;
                    option.text = emoji;
                    emojiSelect.appendChild(option);
                });

                // Event listener for emoji selection
                emojiSelect.addEventListener('change', function() {
                    const selectedEmoji = this.value;
                    if (selectedEmoji) {
                        inputText.value += selectedEmoji;
                        this.selectedIndex = 0; // Reset dropdown to default option after selection
                    }
                });
            }
        });
    </script>
</body>
</html>

In this modified version:

I've added a <div> with the id emojiContainer where the dynamic instances of emoji selectors and text areas will be added.

The original emoji selector and text area are now considered as templates (with id="emojiSelectTemplate" and class="comment_text" respectively).

Inside the loop, I clone the template elements, set unique IDs for each instance, and then append them to the container.

Best Regard

Danish hafeez | QA Assistant

ICTInnovations

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.