1

I'm trying to add fields dynamically by clicking a button to add them and a button for removing them, I want two fields to appear at the beginning and to be required and there is the option to add more and remove the extra ones. The purpose of this is for adding multiple choice question answers to a question that is being created.

This is my code so far

The form

<div v-if="form.response_type_id === 2">
    <el-divider></el-divider>
    <div v-for="(option, index) in options" :key="index">
        <el-row>
            <el-col :span="22">
                <p class="el-form-item__label">Opciones</p>
            </el-col>
            <el-col :span="2">
                <div class="btn-link-plus action-button" @click="addOption(index)">
                    <i class="fas fa-plus" v-show="index == options.length - 1"></i>
                </div>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="20">
                <el-form-item prop="option">
                    <el-input v-model="option.option"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="2">
                <div class="btn-link-delete action-button" @click="removeOption(index)">
                    <i class="fas fa-trash-alt"
                        v-show="index || (!index && options.length > 1)"></i>
                </div>
            </el-col>
        </el-row>
</div>

Data

options: [];

Methods

addOption() {
    this.options.push({
        survey_question_id: this.form.id,
        option: ''
    });
},
removeOption(index) {
    this.options.splice(index, 1);
},

Currently, nothing shows up, everything inside the <div v-for> does not appear. The logic behind the code is that when the response type of the question is set as multiple choice the above code will appear inside the form to allow the user to then create the different choices, two of them being required. Ideally I would like to add a delete button only to the inputs that are added and not the ones that are required.

1 Answer 1

1

Your explanation is a little misleading. What I have noticed is that you want at least two answers. If I understood correctly:

removeOption(index) {
    if(this.options.length<=2) {
        alert('')
    } else {
        this.options.splice(index, 1);
    }
},

To select two options by default:

data() {
    return {
        options: [{option1Obj}, {option2Obj}]
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

is there a way to start with 2 options from the start too?
@Nancy answer eddited

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.