Using vue.js to bind values from inputs that are generated dynamically

Below is a simplified version of the code I have for generating comments:

<div v-for="(g, gi) in submission.goals" :key="gi">
    <div>
        <p >Goal #{{gi+1}}</p>
        <div>{{g.text}}</div>
    </div>
    <div>
        <p>Comments:</p>
        <div><span class="uk-text-small uk-text-muted"><i>no comments</i></span></div>
        <hr>
        <div>
            <a href="" @click="submitComment(g.id, g.user_id, g.phase, $event)"></a>
            <textarea class="comment-input" placeholder="type your comment here"></textarea>
        </div>
    </div>
</div>

Here is my method:

submitComment(gid,uid,phase,e)
{
    e.preventDefault();
    //var comment -> get the value of the closes textaraea here
    console.log(gid, uid, phase, comment);

    //here I will make the ajax call to the API
}

The divs are generated in a loop based on the size of the submission.goals array from the API.

How can I retrieve the value from the closest textarea input to the anchor that triggers the submit function?

I cannot have a separate data object for each comment area because the size of the submission.goals array is not predetermined. Using v-model="comment" on each input would propagate any user input to all textareas.

While I know how to handle this with jQuery, I am still learning how to do it in Vue.js.

Answer №1

If you designate the text area as a reference, you will be able to create a collection of textarea elements. By utilizing the index number of the v-for items (gi in this instance), you can access the [gi] element from the references list and submit its value.

<a href="" @click="submitComment(g.id, g.user_id, g.phase, $event, gi)"></a>
<textarea ref="comment" class="comment-input" placeholder="type your comment here"></textarea>
submitComment(gid,uid,phase,e, gi)
{
    e.preventDefault();
    var comment = this.$refs.comment[gi].value;
    console.log(gid, uid, phase, comment);

    //At this point, an AJAX call to the API will be initiated
}

Answer №2

Consider updating the variable submission.goals to utilize a computed property called submissionGoals. Implement this computed property with the following code snippet:

submissionGoals(){
  return this.submission.goals.map(goal => ({...goal, comment: ''}));
}

Apply v-model="g.comment" to the textarea element. Next, modify the function

submitComment(g.id, g.user_id, g.phase, $event)
to submitComment(g, $event), as suggested by Alexander Yakushev.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for updating the content within an HTML tag with jQuery

I am looking to update the parameter value of an applet tag based on the selection from a dropdown menu. As I am new to jQuery, I would appreciate any guidance on how to achieve this using jQuery. This is my current applet code: <applet id="decisiontr ...

What steps can be taken to troubleshoot a jQuery / JavaScript conflict?

I am facing an issue with my web page, which includes two WebUsercontrols(.ascx): one for a slide show and the other for FullCalendar. When running each user control separately, they work fine. However, when both are included on the same page, a script con ...

What is the method for defining field names in Highcharts?

Having experience with Kendo UI charts, I am new to highcharts. In Kendo, we could specify the fieldname for plotting the chart like this: series: [{ name: "steps", field: "steps", categoryField: "createddate" }] We could also define the data ...

"Failure to update variables within the catch block of the .map() function leads to inconsistencies

Greetings Sorcerers, I have been utilizing .map() to loop through an array of Objects. Following some data manipulations and assigning values to specific variables, I am inserting them into a postgres database. const insertIntoDB = (jsonObj) => { le ...

After inserting the Telerik component, the code <% ... %> is throwing an error

I have a webpage with ASPX that utilizes JavaScript and ASP components without issues. However, after adding a Telerik combobox, I encountered an error: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %& ...

Tips for verifying elements using the Loop technique in a JSON array

I am new to JavaScript and I have been trying to run the following code with an expected result like this: [["00:04:12","05:54:46"],["06:06:42","12:45:22"],["12:51:11","15:56:11"]] However, my script is not working as expected. Can someone please help ...

How can information be effectively passed from the controller to Vue.js within the Laravel-Vue.js framework?

This is my first time attempting this approach and I seem to have hit a bump in the road. Although I have successfully set the data in the controller, added the mycourses entry, it doesn't seem to be appearing as expected. The rest of the data is com ...

Issue with validating alphanumeric value with multiple regex patterns that allow special characters

I have created a regular expression to validate input names that must start with an alphanumeric character and allow certain special characters. However, it seems to be accepting invalid input such as "sample#@#@invalid" even though I am only allowing sp ...

Utilize regular expressions in TamperMonkey to extract specific groups of text

I'm currently working on a TamperMonkey userscript that aims to identify URLs matching a specific pattern, visit these pages, extract relevant information, and then update the link for each URL with the extracted text. I'm facing some challenges ...

I encounter issues when entering conditions in my JavaScript code

Being new to JavaScript, I'm trying to save the Vector position and use two buttons (forward and backward) to move the Camera to that specific location. I also attempted to incorporate 'gsap' for smooth movements, but unfortunately, the code ...

"Looking to trigger a server click using JQuery or Javascript in your code? Here's how you can

I am facing an issue with triggering a Server-Side OnClick event on an ASP Server Button within a User Control using JavaScript or JQuery. The current methods I have tried do not produce the desired result as they do not actually simulate a user clicking t ...

An error was thrown due to an unexpected end of JSON input while fetching from localhost

After running the code snippet provided, I encountered an Uncaught SyntaxError: Unexpected end of JSON input. As a beginner in coding, any guidance or assistance would be greatly appreciated. Thank you. fetch('http://localhost:3000/add-user', { ...

In Phaser 3 JavaScript, I observed two objects in the display, both overlapping each other, yet no events were triggered

My goal is to make the coin disappear when the player overlaps with it. However, for some reason, the cutcoin function is not being called and I'm not sure why. function create() { var healthGroup = this.physics.add.staticGroup({ key: &ap ...

Unconventional Quirks of Equalizing Arrays from Split CSV Strings

Update - It appears that we might be dealing with a localized bug. Further testing is required to confirm... I have a CSV String (containing spaces) that resembles the following: var myString = "Here is a value, I am an important value, One last value" ...

Executing code in Nuxt.js upon page loading

Is there a way to execute code when a page loads in Nuxt.js? I am looking to include a class if the browser supports touch events by using !!window.ontouchstart. My attempt resulted in an error because window is undefined: <section v-bind:class="{ t ...

Highlighting in ThreeJS/Projector Interface

Is there a way to incorporate a 2D sprite underneath a 3D object on top of a plane in order to indicate that my objects are highlighted or selected? Additionally, how can this be achieved on uneven terrain? To provide further clarification, I have includ ...

Experimenting with incorporating easing effects into jQuery tabs

Could someone please help me implement an easing/fading effect on tabs using jQuery? I am looking to add an easing effect to my current code and also incorporate two CSS classes to change the background color along with the text color. Thank you for any as ...

Is it possible to extract link text when clicked on?

Could someone help me with coding a feature for my website where clicking on a link not only opens the page but also copies the link text to the user's clipboard? Appreciate any assistance, thank you! ...

React component failing to update when props change

After loading correctly, my react component fails to re-render when props change. Despite the fact that render() is being called and the list array contains the correct data according to console.log(list), the page does not refresh. Adding a setState in co ...

How to delete URL parameters in JavaScript and HTML5

I have a URL that looks like this: /users/?i=0&p=90 How can I remove the part from ? to 90 Can anyone provide me with some JavaScript code to achieve this? EDIT I mean doing this with window.location.href directly in the browser URL bar. I trie ...