Enhanced dropdown menu with Vue.js

Trying to manage two select lists where their combined values equal a maximum size. For example, if the max number of people is 20 and 5 children are selected, only a maximum of 15 adults can be added, and so on.

My latest attempt:

Template:

<div class="form-row">
 <div class="col">
   <div class="form-group">
     <label for="adultNumber">Number of adults in your group:</label>
     <select class="form-control form-control-sm" v-model.lazy="adultNumber" v-on:change="updateChildPartySizes" id="adultNumberVal">
       <option v-for="n in maxAdultPartyArray">[[ n ]]</option>
     </select>
     Answer: [[ adultNumber ]]
   </div>
 </div>
 <div class="col">
   <div class="form-group">
     <label for="childNumber">Number of children in your group:</label>
     <select class="form-control form-control-sm" v-model.lazy="childNumber" v-on:change="updateAdultPartySizes" id="childNumberVal">
       <option v-for="n in maxChildPartyArray">[[ n ]]</option>
     </select>
     Answer: [[ childNumber ]]
   </div>
 </div>
</div>

Vue instance:

<script>
    let app = new Vue({
      el: '#app',
      data: {
        bookingDetails: true,
        yourDetails: false,
        sessionName: null,
        specialRequests: '',
        adultNumber: 0,
        childNumber: 0,
        maxAdultPartySize: 20,
        maxChildPartySize: 20,
        maxAdultPartyArray: Array.apply(null, {length: 20 + 1}).map(Number.call, Number),
        maxChildPartyArray: Array.apply(null, {length: 20 + 1}).map(Number.call, Number),
        sessionSize: {{ sessionSize }},
        csrfToken : '{{ csrf_token }}',
      },
      delimiters: ['[[', ']]'],
      methods: {
        updateChildPartySizes: function (adultNumber) {
          this.maxChildPartySize = this.maxChildPartyArray.length - adultNumber;
          this.maxChildPartyArray = Array.apply(null, {length: this.maxChildPartySize}).map(Number.call, Number);
        },
        updateAdultPartySizes: function (childNumber) {
          this.maxAdultPartySize = this.maxAdultPartyArray.length - childNumber;
          this.maxAdultPartyArray = Array.apply(null, {length: this.maxAdultPartySize}).map(Number.call, Number);
        },
      }
    });
</script>

I've attempted various methods, but nothing seems to provide the desired result. The math and array operations appear to be correct, but the final output is not as expected...

Can anyone offer assistance?

Answer №1

It's a common mistake to assume that the event handler called from onChange will receive the model value passed in. In reality, it gets an HTMLElement change event. Instead, it's better to use the model directly, which is automatically updated.

