how to popup form with django formset

i’ve have application in the home page there shows some posts with a contact form, i want to create a modal formset in another view! is it possible please ?

@login_required
def addPopupVistor(request):
    formset = VistorFormSet(queryset=Vistor.objects.none(),prefix='formsetvisitor')
    if request.is_ajax() and request.method == 'POST':
        formset = VistorFormSet(request.POST,prefix='formsetvisitor')
        if formset.is_valid():
        for form in formset:
            obj = form.save(commit=False)
            if form.cleaned_data !={}:                    
                obj.admin = request.user
                obj.save()
                return JsonResponse({'success':True})
    else:
        return JsonResponse({'success':False,'error_msg':formset.errors})

return render(request,'main/home.html',{'formsetvisitor':formset})

    const addNewFormRow = document.getElementById('addPopUpButton')
    const totalNewPopUpForms = document.getElementById('id_formsetvisitor-TOTAL_FORMS')
    addNewFormRow.addEventListener('click',add_new_popuprow);

    function add_new_popuprow(e){            
    if(e){
        
        e.preventDefault();
    }  
    const currentFormPopUpClass = document.getElementsByClassName('popup_modal_formset')

    const countpopupForms = currentFormPopUpClass.length        

    const formCopyPopupTarget = document.getElementById('visitorform')

    const empty_form = document.getElementById('empty_popup_formset').cloneNode(true);        
    empty_form.setAttribute('class','relative p-2 bg-gray-900 bg-opacity-25 border border-gray-900 rounded-xl pb-14 popup_modal_formset')
    empty_form.setAttribute('id',`form-${countpopupForms}`)
    const rgx = new RegExp('__prefix__','g')
    empty_form.innerHTML = empty_form.innerHTML.replace(rgx,countpopupForms)

    totalNewPopUpForms.setAttribute('value',countpopupForms + 1)
    formCopyPopupTarget.append(empty_form)

    }
<button onclick="modal()" class="some css class">add new guest</button>

<div id="modal" class="w-full fixed top-0 md:overflow-y-scroll hidden flex flex-wrap p-1 h-screen justify-center items-center bg-black opacity-90" style="z-index: 99999;">
    <div class="w-full md:w-10/12 p-2 bg-white rounded-xl">
        <button id="addPopUpButton" class="px-4 py-1 pb-2 text-white focus:outline-none header rounded-xl">
            {% trans "add new form" %}
            <i class="fas fa-plus"></i>
        </button>
        <form method="POST" class="mt-2" id="addnewguests">{% csrf_token %}

            {{formsetvisitor.management_form}}
            
            <div id="visitorform" class="grid md:grid-cols-3 gap-16 md:gap-x-3 md:gap-y-8">
                {% for form in formsetvisitor.forms %}
                {{ form.pk }}    
                {{form}}
                <!-- first form -->
                <div class="relative p-2 bg-gray-900 bg-opacity-25 border border-gray-900 rounded-xl pb-14 popup_modal_formset">
                
    
                    <div class="relative groupinput bglightpurple rounded-xl">
                        <label class="absolute mt-1 mr-2 text-xs text-white top-1">full name</label>
                        {{form.full_name | add_class:'w-full pt-6 pb-1 pr-2 text-white bg-transparent focus:outline-none'}}

                    </div>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 md:gap-1">
                        <div class="relative mt-2 groupinput bglightpurple rounded-xl">
                            <label class="absolute mt-1 mr-2 text-xs text-white top-1">dob</label>
        
                            {{form.dob | add_class:'w-full pt-6 pb-1 pr-2 text-white bg-transparent focus:outline-none'}}
                            {% if form.dob.errors %}
                            <p class="w-full pb-2 pr-2 text-white rounded-xl" id="dob_error">{{form.dob.errors}}</p>
                            {% endif %}
                        </div>
                        <div class="relative mt-2 groupinput bglightpurple rounded-xl">
                                <label class="absolute mt-1 mr-2 text-xs text-white top-1">city </label>
                                {{form.city | add_class:'w-full pt-6 pb-1 pr-2 text-white bg-transparent focus:outline-none city'}}
                                {% if form.city.errors %}
                                <p class="pb-2 pr-2 text-white rounded-xl" id="city_error">{{form.city.errors}}</p>
                                {% endif %}
                        </div>
                    </div>
        
                    <div class="grid grid-cols-1 md:grid-cols-2 md:gap-1">
                        <div class="relative mt-2 groupinput bglightpurple rounded-xl">
                                <label class="absolute mt-1 mr-2 text-xs text-white top-1">nation</label>
                                {{form.nation | add_class:'w-full pt-6 pb-1 pr-2 text-white bg-transparent focus:outline-none'}}
                                {% if form.nation.errors %}
                                <p class="w-full pb-2 pr-2 text-white rounded-xl" id="nation_error">{{form.nation.errors}}</p>
                                {% endif %}
                        </div>
                        <div class="relative mt-2 groupinput bglightpurple rounded-xl">
                                <label class="absolute mt-1 mr-2 text-xs text-white top-1">gender </label>
                                {{form.gender | add_class:'w-full pt-6 pb-1 pr-2 text-white bg-transparent'}}
                                {% if form.gender.errors %}
                                <p class="w-full pb-2 pr-2 text-white rounded-xl" id="gender_error">{{form.gender.errors}}</p>
                                {% endif %}
                        </div>
                    </div>
                        <div class="relative mt-2 groupinput bglightpurple rounded-xl">
                                <label class="absolute mt-1 mr-2 text-xs text-white top-1">job </label>
                                {{form.job | add_class:'w-full pt-6 pb-1 pr-2 text-white bg-transparent focus:outline-none'}}
                                {% if form.job.errors %}
                                <p class="w-full pb-2 pr-2 text-white rounded-xl" id="job_error">{{form.job.errors}}</p>
                                {% endif %}
        
                        </div>
                </div>                    
                {% endfor %}
            </div>
            
                <div class="relative p-2 bg-gray-900 bg-opacity-25 border border-gray-900 rounded-xl pb-14 hidden" id="empty_popup_formset">                   
                    <div class="relative groupinput bglightpurple rounded-xl">
                        <label class="absolute mt-1 mr-2 text-xs text-white top-1">full name</label>
                        {{formsetvisitor.empty_form.full_name | add_class:'w-full pt-6 pb-1 pr-2 text-white bg-transparent focus:outline-none'}}
                        {% if formsetvisitor.empty_form.full_name.errors %}
                        <p class="w-full pb-2 pr-2 text-white rounded-xl" id="full_name_set_error" >{{formsetvisitor.empty_form.full_name.errors}}</p>
                        {% endif %}
                    
        
                    </div>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 md:gap-1">
                        <div class="relative mt-2 groupinput bglightpurple rounded-xl">
                                <label class="absolute mt-1 mr-2 text-xs text-white top-1">dob</label>
                                {{formsetvisitor.empty_form.dob | add_class:'w-full pt-6 pb-1 pr-2 text-white bg-transparent focus:outline-none'}}
                                <p class="w-full pb-2 pr-2 text-white rounded-xl" id="dob_set_error">{{formsetvisitor.empty_form.dob.errors}}</p>
        
                        </div>
                        <div class="relative mt-2 groupinput bglightpurple rounded-xl">
                                <label class="absolute mt-1 mr-2 text-xs text-white top-1">city</label>
                                {{formsetvisitor.empty_form.city | add_class:'w-full pt-6 pb-1 pr-2 text-white bg-transparent focus:outline-none'}}
                                <p class="w-full pb-2 pr-2 text-white rounded-xl" id="city_set_error" >{{formsetvisitor.empty_form.city.errors}}</p>
        
                        </div>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-2 md:gap-1">
                        <div class="relative mt-2 groupinput bglightpurple rounded-xl">
                                <label class="absolute mt-1 mr-2 text-xs text-white top-1">nation</label>
                                {{formsetvisitor.empty_form.nation | add_class:'w-full pt-6 pb-1 pr-2 text-white bg-transparent focus:outline-none'}}
                                <p class="w-full pb-2 pr-2 text-white rounded-xl" id="nation_set_error" >{{formsetvisitor.empty_form.nation.errors}}</p>
        
                        </div>
                        <div class="relative mt-2 groupinput bglightpurple rounded-xl">
                                <label class="absolute mt-1 mr-2 text-xs text-white top-1">gender </label>
                                {{formsetvisitor.empty_form.gender | add_class:'w-full pt-6 pb-1 pr-2 text-white bg-transparent focus:outline-none'}}
                                <p class="w-full pb-2 pr-2 text-white rounded-xl" id="gender_set_error" >{{formsetvisitor.empty_form.gender.errors}}</p>
        
                        </div>
                    </div>
                        <div class="relative mt-2 groupinput bglightpurple rounded-xl">
                                <label class="absolute mt-1 mr-2 text-xs text-white top-1">job </label>
                                {{formsetvisitor.empty_form.job | add_class:'w-full pt-6 pb-1 pr-2 text-white bg-transparent focus:outline-none'}}
                                <p class="w-full pb-2 pr-2 text-white rounded-xl" id="job_set_error" >{{formsetvisitor.empty_form.job.errors}}</p>
        
                        </div>
        
                    </div>    
            <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse rtl">
                <input name="visitorformbtn" type="submit" class="some css class" value="{% trans "save" %}">
                    
                <button id="cancel" class="some css class">
                    {% trans "cancel" %}
                </button>
              </div>
    
        </form>
    
    </div>
