Using Javascript to Trigger Events on Selection

I have a unique situation:

1) One of my dropdown's choices features various car names.

2) Another dropdown has two options:

When selecting each option in the second dropdown, the following should occur:

a) Choose UserInput - This action will hide the left multiselect box and display a text box in the same location. Users can input any car name into the textbox and use the buttons to move it to the right-hand side select box. The right-to-left button should be disabled in this scenario.

b) Opt for AutoPopulate - In this case, a multiselect box should appear on the left side where the textbox was located. The textbox will disappear and the multiselect box will populate with the cars available in the first dropdown. Users can freely select and transfer cars between the two boxes.

I am just starting to learn Javascript and would appreciate some assistance with this task.

JSFiddle

$(function(){
    $("#button1").click(function(){
        $("#list1 > option:selected").each(function(){
            $(this).remove().appendTo("#list2");
        });
    });
    
    $("#button2").click(function(){
        $("#list2 > option:selected").each(function(){
            $(this).remove().appendTo("#list1");
        });
    });
});
 .bloc { display:inline-block; vertical-align:top; overflow:hidden; border:solid grey 1px; width:100px;}
 .bloc select { padding:10px; margin:-5px -20px -5px -5px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
DropDown1:
<select id="DropDown1" name="DropDown1">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>
<br><br>
DropDown2:
<select id="DropDown2" name="DropDown2">
  <option value="">-- Select --</option>
  <option value="oneUsrInput">User Input</option>
  <option value="twoAutoPopulate">Auto Populate</option>
</select>
<br><br>
<input type="text" id="TextBoxId" name="TextBoxId">
<div class="bloc">     
    <select id="list1" multiple="multiple" rows=2>
        <option value=1>Option 1</option>
        <option value=2>Option 2</option>
        <option value=3>Option 3</option>
        <option value=4>Option 4</option>
        <option value=5>Option 5</option>
        <option value=6>Option 6</option>
    </select>
   </div>
 <div style="display:inline-block;">
    <input id="button1" type="button" value=">>" />
    <br/>
    <input id="button2" type="button" value="<<" />
 </div>
<div class="bloc">
    <select id="list2" multiple="multiple" rows=2>        
    </select>   
</div>

Answer №1

Here is a more precise version of the code:

$(function() {
  var value = 100;
  $("#button1").click(function() {
    if ($("#DropDown2").val() == "oneUsrInput") {
      console.log();
      $("<option value=" + (value++) + ">" + $("#TextBoxId").val() + "</option>").appendTo("#list2");
    } else if ($("#DropDown2").val() == "twoAutoPopulate") {
      $("#list1 > option:selected").each(function() {
        $(this).remove().appendTo("#list2");
      });
    }
  });

  $("#button2").click(function() {
    $("#list2 > option:selected").each(function() {
      $(this).remove().appendTo("#list1");
    });
  });
  $("#DropDown2").on('change', function() {
    if ($("#DropDown2").val() == "oneUsrInput") {
      $("#TextBoxId").show();
      $("#list1").parent().hide();
    } else if ($("#DropDown2").val() == "twoAutoPopulate") {
      $("#TextBoxId").hide();
      $("#list1").parent().show();
    }
  })
});

Do you require further assistance, or are you ready to proceed?

JSFIDDLE

Answer №2

If you're looking for a solution to add text to a list without duplicates, check out this snippet:

$(function(){
    $("#button1").click(function(){
        if ($('#DropDown2').val() === 'oneUsrInput') {
            var txt = $('#TextBoxId').val();
            $('#TextBoxId').val('');
            // Add text only when not already existing in the list:
            if (!$('#list2').val(txt).val()) {
                $('<option/>').text(txt).val(txt).appendTo('#list2');
            }
        } else {
            $("#list1 > option:selected").each(function(){
                $(this).remove().appendTo("#list2");
            });
        }
    });
    
    $("#button2").click(function(){
        $("#list2 > option:selected").each(function(){
            $(this).remove().appendTo("#list1");
        });
    });
    
    $("#DropDown2").change(function() {
        var isUserInput = $(this).val() === 'oneUsrInput';
        $('#TextBoxId').toggle(isUserInput);
        $('#list1,#button2').toggle(!isUserInput);
    });
    
    // At startup, populate multi-select list    
    $("#list1").html($("#DropDown1").html()); 
    // At startup, set visibility right:
    $("#DropDown2").change();
});
.bloc { display:inline-block; vertical-align:top; overflow:hidden; 
        border:solid grey 1px; width:100px;}
.bloc select { padding:10px; margin:-5px -20px -5px -5px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
DropDown1:
<select id="DropDown1" name="DropDown1">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
</select>
<br><br>DropDown2:
<select id="DropDown2" name="DropDown2">
    <option value="">-- Select --</option>
    <option value="oneUsrInput">User Input</option>
    <option value="twoAutoPopulate">Auto Populate</option>
</select>
<br><br>
<div class="bloc">     
    <input type="text" id="TextBoxId" style="display:none" name="TextBoxId">
    <select id="list1" multiple="multiple" rows=2>
    </select>
</div>
<div style="display:inline-block;">
    <input id="button1" type="button" value=">>" />
    <br/>
    <input id="button2" type="button" value="<<" />
</div>
<div class="bloc">
    <select id="list2" multiple="multiple" rows=2></select>   
</div>

Answer №3

Your code has been modified for better performance:

$(function(){
    $("#button1").click(function(){
            if($('.userArea').hasClass('twoAutoPopulate')){
            $("#list1 > option:selected").each(function(){
                $(this).remove().appendTo("#list2");
                console.log($(this));
            });
        }
        else if($('.userArea').hasClass('oneUsrInput')){
            $('#list2').append($('<option>', { 
                value: $('#TextBoxId').val(),
                text : $('#TextBoxId').val() 
            }));
            $('#TextBoxId').val('')
        }
    });

    $("#button2").click(function(){
            if($('.userArea').hasClass('twoAutoPopulate')){
            $("#list2 > option:selected").each(function(){
                $(this).remove().appendTo("#list1");
            });
        }
    });
});

$("#DropDown2").on('change', function() {
    $('.userArea').fadeIn(300);
    if($("#DropDown2").val() == "oneUsrInput") {
    $('.userArea').addClass('oneUsrInput').removeClass('twoAutoPopulate');
  }
  else if($("#DropDown2").val() == "twoAutoPopulate") {
    $('.userArea').addClass('twoAutoPopulate').removeClass('oneUsrInput');
  }
});

For a demo of the changes made in your code, visit this link: https://jsfiddle.net/IA7medd/e6v3zvzn/

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

Fix Type error in jQuery when sending JSON data

An error message is appearing in the console log stating TypeError: 'append' called on an object that does not implement interface FormData. and seems to be related to the line of code $.ajax({ in the provided script. The meaning of this error i ...

Leveraging Handlebars for templating in Node.js to incorporate a customized layout

app.js const exphbs = require('express-handlebars'); app.engine('handlebars', exphbs({defaultLayout: 'layout'})); app.set('view engine', 'handlebars'); app.use('/catalog', require('./routes/ ...

Strategies for ensuring a promise is fulfilled before moving on to the next iteration in a never-ending for loop in JavaScript

I've been exploring ways to ensure that a promise is resolved before moving on to the next iteration in a for loop. One suggestion was to use the setInterval() function instead of a for loop, but this isn't ideal since it's hard to predict w ...

Place centered items within a flexbox that uses space-between alignment

When designing a navigation section, I am looking to achieve space-between justification. However, for smaller screens where the navigation items may need to wrap onto multiple rows, I want the items to center themselves instead of aligning to the left whe ...

What is the reason for Javascript XMLHttpRequest returning the octet-stream MIME type response as a string instead of binary

My attempt to retrieve a gltf binary file using the XMLHttpRequest method was unsuccessful. Below is the code I used. var xhr = new XMLHttpRequest(); xhr.open("GET","THE ADDRESS",true); xhr.setRequestHeader("Accept", "application/octet-stream"); xhr.respo ...

Simple method for implementing a fade effect on a React component with raw JavaScript techniques?

I am seeking a way to have my React component smoothly fade in upon being mounted. The component's outermost DIV starts with inline style display:none. Within the componentDidMount() method, I've written the following code: let el = document.que ...

Wordpress team exhibition

Does anyone know how to create a Team showcase slider in Wordpress? I have been using slick slider, but I'm looking for a way to add team members easily through a plugin rather than manually. I found an image of what I want it to look like. Can any ...

The output stored in the variable is not appearing as expected

https://i.sstatic.net/VWCnC.pnghttps://i.sstatic.net/UoerX.pnghttps://i.sstatic.net/n52Oy.png When retrieving an API response and saving it in the "clima" variable, it appears as undefined. However, when using console log, the response.data is visible ...

Using an element with the href property in conjunction with react-router: a comprehensive guide

My goal is to implement the navigation.push(url) functionality upon clicking an anchor tag element in order to prevent the app from refreshing when navigating to a new page, thus allowing me to maintain the application state. The decision to use this on a ...

The scrollTop feature fails to function properly following an Axios response

I'm currently facing a challenge with creating a real-time chat feature using Laravel, Vue.js, Pusher, and Echo. The issue arises while implementing the following 3 methods: created() { this.fetchMessages(); this.group = $('#group') ...

If the next element in the sequence happens to be the final element, then conceal a separate

Continue pressing the downward button consistently on until you reach the bottom. The down arrow should disappear slightly before reaching the end. Is there a way to achieve this using the code provided below? I'm new at this, but I believe I need t ...

Is your dropdown menu malfunctioning with jQuery? (Chromium)

I am currently working on a website that requires the options in the second dropdown menu to change based on the selection made in the first dropdown menu. However, despite the fact that the browser is recognizing the javascript file, it doesn't seem ...

Enzyme examination: Error - anticipate(...).find was not recognized as a function

What is the reason for .find not being recognized as a function in the code snippet below? import React from 'react'; import { shallow } from 'enzyme'; import toJson from 'enzyme-to-json'; import { AuthorizedRoutesJest } from ...

Issues arise when attempting to integrate jQuery with Recaptcha

I am currently working with Rails 3.1 and attempting to configure Recaptcha in a way that it only appears after I have clicked the 'Submit' button on my form. The Jquery code below is used to hide Recaptcha until the Submit button is clicked, ho ...

Is it possible to apply capitalization or convert the value of props to uppercase in React?

Despite attempting the toUpperCase method, I am unable to capitalize my props value. Here's the code I have: export default function Navbar(props) { return ( <> <div> <nav class="navbar navbar-expand-lg bg-b ...

Using jQuery to present JSON data on a website

I am currently working on a project that involves outputting the company name and number for each company. Once I have this data, I plan to display it in a list within my div element. My knowledge of jquery, Ajax, and Json is limited, so I'm feeling a ...

Display user profile pictures from Vue.js in the Laravel public directory

I have been working on implementing a commenting system and recently incorporated vue.js into my laravel project. One of the features I want to include in my comment area is displaying user profile images from the laravel public folder. However, I am u ...

What is the best way to conceal the jqgrid entirely while it is still loading?

Having an issue with my jqgrid. As I load the table and fetch a large amount of data from the database, the loading process naturally takes a few seconds. However, during this time, I can see the column headers without any rows or styles applied to the jqg ...

Embed script tags into static HTML files served by a Node.js server

Looking to set up a Node server where users can request multiple pages from a static folder, and have the server inject a custom tag before serving them. Has anyone had success doing this? I've tried with http-proxy without success - not sure if a pro ...

I am encountering difficulties in accessing my component's property within the corresponding template while working with Angular 5

When I call an HTTP POST method to retrieve table names from the backend, I attempt to display them in the template using ngFor. However, the table names are not appearing on the screen. The tNames property is inaccessible in the template. As a beginner i ...