updateChildPartySizes: function () {
    this.maxChildPartySize = this.maxChildPartyArray.length - this.adultNumber;

I discovered this issue by initially trying:

console.log(this.maxChildPartySize); // NaN

Since NaN spreads like a plague, it indicated that one of the variables being added together was faulty. After logging them, I identified the root cause of the event.

Additionally, remember that models (v-model="something") are two-way bindings by default, binding :selected="foo" (one way) and v-on:change="foo" under the hood.

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

How come I am unable to activate the input file using prop?

Attempting to access a selection of files by passing a prop to a component for convenience. Is there a method to achieve this? https://codepen.io/iliyazelenko/pen/RBejRV?editors=1010 The code snippet below does not meet my requirements: <input type ...

Crafting a clever smart banner using jquery.smartbanner for Android Firefox users

In order to display smartbanners on my mobile website, I utilize jquery.smartbanner. This implementation has been successful for ios, windows phone, and the default android browser. However, when testing on Firefox for android, the smartbanner is not visib ...

Tips for creating a TypeScript-compatible redux state tree with static typing and immutability:

One remarkable feature of TypeScript + Redux is the ability to define a statically typed immutable state tree in the following manner: interface StateTree { readonly subState1: SubState1; readonly subState2: SubState2; ...

Issue with Telerik RadDatePicker when using ClientIDMode set to "Static"

var StartDate = $('#dtStartDate').val(); var EndDate = $('#dtEndDate').val(); alert(StartDate); alert(EndDate); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <table> <tr ...

Using NodeJs to pass values to a callback within a condition statement and retrieve the returned value

Within my routing file, I have implemented a condition where an external function is used to compare two values: obj.id === getId. Based on whether this condition evaluates to true or false, the view is rendered, or the user access is blocked. The functio ...

When I attempt to use document.execCommand("copy"), the line break does not get applied

I am currently using the following code to create a string and copy it. However, when I paste it as output, the line break is not being applied. function copyToClipboardShipto() { var $temp = $("<input>"); $("body").append($ ...

You are limited to using a maximum of two custom tags within a custom div

I came up with this code that is supposed to style the elements differently based on their tag names. However, when I tested it, the styling did not work as expected. For example, 'London' should be displayed as a large and bold h1 text, while th ...

How can we convert unpredictable-length JSON user input into well-structured HTML code?

Welcome to the world of web development! I am currently embarking on a project where I aim to transform JSON data into HTML structures. Specifically, I am working on creating a dynamic menu for a restaurant that can be easily updated using a JSON file. The ...

Utilize range slider to refine dataset

I have implemented a jquery datatable along with the range.slider plugin. My goal is to apply the range slider to filter out data in the last column. In my attempt, I am using search.push to accomplish this filtering process. Below is an example of my i ...

Is there a way to execute v-for once the created() lifecycle hook has finished running?

In my current project, I am faced with the challenge of including avatars in notifications. Despite my efforts, I have not been able to solve this issue independently. The Vue.js template below demonstrates how I have attempted to add avatars to each notif ...

The PHP script encountered an issue with the HTTP response code while processing the AJAX contact form, specifically

Struggling to make this contact form function properly, I've tried to follow the example provided at . Unfortunately, all my efforts lead to a fatal error: "Call to undefined function http_response_code() in /hermes/bosoraweb183/b1669/ipg.tenkakletcom ...

Unable to replicate the exact Bootstrap template found on their website

Attempting to replicate a template from bootstrap.com, but encountering issues with the copied version. The navigation bar is turning white instead of remaining black, and I'm unable to change the color. Additionally, facing problems with the toggle ...

"Utilizing Express's Jade middleware to efficiently handle and manage

Can you create a custom exception handler for errors in jade templates? For example: // server.js app = express(); app.set('view engine', jade); app.locals.js = function () { throw new Error('hello'); } // views/index.jade html != ...

The res.sendFile() function quickly delivers a 204 no content response

Currently, I am facing an issue with using Express' sendFile() function to send an image. The function does not seem to read my file at all and instead returns a 204 no-content response. Below is the code for my function/endpoint: @httpGet('/pri ...

Adapting the colors of various elements throughout the entire webpage

My goal is to incorporate color-switch buttons on my webpage. When these buttons are clicked, I want the existing colors to change to different shades. However, my challenge lies in the fact that these colors are used for various elements such as backgro ...

Why is there no type guard for Number.isFinite()?

Why doesn't Number.isFinite have a type guard like number is number? This example triggers an error Object is possibly 'undefined' function inc (n?: number) { return Number.isFinite(n) ? n + 1 : 1; } Check it out on the Playground: http ...

Converting JSON to Array: A Step-by-Step Guide

Greetings, StackOverflow community! This is my inaugural question here. I believe the answer is not overly complex, but my knowledge of Javascript is quite rudimentary. Currently, I have a JQuery AJAX function that processes this JSON object: { "Users" ...

String validation using regular expressions

Below is the code I am using to validate a string using regular expressions (RegEx): if(!this.validate(this.form.get('Id').value)) { this.showErrorStatus('Enter valid ID'); return; } validate(id) { var patt = new RegExp("^[a-zA- ...

How to modify values in a JSON array using JavaScript

Currently, I am facing an issue with displaying dates properly on the x-axis of a graph created using Highcharts. To solve this problem, I need to parse the dates from the JSON response. Despite my attempts to manipulate the JSON date, I have not been able ...

Would it be a security risk to share the Stripe charge ID and connected account ID with clients on the frontend?

I am currently making an ajax call to my backend and I am unsure whether it is secure to reveal the charge id and the connected account id on the client side. Just to clarify, there are no secret keys or sensitive information stored in the browser. Your ...