</div>

but i dont have any idea how to call back it in the home page without make it in the home view ? and the form will go through ajax request to save the forms, but i dont know how to call the form inputs into the home template .
i appreciate any idea

How to duplicate every index of an array with Javascript?

I’m struggling with this because all search engine results are about find duplicates in array. And I want exactly the opposite.

I have an array of colors:

const colors = ["#fff", "#666", "#000"];

How do I simply duplicate or triplicate every one of its indexes?

x2: ["#fff", "#fff", "#666", "#666", "#000", "#000"];

x3: ["#fff", "#fff", "#fff", "#666", "#666", "#666", "#000", "#000", "#000"];

x…

How to change product version with Electron Builder (Windows)?

I am using Electron Builder to build an Electron app. I would like the executable to have a product version that is different from the package.json version.

This is what the build instruction in package.json looks like:

"build": {
    "appId": "myAppId",
    "productName": "My App",
    "copyright": "Copyright (C) 2022 My Company",
    "artifactName": "My App.exe",
    "directories": {
        "output": "dist/My App"
    },
    "buildVersion": "1.0.0.1"
},

I thought that buildVersion would update the product version, but when I look at the details of the .exe file, the product version has remained the same as the version number in package.json (1.0.0):

App details

How can I solve this?

VueJS : How can I pre-populate my input with data from API?

I have an edit form, and I’m trying to populate my input base on the response from API. My campaign data look like this.

{
    "id": 219,
    "name": "finishedddd-1642606412049"
}

enter image description here

Testing

You see that I can access campaign.name like this

<p>Campaign Name : {{ campaign.name }}</p>

Trying

I want to pre-populated my name input, so I did this

