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

How to fix the issue of the mobile Chrome bar occupying part of the screen height in CSS

I am encountering a well-known issue with my collapsible scrollable bar implemented in Bootstrap. The problem occurs when scrolling on mobile devices, as the search bar takes up space from the sidebar's 100% height, causing the scrollbar to not reach ...

Creating nested directories in Node.js

I am attempting to accomplish the following task Create a function (in any programming language) that takes one parameter (depth) to generate folders and files as described below: At depth 0, create a folder named 0, and inside it, create a file with its ...

What steps can I take to ensure that an image does not exceed the size of its parent tag?

Is there a way to ensure that items placed in a container do not exceed the boundaries of the container? I am trying to use my logo as the home button, but when I set the image height and width to 100%, it becomes larger than the nav bar. The CSS for the n ...

Is it advisable to Utilize ES6 Classes in Javascript for Managing React State?

Is it recommended to use ES6 classes directly as React state? I am interested in creating an ES6 class that: Contains member variables that will trigger re-renders on the frontend when changed. Includes methods that sync these member variables with the ...

Cross-domain scripting

I have a unique javascript code hosted on my server. I want to offer website visitors a similar implementation approach to Google Analytics where they can easily embed the script on their servers. For instance: <script type="text/javascript" src="http: ...

Retrieve the total number of clicks and initiate a single AJAX request using jQuery

When a user continuously clicks a link, I need to call an ajax service. Currently, my code only works for a single click - the ajax call is made and functions correctly, but if the user clicks multiple times, only the first click is registered. I want to k ...

What is the best way to incorporate tooltips in SVG?

My teacher wants me to display a tooltip on an SVG circle with links and information when we hover over it. They suggested using jQuery UI, but I've done extensive research and nothing has been able to assist me so far. ...

The web server experiences a layout and functionality breakdown caused by an issue with the config.js file following the uploading process

I recently created a website. However, when I uploaded it to my hosting company's server and tested it on different browsers, the layout appeared broken. Some of the CSS files loaded properly, but certain elements and styles were not in their correct ...

jQuery divs seem to "gaze up" towards the mouse pointer

I am attempting to recreate a fascinating effect using jQuery - where "cards" move in response to the mouse cursor as if they are looking up at it. I have come across a script that almost achieves what I need, but I require the ability to control the mov ...

"Can you guide me on how to display a React component in a

I have a function that loops through some promises and updates the state like this: }).then((future_data) => { this.setState({future_data: future_data}); console.log(this.state.future_data, 'tsf'); }); This outputs an array o ...

Encountering an issue while attempting to retrieve information from Vuex store

I recently encountered an issue while trying to store my water data in Vuex. I followed the implementation below, but when I attempted to access my data array, it did not show up as expected. const store = new Vuex.Store({ state: { categories: ...

Find the variance between the initial time and the present time, as well as the final time and the current time

If a user logs in before the start time of a game, they will receive a message indicating that the game will start in 01h:10m:23s. If the user logs in after the start time but before the end time, they will see a message stating that the game closes in 0 ...

Is real-time updating possible with data binding in Polymer and JavaScript?

I have a scenario where I am working with two pages: my-view1 and my-view2. On my-view1, there are two buttons that manipulate data stored in LocalStorage. On my-view2, there are two simple div elements that display the total value and the total value in t ...

Disregarding boundaries set by divisions

Trying to keep things concise here. I have a division called "the box" with a fixed width of 1200px that contains various other divisions. One of these divisions is a links bar, known as the "pink bar", which has a width of 100% and a height of 25px. My is ...

Modify a single field in user information using MySQL and NodeJS

I am currently working on developing a traditional CRUD (create, read, update, delete) API using NodeJS/Express and MySQL. One of the routes I have created is responsible for updating user information, which is functioning correctly. The issue: When I d ...

"Creating Rounded Corners in HTML: A Step-by-Step Guide

Is there a way to round the corners of this image? Below is an excerpt from my body... <body> <h1 style="float:left; width:37%;"><font color="#99CC00"><font face="Verdana">MrEpicGaming4U</font></h1> <div style= ...

Guide to updating Django model-based form records with choices option using an HTML form

I have a pre-existing model called ShiftChange that I am trying to update. In the model-based form, I have used CHOICES as follows: from django.db import models ====== ============= ) class ShiftChange(models.Model): ...

Internet Explorer is failing to show the results of an ajax call retrieved from the

Need help with this code block: $(document).ready(function() { dataToLoad = 'showresults=true'; $.ajax({ type: 'post', url: 'submit.php', da ...

Toggle visibility of div based on current business hours, incorporating UTC time

UPDATE I have included a working JSFiddle link, although it appears to not be functioning correctly. https://jsfiddle.net/bill9000/yadk6sja/2/ original question: The code I currently have is designed to show/hide a div based on business hours. Is there a ...

Exploring file writing using Node Webkit and JavaScript

When developing my app, I encountered an issue with the 'fs' module not functioning as expected. Despite the code being written to write a file, nothing happens when the app is launched. However, if I start the app using the following command: $ ...