Choose only one option from the dropdown menu at a time within the specified div

I attempted to utilize the "setSelected" option on my multiselect feature, but I noticed that it does not function with div elements (at least I could not make it work myself). I am endeavoring to create two synchronized multiselects using this example: but focusing only on the last two inputs.

var options = [


       { text: 'item1', value: 'item1'},
       { text: 'item2', value: 'item2'},

   ];


    var teste1 = null;
    var teste2 = null;
    let isTeste2 = true;
    var $testes = $('#teste1-id')
    if (isTeste2)
        $testes = $testes.add('#teste2-id')


    var install = function () {
        $testes.bsMultiSelect({
            options: options
        });
        if (isTeste2) {
            $('#teste1-id').on('dashboardcode.multiselect:change', function () {
                $('#teste2-id').bsMultiSelect("UpdateOptionsSelected");
            })
        }

    }
    install();
    
    $("#btn").click(
       function(){
          options[0].selected = true;
          var api1 = $testes.BsMultiSelect();
          api1.updateOptionSelected(0);    
       }
    )
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8fffe0ffffeafda1e5fccfbea1beb9a1bf">[email protected]</a>/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@dashboardcode/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfddccd2cad3cbd6ccdad3dadccbff8f9189918d87">[email protected]</a>/dist/js/BsMultiSelect.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">


<label class="control-label" for="teste1-id">Teste1</label>
    <div id="teste1-id"></div>

    <label class="control-label" for="teste2-id">Teste2:</label>
    <div id="teste2-id"></div>

<br/>
<button id="btn">Click Me</button>

Can you assist me in finding a solution, please?

Answer №1

When you only need to select "one item":

var options = [
       { text: 'item1', value: 'item1', selected: true},
       { text: 'item2', value: 'item2', selected: false},
];

function isValidSelection(v){
    var l = options.filter(function(item){
         return item.selected==true;
    }).length;
    var r = ( !v ) || (v && l==0);
    return r;
}

var teste1 = null;
var $teste1 = $('#teste1-id')

var install = function () {
   $teste1.bsMultiSelect({
       options: options,
       setSelected: function(o,v){
           if (isValidSelection(v)){
              o.selected = v;
              return true;
           }
           else{
              return false;
           }
       }
   });
}
install();
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e1918e91918493cf8b92a1d0cfd0d7cfd1">[email protected]</a>/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@dashboardcode/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2745544a524b534e54424b4244536717091109151f">[email protected]</a>/dist/js/BsMultiSelect.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">


<label class="control-label" for="teste1-id">Test it (only one selection allowed)</label>
    <div id="teste1-id"></div>
<br/>

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

Gulp- Ensuring the latest versions of your javascript files

I have implemented bundling and minification for my JavaScript files using gulp. What I am aiming to achieve is that whenever I make a change in any of my files and run gulp, a new bundled and minified file with a version number is generated. For example: ...

What is the best way to add animation to my `<div>` elements when my website is first loaded?

I am looking for a way to enhance the appearance of my <div> contents when my website loads. They should gradually appear one after the other as the website loads. Additionally, the background image should load slowly due to being filtered by the wea ...

Struggling to make npm and sqlite3 function properly on MacOS Catalina

Struggling with npm package installation in a project directory on my Mac has proven to be quite the challenge. Each attempt at a simple npm install results in perplexing errors that I can't seem to grasp. The hurdle seems to center around specific p ...

What is the best way to trigger an event using vue-chartjs?

I am using vue js to display a graph with chartjs. I have implemented an onClick function on the graph to emit an event in the parent component and retrieve data. However, the event is not working as expected. Can you help me identify the issue? Component ...

Expand the <div> by clicking on it, then hover away to return it to its normal size