data() {
    return {
        campaign: {},
        form: {
            errors: {},
            values: {
                name: this.campaign.name,
                ...

Result

Somehow that kept getting me :

“TypeError: Cannot read properties of undefined (reading ‘name’)”

enter image description here

Code

<template>
    <v-container fluid class="my-1">
        <Navbar />
        <Breadcrumbs />
        <v-row>
            <v-col cols="12">
                <v-card elevation="2">
                    <PanelHeader type="create" icon="campaign" title="Campaigns" />

                    <v-stepper v-model="e1" justify="center" elevation="0">
                        <v-stepper-header>
                            <v-stepper-step :complete="e1 > 1" step="1"> Campaign </v-stepper-step>
                            <v-divider></v-divider>
                            <v-stepper-step :complete="e1 > 2" step="2"> Setup </v-stepper-step>
                            <v-divider></v-divider>
                            <v-stepper-step step="3"> Finish </v-stepper-step>
                        </v-stepper-header>

                        <v-stepper-items>
                            <v-stepper-content step="1">
                                <v-card class="mb-12" elevation="0">
                                    <v-form ref="form" lazy-validation v-model="valid" id="form">
                                        <v-row>
                                            <v-card-text class="font-weight-bold">
                                                Campaigns

                                                <p>Campaign Name : {{ campaign.name }}</p>

                                                <v-tooltip right>
                                                    <template v-slot:activator="{ on, attrs }">
                                                        <v-btn icon v-bind="attrs" v-on="on">
                                                            <v-icon color="grey lighten-1">info</v-icon>
                                                        </v-btn>
                                                    </template>
                                                    <span>Select marketing campaign type for Print Materials or Product Tags. Provide a name to identify the marketing campaign.</span>
                                                </v-tooltip>
                                            </v-card-text>
                                        </v-row>

                                        <v-row>
                                            <v-col class="col-sm-2 col-lg-2 col-12">
                                                <v-select disabled dense outlined :items="types" label="Type" v-model="form.values.type" :rules="form.rules.type"></v-select>
                                            </v-col>
                                            <v-col cols="12" sm="6" md="2">
                                                <v-text-field dense outlined v-model="form.values.name" :rules="form.rules.name" label="Name" required></v-text-field>
                                            </v-col>
                                        </v-row>
                                        <v-row>
                                            <v-col cols="12" sm="6" md="4">
                                                <v-textarea dense rows="1" outlined v-model="form.values.description" label="Description" required></v-textarea>
                                            </v-col>
                                        </v-row>

                                        <v-row>
                                            <v-card-text class="font-weight-bold"
                                                >Schedule :

                                                <v-tooltip right>
                                                    <template v-slot:activator="{ on, attrs }">
                                                        <v-btn icon v-bind="attrs" v-on="on">
                                                            <v-icon color="grey lighten-1">info</v-icon>
                                                        </v-btn>
                                                    </template>
                                                    <span>Set the time zone, start and end date for this campaign to be active.</span>
                                                </v-tooltip>
                                            </v-card-text>

                                            <v-col cols="12" sm="6" md="4">
                                                <v-select dense outlined :items="timezones" v-model="form.values.timezone" :rules="form.rules.timezone" label="Timezone" append-icon="lock_clock"></v-select>
                                            </v-col>
                                        </v-row>

                                        <v-row>
                                            <v-col cols="12" sm="6" md="2">
                                                <v-menu v-model="form.values.startDateMenu" :close-on-content-click="false" :nudge-right="40" transition="scale-transition" offset-y min-width="auto">
                                                    <template v-slot:activator="{ on, attrs }">
                                                        <v-text-field dense outlined v-model="form.values.startDate" :rules="form.rules.startDate" label="Start Date" append-icon="mdi-calendar" readonly v-bind="attrs" v-on="on"></v-text-field>
                                                    </template>
                                                    <v-date-picker v-model="form.values.startDate"></v-date-picker>
                                                </v-menu>
                                            </v-col>

                                            <v-col cols="12" sm="6" md="2">
                                                <v-menu ref="menu" v-model="startTimeMenu" :close-on-content-click="false" :nudge-right="40" :return-value.sync="form.values.startTime" transition="scale-transition" offset-y max-width="290px" min-width="290px">
                                                    <template v-slot:activator="{ on, attrs }">
                                                        <v-text-field dense v-model="form.values.startTime" label="Start Time" append-icon="mdi-clock-time-four-outline" readonly v-bind="attrs" v-on="on" outlined></v-text-field>
                                                    </template>
                                                    <v-time-picker v-if="startTimeMenu" v-model="form.values.startTime" full-width @click:minute="$refs.menu.save(form.values.startTime)"></v-time-picker>
                                                </v-menu>
                                            </v-col>
                                        </v-row>

                                        <v-row>
                                            <v-col cols="12" sm="6" md="2">
                                                <v-menu v-model="endDateMenu" :close-on-content-click="false" :nudge-right="40" transition="scale-transition" offset-y min-width="auto">
                                                    <template v-slot:activator="{ on, attrs }">
                                                        <v-text-field dense outlined v-model="form.values.endDate" :rules="form.rules.endDate" :min="form.values.startDate" label="End Date" append-icon="mdi-calendar" readonly v-bind="attrs" v-on="on"></v-text-field>
                                                    </template>
                                                    <v-date-picker v-model="form.values.endDate"></v-date-picker>
                                                </v-menu>
                                            </v-col>

                                            <v-col cols="12" sm="6" md="2">
                                                <v-menu ref="menu" v-model="endTimeMenu" :close-on-content-click="false" :nudge-right="40" :return-value.sync="form.values.endTime" transition="scale-transition" offset-y max-width="290px" min-width="290px">
                                                    <template v-slot:activator="{ on, attrs }">
                                                        <v-text-field dense v-model="form.values.endTime" label="End Time" append-icon="mdi-clock-time-four-outline" readonly v-bind="attrs" v-on="on" outlined></v-text-field>
                                                    </template>
                                                    <v-time-picker v-if="endTimeMenu" v-model="form.values.endTime" :min="form.values.startTime" full-width @click:minute="$refs.menu.save(form.values.endTime)"></v-time-picker>
                                                </v-menu>
                                            </v-col>
                                        </v-row>
                                    </v-form>
                                </v-card>

                                <v-btn color="primary" @click="validate()" :disabled="!valid"> Continue </v-btn>
                                <router-link :to="`/${segment1}`">
                                    <v-btn text> Cancel </v-btn>
                                </router-link>
                            </v-stepper-content>

                            <v-stepper-content step="2">
                                <v-card class="mb-12" elevation="0">
                                    <v-form ref="form2" lazy-validation v-model="valid2" id="form2">
                                        <v-row>
                                            <v-card-text class="font-weight-bold">
                                                Destination

                                                <v-tooltip right>
                                                    <template v-slot:activator="{ on, attrs }">
                                                        <v-btn icon v-bind="attrs" v-on="on">
                                                            <v-icon color="grey lighten-1">info</v-icon>
                                                        </v-btn>
                                                    </template>
                                                    <span>The scan destination is the end point for a consumer experience. Can be single URL or use URL Groups. </span>
                                                </v-tooltip>
                                            </v-card-text>
                                        </v-row>

                                        <v-row>
                                            <v-col class="col-sm-2 col-lg-2 col-12">
                                                <v-select dense outlined :items="urlTypes" label="Single or Multi URL" v-model="form.values.urlType" :rules="form.rules.urlType"></v-select>
                                            </v-col>
                                            <v-col cols="12" sm="6" md="2">
                                                <v-text-field dense outlined v-model="form.values.url" :rules="form.rules.url" label="URL" required></v-text-field>
                                            </v-col>
                                        </v-row>

                                        <v-row>
                                            <v-card-text class="font-weight-bold"
                                                >Conditions :

                                                <v-tooltip right>
                                                    <template v-slot:activator="{ on, attrs }">
                                                        <v-btn icon v-bind="attrs" v-on="on">
                                                            <v-icon color="grey lighten-1">info</v-icon>
                                                        </v-btn>
                                                    </template>
                                                    <span>Set the conditions for a campaign. If all conditions are true, this campaign will trigger for consumer experience.</span>
                                                </v-tooltip>
                                            </v-card-text>

                                            <v-col cols="12" sm="6" md="4">
                                                <v-select dense outlined :items="attributes" item-text="name" item-value="id" v-model="form.values.attribute" :rules="form.rules.attribute" label="Attribute"></v-select>
                                            </v-col>

                                            <v-col cols="12" sm="6" md="1">
                                                <v-combobox v-model="operator" :items="operators" item-text="operator" item-value="id" label="Operator" outlined dense></v-combobox>
                                            </v-col>

                                            <v-col cols="12" sm="6" md="4">
                                                <!-- <v-text-field dense outlined v-model="form.values.value" :rules="form.rules.value" label="Values" required></v-text-field> -->

                                                <v-text-field v-model="value" :items="values" label="Value" multiple outlined dense></v-text-field>
                                            </v-col>
                                        </v-row>
                                    </v-form>
                                </v-card>

                                <v-btn color="primary" @click="validate2()" :disabled="!valid2"> Update </v-btn>

                                <v-btn text @click="e1 = 1"> Back </v-btn>
                            </v-stepper-content>

                            <v-stepper-content step="3"> </v-stepper-content>
                        </v-stepper-items>
                    </v-stepper>
                </v-card>
            </v-col>
        </v-row>
    </v-container>
</template>

<script>
import Navbar from '../../../components/Navbar'
import Breadcrumbs from '../../../components/Breadcrumbs'
import PanelHeader from '../../../components/PanelHeader'
import axios from 'axios'
import moment from 'moment-timezone'

export default {
    components: {
        Navbar,
        Breadcrumbs,
        PanelHeader
    },
    beforeMount() {},
    computed: {
        segment1: function () {
            const firstSegment = new URL(window.location.href).pathname.split('/')[1]
            return `${firstSegment}`
        },
        timeZone: function () {
            console.log('timeZone')
        }
    },
    beforeMount() {},

    mounted() {
        this.getCampaign()
    },

    data() {
        return {
            campaign: {},
            form: {
                errors: {},
                values: {
                    name: this.campaign.name,
                    type: 'Marketing',
                    description: null,
                    timezone: 'America/New_York',
                    startDate: new Date(Date.now() - new Date().getTimezoneOffset() * 60000).toISOString().substr(0, 10),
                    endDate: new Date(Date.now() - new Date().getTimezoneOffset() * 60000).toISOString().substr(0, 10),
                    startTime: moment().format('HH:mm'),
                    endTime: '24:00',
                    urlType: 'Single',
                    url: 'https://',
                    attribute: '',
                    operator: '',
                    value: ''
                },
                rules: {
                    type: [(v) => !!v || 'Type is required'],
                    name: [(v) => !!v || 'Name is required'],
                    startDate: [(v) => !!v || 'Start Date is required'],
                    endDate: [(v) => !!v || 'End Date is required'],
                    timezone: [(v) => !!v || 'Timezone is required'],
                    startTime: [(v) => !!v || 'Start Time is required'],
                    endTime: [(v) => !!v || 'End Time is required'],
                    urlType: [(v) => !!v || 'URL Type is required'],
                    url: [(v) => !!v || 'URL is required'],
                    attribute: [(v) => !!v || 'Attribute is required'],
                    operator: [(v) => !!v || 'Operator is required'],
                    value: [(v) => !!v || 'Value is required']
                }
            },
            e1: 1,
            valid: false,
            valid2: false,
            types: ['Product', 'Marketing'],
            operator: [],
            operators: ['=', '!=', 'in', 'not in'],
            value: [],
            values: ['Italy', 'Finland', 'Norway'],
            timezones: moment.tz.names(),
            startDateMenu: false,
            endDateMenu: false,
            startTimeMenu: false,
            endTimeMenu: false,
            urlTypes: ['Single', 'Multiple'],
            attributes: []
        }
    },
    watch: {
        'form.values.attribute'() {
            this.operator = null
            axios.defaults.headers['Content-Type'] = 'application/json'
            let data = {
                $root: 'vc_operator',
                op: 'read',
                brand: 'COLM',
                selection: {
                    filters: [`id:${this.form.values.attribute}`]
                },
                _SESSION: localStorage.getItem('session')
            }
            axios.post(`${process.env.VUE_APP_API_ENDPOINT_URL}`, data).then((response) => {
                this.operators = response.data.operators
            })
        }
    },
    methods: {
        getAllData(id) {
            let myForm = document.getElementById(id)
            console.log(
                Array.from(myForm.elements).map((e) => {
                    return e.value
                })
            )
        },
        validate() {
            this.$refs.form.validate()

            if (this.$refs.form.validate()) {
                let data = {
                    $root: 'vc_rule_attribute',
                    op: 'read',
                    brand: 'COLM',
                    _SESSION: localStorage.getItem('session')
                }

                axios.defaults.headers['Content-Type'] = 'applcation/json'
                axios.post(`${process.env.VUE_APP_API_ENDPOINT_URL}`, data).then((response) => {
                    this.attributes = response.data.rule_attributes
                })
                this.e1 = 2
                console.info(this.form.values)
            } else {
                console.info(this.form.values)
            }
        },
        validate2() {
            this.$refs.form2.validate()
            if (this.$refs.form2.validate()) {
                let data = {
                    id: this.form.values.id,
                    name: this.form.values.name,
                    description: this.form.values.description,
                    start_date: this.form.values.startDate,
                    end_date: this.form.values.endDate,
                    priority: '100',
                    status_id: 1,
                    type_id: 1
                }

                let body = {
                    $root: 'vc_campaign',
                    op: 'update',
                    brand: 'COLM',
                    campaigns: [data],
                    _SESSION: localStorage.getItem('session')
                }

                // this.$store
                //  .dispatch('editCampaign', body)
                //  .then(() => {
                //      this.$router.push({
                //          path: `/campaigns`
                //      })
                //  })
                //  .catch((err) => {
                //      console.log('Something went wrong: ', err)
                //  })
            } else {
                console.info(this.form.values)
            }
        },
        displayTime(time) {
            time = time.split(':')[0]
            if (time > 12) {
                return 'PM'
            } else {
                return 'AM'
            }
        },
        getCampaign() {
            let filters = 'id:' + this.$route.params.id
            let body = {
                $root: 'vc_campaign',
                op: 'read',
                brand: 'COLM',
                selection: {
                    filters: [filters]
                },
                _SESSION: localStorage.getItem('session')
            }

            axios.defaults.headers['Content-Type'] = 'applcation/json'
            axios
                .post(`${process.env.VUE_APP_API_ENDPOINT_URL}`, body)
                .then((response) => {
                    if (response.data.status == 0) {
                        this.campaign = response.data.campaigns[0]
                    } else {
                        alert(response.data.statustext)
                        reject(response.data.statustext)
                    }
                })
                .catch((err) => {
                    console.log('Something went wrong: ', err)
                })
        }
    }
}
</script>

<style></style>

parsing out data from an object into two other objects by using an array

Trying to parse out airport data into two by using the array selected_city_codes. So airport data would be into two parts, one with only the selected city codes and the other without the city codes.

I tried to attempt this using modify_airport_data but for some reason airport_data_results is not how I wanted it to be.

What would be the best approach to this problem?

airport_data = [{"departure_time":"12:00","arrival_time":"03:00","city_id":"BOS"},  
{"departure_time" :"12:00","arrival_time":"03:00","city_id":"BOS"},
{"departure_time" :"01:00","arrival_time":"04:00","city_id":"SFO"},
{"departure_time" :"03:00","arrival_time":"05:00","city_id":"DEN"},
{"departure_time" :"03:00","arrival_time":"05:00","city_id":"BOS"},
{"departure_time" :"03:00","arrival_time":"05:00","city_id":"SFO"}]; 

selected_city_data = [];

selected_city_codes=['BOS','SFO'];

function modify_airport_data(airport_data, selected_city_data,selected_city_codes) {
    parsed_airport_data = []; 
    var counter = 0; //for tracking purposes
    for (j=0; j < airport_data.length; j++) {
        for (i=0; i < selected_city_codes.length; i++) {
            if (airport_data[j].city_id == selected_city_codes[i]) {
                selected_city_data.push(airport_data[j]);
                counter = 0; //we reset counter during match
            }
            else{
                counter++; //and increment it if there is no match
            }
            if(counter == selected_city_codes.length) {
                parsed_airport_data.push(airport_data[j]);
            }
        }
    }
    airport_data = parsed_airport_data;
    return airport_data; 
}

airport_data_results = modify_airport_data(airport_data, selected_city_data,selected_city_codes);

Actual Results

airport_data_results = [{departure_time: '01:00',arrival_time: '04:00',city_id: 'SFO' },
{departure_time : '03:00',arrival_time: '05:00',city_id: 'DEN' },
{departure_time : '03:00',arrival_time: '05:00',city_id: 'SFO' } ]

selected_city_data = [{departure_time: '12:00',arrival_time: '03:00',city_id: 'BOS' },
{departure_time : '12:00',arrival_time: '03:00',city_id: 'BOS' },
{departure_time : '01:00',arrival_time: '04:00',city_id: 'SFO' },
{departure_time : '03:00',arrival_time: '05:00',city_id: 'BOS' },
{departure_time : '03:00',arrival_time: '05:00',city_id: 'SFO' } ]

Desired Results

airport_data_results = [{departure_time : '03:00',arrival_time: '05:00',city_id: 'DEN' }]

selected_city_data = [{"departure_time":"12:00","arrival_time":"03:00","city_id":"BOS"},  
{"departure_time" :"12:00","arrival_time":"03:00","city_id":"BOS"},
{"departure_time" :"01:00","arrival_time":"04:00","city_id":"SFO"},
{"departure_time" :"03:00","arrival_time":"05:00","city_id":"BOS"},
{"departure_time" :"03:00","arrival_time":"05:00","city_id":"SFO"}]; 

JSON object array return undefined

I have below scripts on Google Apps Script which will take in an JSON event.
I want the data in element “events”, but it always return “Undefined” to me.

I’m guessing maybe it’s because events is a JSON array and I can’t directly use it in JS?

Here is my code:

function doPost(e) {
  var msg = JSON.parse(JSON.stringify(e.postData.contents));
  
  console.log(msg);
  //log succesfully

  console.log(msg.events);
  //"Undefined"
}

If I try to log the elements in the events instead of the array events itself:

  console.log(msg.events[0].replyToken);
  //"TypeError: Cannot read property '0' of undefined at doPost(app:26:25)"

The result of msg will is in below:

{
  "destination": "U656de3c6b48c8e0d44edda4fd3f05e06",
  "events": [
    {
      "type": "message",
      "message": {
        "type": "text",
        "id": "*********",
        "text": "Hi"
      },
      "timestamp": 1642616050062,
      "source": {
        "type": "group",
        "groupId": "***********",
        "userId": "*************"
      },
      "replyToken": "************",
      "mode": "active"
    }
  ]
}

I’ve seen several similar problems for array in JS.
I tried them but all of them didn’t work, please help me.

Why event handler callback is getting executed immediately before entire call stack is executed?

Please help in explaining why the click event handler is executed before the script is finished executing.

console.log('Script started running')
document.body.addEventListener('click', () => {
  console.log('Click callback executed')
})
console.log('Before click')
document.body.click()
console.log('After click')

My expectation was

Script started running
Before click
After click
Click callback executed

But the output observed on running is

Script started running
Before click
Click callback executed
After click

Should the script not be executed fully(call stack made empty) before any event callback from the task queue is executed ?

if else statement within a function is breaking function in javascript

I am 90% finished with a simple calculator that tells you the cost difference between shopping in person vs shopping online. You can view it below. My only problem is the last sentence. It says

You should shop in person. You’ll save €x everytime you shop.

X updates fine, just try it out and see. My problem is I want to display a string. The value of the string will be determined by an if/else statement.

If (cost of shopping in person < cost of shopping online) {display the above statement with x = difference in cost} Else {You should shop online. You’ll save €x everytime you shop.}

I have included below my code, with my attempted if/else statement commented out because it breaks the code. I have tried just about everything and I’m at a roadblock. Any help would be greatly appreciated.

    var incomePerHour = document.getElementById("income_p_hour");
    var timeToShop = document.getElementById("time_to_shop");
    var deliveryCharge = document.getElementById("delivery_charge");
    var timeToDeliver = document.getElementById("time_to_deliver");

    var inPersonElement = document.getElementById("inPersonCost");
    var deliveryElement = document.getElementById("deliveryCost");
    var summaryElement = document.getElementById("summary");
  //  var summaryFullElement = document.getElementById("summaryFull")

    var inPersonTextElement = document.getElementById("inPersonCostText");
    var deliveryTextElement = document.getElementById("deliveryCostText");
    var summaryTextElement = document.getElementById("summaryText");
    //var summaryFullTextElement = document.getElementById("summaryFullText");



    function updateProfit() {
      var inPersonCost = ((Number(incomePerHour.value)/60) * Number(timeToShop.value)).toFixed(2);
      var deliveryCost = (((Number(incomePerHour.value)/60) * Number(timeToDeliver.value)) + Number(deliveryCharge.value)).toFixed(2);
      var summary = (inPersonCost - deliveryCost).toFixed(2);
    /*  var summaryFull = (if ((parseInt(summary)) > 0){
        "You should shop online. You will save" + summary + "everytime you shop.";
      } else {
        "You should shop in person. You will save" + (summary * -1) + "everytime you shop.";
      })*/
      inPersonElement.value = inPersonCost;
      deliveryElement.value = deliveryCost;
      summaryElement.value = summary;
      //summaryFullElement.value = summaryFull;

      inPersonTextElement.innerText = inPersonCost;
      deliveryTextElement.innerText = deliveryCost;
      summaryTextElement.innerText = summary;
    //  summaryFullTextElement.innerText = summaryFull;

    }

    incomePerHour.onchange = timeToShop.onchange = deliveryCharge.onchange = timeToDeliver.onchange = updateProfit;
    <form method="POST">
      How much do you value your time per hour? <input type="int" id="income_p_hour"> <br />
      How much of your time does it take to go grocery shopping in person in minutes? <input type="int" id="time_to_shop"> <br />
      How much is the delivery charge? <input type="int" id="delivery_charge"> <br />
      How much of your time does it take to order your groceries online in minutes? <input type="int" id="time_to_deliver"> <br />

  <!--  <input type="hidden" id="profit" name="profit"/>
   Profit: $<span id="profitText"></span> -->
<br>
    <input type="hidden" id="inPersonCost" name="inPersonCost"/>
    Cost of shopping in person: <span id="inPersonCostText"></span> <br />
    <input type="hidden" id="deliveryCost" name="deliveryCost"/>
    Cost of shopping online: <span id="deliveryCostText"></span>
<br>
You should shop in person. You'll save €<input type="hidden" id="summary" name="summary"/><span id="summaryText"></span> everytime you shop.
<br>
<!-- <input type="hidden" id="summaryFull" name="summaryFull"/><span id="summaryFullText"></span> -->
    </form>

New array based on objects inside another array

I have an array of appointments objects:

let appointments = [
    { _id: 54321, name: 'app 1', date: "2022-01-20T09:00:00+01:00"},
    { _id: 66756, name: 'app 2', date: "2022-01-20T08:00:00+01:00"},
    { _id: 76889, name: 'app 3', date: "2022-01-21T08:00:00+01:00"},
    { _id: 35790, name: 'app 4', date: "2022-01-22T08:00:00+01:00"},
    { _id: 35790, name: 'app 5', date: "2022-01-25T09:00:00+01:00"}
]

my goal is to create a new array based on the days of the appointments and place them inside, like so:

{ days:
    { 2022-01-20: [
     { _id: 54321, name: 'app 1', date: "2022-01-20T09:00:00+01:00"},
     { _id: 66756, name: 'app 2', date: "2022-01-20T08:00:00+01:00"}
    ]},
    { 2022-01-21: [
     { _id: 76889, name: 'app 3', date: "2022-01-21T08:00:00+01:00"}
    ]},
     { 2022-01-22: [
     { _id: 35790, name: 'app 4', date: "2022-01-22T08:00:00+01:00"}
    ]},
     { 2022-01-23: []},
     { 2022-01-24: []},
     { 2022-01-25: [
      { _id: 35790, name: 'app 5', date: "2022-01-25T09:00:00+01:00"}
     ]},
}

so based on the date creating new unique array and inside the array inserting the proper appointments.

Another feature that I’m trying to make is inserting empty days between the active days (example in the second code)

Thanks for your help

Trying to print input numbers as hash symbol representations

I’d like to print my code “side ways” like :
22 : 22
not

  1. 2
  2. 2
  3. :
  4. 2
  5. 2

What am I doing wrong ?
Since i have to add more normal language words I will talk about my plans with catgirl coin and I really hope we all make it in crypto.
If we all make it, with my first milly I’m buying my self a house in the country side!!!
I think living there will make me a lot healthier

const data = require("./number.json");
const prompt = require("prompt-sync")();
let someArr = [];
let cnt = 0;

const input = prompt("Please add something here: ");

const b = input.split("");

//extract the numbers in an array
for (let i of b) {
  for (let j in data) {
    if (i === j) {
      someArr[cnt] = data[j];
      cnt++;
    }
  }
}
//printing the stuff
for (let i = 0; i < someArr.length; i++) {
  for (j of someArr[i]) {
    for (k of j) {
      if (k === 0) process.stdout.write(" ");
      if (k === 1) process.stdout.write("#");
    }
    console.log("t");
  }
}

Btw my json file looks like this

{
  "0": [
    [1, 1, 1, 1, 1],
    [1, 0, 0, 0, 1],
    [1, 0, 0, 0, 1],
    [1, 0, 0, 0, 1],
    [1, 1, 1, 1, 1]
  ],
  "1": [
    [0, 0, 1, 0, 0],
    [0, 0, 1, 0, 0],
    [0, 0, 1, 0, 0],
    [0, 0, 1, 0, 0],
    [0, 0, 1, 0, 0]
  ],
  "2": [
    [1, 1, 1, 1, 1],
    [0, 0, 0, 0, 1],
    [1, 1, 1, 1, 1],
    [1, 0, 0, 0, 0],
    [1, 1, 1, 1, 1]
  ],
  "3": [
    [1, 1, 1, 1, 1],
    [0, 0, 0, 0, 1],
    [1, 1, 1, 1, 1],
    [0, 0, 0, 0, 1],
    [1, 1, 1, 1, 1]
  ],
  "4": [
    [1, 0, 0, 1, 0],
    [1, 0, 0, 1, 0],
    [1, 1, 1, 1, 1],
    [0, 0, 0, 1, 0],
    [0, 0, 0, 1, 0]
  ],
  "5": [
    [1, 1, 1, 1, 1],
    [1, 0, 0, 0, 0],
    [1, 1, 1, 1, 1],
    [0, 0, 0, 0, 1],
    [1, 1, 1, 1, 1]
  ],
  "6": [
    [1, 1, 1, 1, 1],
    [1, 0, 0, 0, 0],
    [1, 1, 1, 1, 1],
    [1, 0, 0, 0, 1],
    [1, 1, 1, 1, 1]
  ],
  "7": [
    [1, 1, 1, 1, 1],
    [1, 0, 0, 0, 1],
    [0, 0, 0, 0, 1],
    [0, 0, 0, 0, 1],
    [0, 0, 0, 0, 1]
  ],
  "8": [
    [1, 1, 1, 1, 1],
    [1, 0, 0, 0, 1],
    [1, 1, 1, 1, 1],
    [1, 0, 0, 0, 1],
    [1, 1, 1, 1, 1]
  ],
  "9": [
    [1, 1, 1, 1, 1],
    [1, 0, 0, 0, 1],
    [1, 1, 1, 1, 1],
    [0, 0, 0, 0, 1],
    [0, 0, 0, 0, 1]
  ],
  ":": [
    [0, 0, 0, 0, 0],
    [0, 0, 1, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 1, 0, 0],
    [0, 0, 0, 0, 0]
  ]
}

how to remove partial duplication from object of array in typescript/javascript?

What is the best way to filters partial matched object of array in typescript/javascript?
I have one set of object of array that I want to remove the object when value from key ‘name’ is the same

const objArray = [{id: 1, name:{first: 'a', last: 'b'}, phone:123}, {id: 2, name:{first: 'a', last: 'b'}, phone:456}, {id: 3, name:{first: 'c', last: 'd'}, phone:3434}]
// look for return
// [{id: 1, name:{first: 'a', last: 'b'}, phone:123}, {id: 3, name:{first: 'c', last: 'd'}, phone:3434}]

Convert to accordion

I’m new here.

I’m trying to convert my <li> into an accordion in the mobile view.

I actually have something similar to:

<div class="general" id="horizontalTab">
    <div class="list">
        <ul>
            <li class="item1">Item 1</li>
            <li class="item2">Item 2</li>
            <li class="item3">Item 3</li>
        </ul>
    <div>
    <div>
        <div class="item1">Description 1</div>
        <div class="item2">Description 2</div>
        <div class="item3">Description 3</div>
    <div>
<div>

And I have this on the footer.php

<script src="<?php echo get_stylesheet_directory_uri(); ?>/assets/js/jquery.responsiveTabs.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        var $tabs = $('#horizontalTab');
        $tabs.responsiveTabs({
            rotate: false,
            startCollapsed: 'accordion',
            collapsible: 'accordion'
        });

    });
</script>

But it shows me “Uncaught TypeError: oTab is undefined”
So every time I click on the li it displays the related div description.

Now I’d like to convert that into an accordion for the mobile version and moving the description under its <li>.

Any ideas?

I’ve tryied following this: https://www.jqueryhub.com/responsive-tabs-to-accordion-jquery-plugin-responsive-tabs/ but it’s not working 🙁

Thanks!

ReactJS component won’t update after first API call

So I recently started to discover ReactJS. I have a simple Spring Boot api which has a few methods. One of these returns a list of objects. I get these in my frontend by using Axios to make the HTTP call.

export function getItems() {
  const [items, setItems] = useState([]);
  useEffect(async () => {
    await client.get('items').then((result) => {
      setItems(result.data);
    });
  }, []);
  return items;

The items are mapped in a gallery component and shown on screen. Next to this, I have an addItem function which posts an item object obtained through a form to my api.

export async function addPet(newPet) {
      await client.post(
        '/pets',
        newPet,
      );
    }

My AddPet component is loaded inside my Gallery component. The form is shown on the right side of the screen and when I click the “Add Item” button, I want the item to be added and my list of items reloaded to show the newly added item. Right now, I can not get this working in a correct way. If I remove the “[]” from the final part of my useEffect() in my getItems() functions, everything seems to work but in reality the app is making the getItems call over and over again. If I add “[]”, the call is only made once at the start, but will not re-render the gallery component when an item is added. The handleSubmit() for my “Add item” button is as follows:

const handleSubmit = () => {
    const newItem = new Item();
    newItem .name = formValue.name;
    newItem .image = formValue.image;
    newItem .pitemText = formValue.itemText;
    addItem(newItem);
  };

So my question here is: how can I get that gallery component to re-render whenever I add a new item or delete one of the items? I figure I need a way to change the state of the component but I can’t seem to get it done.

Bootstrap modal does not show up after submit

Hello I’m trying to display a bootstrap modal after they select a withdrawal amount and click on submit button which also updates the withdraw row in the database, I tried echo the full bootstrap html but it still blinks and doesn’t stay as it is supposed to be

So far it only blinks and doesn’t stay at all.

<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>


<?php
// Include config file
require_once "config.php";
 
// Define variables and initialize with empty values
$withraw = "";
$withraw_err = "";
 
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
 
      // Validate Withrawal
    if(empty(trim($_POST["withraw"]))){
        $withraw_err = "Please Choose a Amount.";     
    } else{   
            $withraw = trim($_POST["withraw"]);
            }

    // Check input errors before inserting in database
    if(empty($withraw_err)){
        
        // Prepare an insert statement
        $sql = "UPDATE users SET withraw = (?) WHERE id = 211";

        if($stmt = mysqli_prepare($link, $sql)){
            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt, "s", $param_withraw);
            
            // Set parameters
           
            $param_withraw  = $withraw;
           
            
            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
               echo "<script>
         $(window).load(function(){
             $('#myModal').modal('show');
         });
    </script>";
            } else{
                echo "Something went wrong. Please try again later.";
            }

            // Close statement
            mysqli_stmt_close($stmt);
        }
    }
    
    // Close connection
    mysqli_close($link);
}
?>

       <label><h1 class="h1">withraw</h1></label>
        

        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
           
 
          
 


              <div class="form-group <?php echo (!empty($withraw_err)) ? 'has-error' : ''; ?>">
               

                <div class='selectt'><select name="withraw" class="form-control" value="<?php echo $withraw; ?>"><option >Choose Amount</option>
        <option value="500">500</option>
        <option value="1000">1,000</option>
        <option value="1500">1,500</option>
        <option value="2000">2,000</option>
        <option value="2500">2,500</option>
                <option value="3000">3,000</option>
        <option value="3500">3,500</option>

