Updating SELECT options using CHECKBOX without the need to refresh the page

Here is a select element with various options:

<select name="kategory" class="select-field">
    <option disabled>ATRACTIONS
    <option value="">
    <option value="Castles">Castles
    <option value="History">History
</select>

Additionally, there is a check-box available:

Would you like to eat?<input type="checkbox" class="checkbox" name="restaurants" value="" />

Upon selecting the check-box, the select options need to be updated to the following without refreshing the page:

<option disabled>Restaurants
<option value="China food">Chinas food
<option value="Pizza">Pizza
<option value="Pub">Pub

How can this task be achieved?

Answer №1

Initially, markup both select boxes but hide one of them by default and then toggle its visibility.

$('input[name="preferences"]').change(function() {
  $('select[name="options"]').toggle();
  $('select[name="choices"]').toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

What do you prefer? <input type="checkbox" name="preferences" />

<select name="options">
<option value="beach">Beach</option>
<option value="mountain">Mountain</option>
</select>    

<select name="choices" style="display: none;">
<option value="italian">Italian</option>
<option value="mexican">Mexican</option>
<option value="indian">Indian</option>
</select>

Answer №2

Here is an alternative method that distinguishes the data from the selection (not necessarily superior, just a different approach).

//Converted into a function
function getOptions(category) {
    $('#Selection').empty().append($('#source optgroup[data-type='+category+']').clone());
}
//Retrieve initial data from Attractions
getOptions('Attractions');

$('input[name=food]').on('change', function() {
    if($(this).is(':checked')) {
        //Populate with data from Restaurants
        getOptions('Restaurants');
    } else {
        //Populate with data from Attractions
        getOptions('Attractions');
    }
})
#source {
    display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Are you hungry?<input type="checkbox" class="checkbox" name="food" value="" />

<select id='Selection'></select>

<select id='source'>
    <optgroup data-type='Attractions'>
        <option disabled>ATTRACTIONS</option>
        <option value="Zoos">Zoos</option>
        <option value="Museums">Museums</option>
    </optgroup>
    <optgroup data-type='Restaurants'>
        <option disabled>Restaurants</option>
        <option value="Italian cuisine">Italian Cuisine</option>
        <option value="Sushi">Sushi</option>
        <option value="Burger joint">Burger Joint</option>
    </optgroup>
</select>

Answer №3

Another way to achieve this effect is by combining CSS and a dash of Javascript.

<style>
  #option-toggle select { display: none; }
  #option-toggle.category select[name="category"] { display: block; }
  #option-toggle.food select[name="food"] { display: block; }
</style>

<div id="option-toggle" class="category">
  <select name="category">
    <option value="beach">Beaches</option>
    <option value="mountain">Mountains</option>
  </select>    

  <select name="activity">
    <option value="surfing">Surfing</option>
    <option value="hiking">Hiking</option>
    <option value="sightseeing">Sightseeing</option>
  </select>
<div>
Ready for an adventure?<input onclick="switchSelect()" type="checkbox" class="checkbox" name="explore" value="" />

<script>
  function switchSelect() {
    document.getElementById('option-toggle').setAttribute('class', 'food')
  }
</script>

This method utilizes CSS to hide the second select element, depending on whether the option-toggle div is assigned the CSS class of "category" or "food". The onclick() event of the checkbox will alter the CSS class of the option-toggle, revealing the hidden select box.

To see a live demonstration, check out this JSFiddle.

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

The sequential progression of individual functions relying on the output of the previous one in asynchronous execution

Understanding asynchronous code and callback functions has been a challenge for me. I am trying to create a sequence of functions that rely on the output of the previous one. The first function will fetch data from a database. import value > fctOne(Va ...

What is the most effective approach for managing exceptions at a global level in Node.js using Express 4?

Is there an Exception filter available in node.js with express 4, similar to the one in asp.net MVC? I have searched through various articles but haven't found a solution that meets my requirements. I also attempted the following in app.js: process ...

Change the content of a selectbox dynamically with the help of jQuery and AJAX

Currently, I am exploring the best approach for a specific challenge: I have various categories, subcategories, sub-subcategories, and so on, that I need to display in separate select boxes. For instance, initially, the options may look like this: <sel ...

Add an image to a div element and determine its height, then apply the height to the CSS property

Here is my JavaScript code that utilizes jQuery: $(".article_big_photo").click(function() { $('#screen').css({ opacity: 0.5, 'width':$(document).width(),'height':$(document).height()}); $('#screen').show() ...

Unlocking the secret to accessing state in a JavaScript file using VUEX

Can anyone help me figure out why I can't access the currentUser property from the state in my vuex store's user.js file? I'm trying to use it in auth.js, but when I write: store.state.currentUser.uid === ... This is the error message I&apo ...

What is the best way to determine which function to invoke in ngIf?

Depending on the value of a variable, I need to call either the login() or logout() methods from this.loggedInService.isLoggedIn. If the value of the variable is !this.loggedInService.isLoggedIn, then call login(). If !this.loggedInService.isLoggedIn is ...

What is the best way to enhance an error object in Express with additional information beyond just a simple message?

I need to enhance the error handling process in my express application by passing two pieces of information to the error handler, which will then send both pieces of information in a JSON format to the client. Currently, I am only able to include an error ...

Updating the HTTP request header in AngularJS without requiring a page refresh

I'm in the process of developing a website that utilizes ngRoute for page navigation. When a user logs in, a form will appear and upon successful login, the controller will modify the http header for subsequent requests. However, I am encountering an ...

A method for arranging an array of nested objects based on the objects' names

Recently, I received a complex object from an API: let curr = { "base_currency_code": "EUR", "base_currency_name": "Euro", "amount": "10.0000", "updated_date": "2024 ...

Encountering a "404 method not found" error in the developer console when handling meteor collections

Having an issue while trying to insert a document into my meteor collection using an autoform generated from my Mongo schema. Upon clicking the submit button, I am encountering a "method not found [404]" error in the developer console. I suspect the proble ...

I'm curious about why I'm receiving the error "Unable to bind to 'ngFor' since it is not recognized as a property of 'li'. Can someone please explain why this is happening?

The issue is related to the *ngFor directive for nonvegfoodlist app.component.ts import { Component } from '@angular/core'; export class Menu { id : number; name :string; } const veg : Menu[] = [ { id:1 , name:'Rice'}, { id: ...

When additional lines are drawn elsewhere on the HTML5 Canvas, the diagonal lines will gradually appear thicker and more pronounced

For horizontal and vertical lines, using a translation of 0.5 for odd stroke widths results in crisper and sharper lines. But what about diagonal lines? Link to jsfiddle <!DOCTYPE html> <html lang="en"> <body style="background: black"& ...

Using Props with jQuery in React Components: A Comprehensive Guide

I trust you comprehend this straightforward example. I attempted to modify the background color of my HTML element during initial rendering by managing it in a React Component with a touch of jQuery assistance. Here is the code within my React Component ...

Techniques for accessing the most recent input values within a loop

Here is the HTML code snippet: <div v-for="item in my_items"> <div> <input type="text" :value=item.name /> </div> <div> <button @click="edit(item.id, item.name)">Edit ...

Implementing additional states in an AngularJS app configuration with Ui-Router

Currently tackling a major application with numerous routes for its different components, my team and I have decided to break down the routes into separate files instead of cramming everything into one large file. In attempting to create a variable and im ...

How to implement a modal popup in Vue.js using an anchor tag

As a newcomer to Vue.js, I'm facing an issue with creating a link in my navbar component that, when clicked, displays a modal component. I've noticed that the solutions I found are for buttons which use the data target attribute, but this isn&apo ...

Is there a way to categorize data and sort it by using an action and reducer in redux?

I have developed a filtering system that allows users to filter data by different categories such as restaurants, bars, cafes, etc. Users can select whether a specific category should be displayed or not, and this information is then sent to the action and ...

What is the most effective way to output data using the response.write method in a Node.js program after retrieving it from a MySQL server?

Currently working on a NodeJS web app and encountering a roadblock. Seeking feedback on my code: var config = require('./config.json'); var mysql = require('mysql'); var http = require('http'); var url = require('url&apo ...

What techniques can I use to adjust the size of an image through zooming in and out?

In my custom gallery component, the crucial code section looks like this: <Gallery> <Header> <img src={galleryIcon} alt='Galley icon' /> <h1>My Gallery</h1> </Header> ...

Transform PHP array into a JavaScript array

Currently, I am using Laravel and retrieving a list of values from a database with the following code: $idordenes = DB::table('ordenes')->select('id')->get(); Upon echoing the idordenes variable, the output is as follows: [{"fa ...