One interesting feature I have on my website is a <div> that expands when clicked, and returns to normal size with another click. However, I am looking for something a bit different... What I want is for the <div> (with the class name .topHead ...

Unable to display image on HTML page in Sails JS

In my current project, I am utilizing Sails Js and Mongo DB for development. When a user uploads an image and content for a blog post, I store it in the images folder and save the file destination along with the content to MongoDB. My goal is to display bo ...

Puppeteer encounters difficulty when attempting to click on a particular div element within Gmail

I am attempting to click on the three dots in Gmail by following this link: 1 After that, I want to click on the 'mark all as read' option: 2 Clicking on the three dots works without any issues. However, I am encountering difficulty when tryin ...

What is the best way to access the methods in the "parent" class?

I am facing a situation where I have an object with fieldsCreators that hold creator methods for each field. The dilemma is how to call the creator method inside fieldsCreators as shown below: var obj={ creator:function(ch) { .... .. ...

Managing toggles for save and edit buttons in Vue - a comprehensive guide

I am currently working on a Vue 'app' within a larger Django application as a means to enhance my understanding of Vue. My objective is to create unique forms that can be edited independently. I have been experimenting with this for some time n ...

Send backspace key press event to the applet and prevent it from continuing

I am struggling with a Java applet on my webpage that allows users to edit text. Whenever a user tries to modify the text by pressing the backspace button, the browser mistakenly forwards to the previous page. I attempted to filter out the backspace key pr ...

How to access v-for dynamically generated elements beyond the loop

How can I access a dynamically created item outside of a v-for loop in Vue.js? <li v-for="item in cart.items"> <h1>{{ item.product.name }}</h1> </li> <p>Is it possible to access {{ item.product.name }} out ...

Maintain the aspect ratio of an image when placing it in a square container

Looking for a way to create a CSS grid with non-square random sized images? I need help filling all the space inside a fixed size div. Any suggestions? Check out my example: (blue represents the fixed size div and red shows the image inside it) ...

What are the recommended methods for updating data using mongoose?

There are two methods for updating data with mongoose. Using model methods, such as User.updateOne({username}, {$set: {age}}) Finding the document, making changes to its properties, and saving it. Like this: const user = await User.findById(userId) user. ...

Combining Javascript and Django for a powerful web development solution

Having trouble setting up JS on my Django web app, despite reading through the documentation and previous queries. Using the Django dev server with the following file structure: mysite/ __init__.py MySiteDB manage.py settings.py ...

Learn the step-by-step guide on integrating Angular 2 into Codeigniter 3

Currently, I am using Codeigniter 3x and have been using and learning it for a month. Now, I want to start learning a JavaScript framework like Angular, but I'm not sure how to install or use Angular in Codeigniter. Can anyone guide me on this? Is it ...

The system is unable to locate the command "nvm"

Lately, I've been experimenting with using nvm to manage different versions of node. After successfully installing nvm on my Mac OS Catalina(10.15.6), I was able to easily switch between versions through the terminal. However, when attempting to do t ...

Tips for utilizing 'toHaveClass' to find a partial match in Jest?

When I assign the class success to an element, React-Mui appends additional text to it in the DOM, such as mui-AbcXYZ-success. This causes my test using the code snippet below to fail: expect( getByTestId('thirdCheck')).toHaveClass("success ...

Inability to successfully upload batch data within specified criteria using a keyword and conditional statement

My goal is to batch the data, using "Repair" as a separator for the data. Splitting criteria = Repair Copper limit = 2.5 [ {"engineSN":"20","timeRun":"30","Cu":"2"}, {"engineSN": ...

Can anyone tell me where to locate the AndroidManifest.xml file within a React Native Expo project?

How can I locate the AndroidManifest.xml file in a React Native Expo project to request permissions? Are there alternative methods for asking users for permission? ...

Difficulty encountered in assigning a value to a variable when utilizing an async function in Node.js

While attempting to retrieve the jwtauthtoken from the user and passing it to a function called getUserId() in the imported JavaScript file, I encountered an issue where the returned value was undefined instead of the decoded ID. The getUserId() function ...