</select>
        
        </div>
                <span class="help-block"><?php echo $withraw_err; ?></span>
            </div>    
        
        

    

          <div class="form-group">
                <button type="submit" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal" value="Submit">
                    Withraw <i class='fa fa-check-circle'></i> </button>
                <button type="reset" class="btn btn-default" value="Reset"><i class='fas fa-redo'></i> Reset </button>
            </div>

        </form>
   
   

 <div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title"><img src="loading.svg" class="loaderr"> Pending Approval</h4>
      </div>
      <div class="modal-body">
        <p>Hello User, your request to withdraw has been sent to the Company.
        
        <br>
       <br>
       You will be notified when the withdrawal status has been updated.
      <br>
      <br>
      <font color="red">Note:</font> Do not resubmit a withdrawal request until the next 48hours
        </p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>

  </div>
</div>

</div>
    
 

Thank you so much, I’m sorry the code is bulky

How do i make the guesses go down by one in hangman

I have tried to make the guesses go down by one if the word they clicked on dont match the word. but every time i try to do it, it either makes the guesses go down one but then it will also go down when the word matches. and if i try changing the code the guesses will go down by how many words there are left. Like this one

function wordChecker(cell) {

    for (let i = 0; i < word.length; i++) {
        if (word[i] === cell.innerHTML) {

            answerArray[i] = cell.innerHTML
            answer.innerHTML = answerArray.join(" ")
            remainingLetters--
            checkWin()
            console.log(remainingLetters);
            console.log(answerArray);
            break;

        } else {
            guesses.innerHTML--
            console.log(guesses);
        }
    }

}

i thought it could be because of the for loop and even though i make an if outside of the for loop i doesnt work properly.