Opening a modal in Bootstrap 4 selectpicker depending on the chosen value

I am facing an issue with a selectpicker that has live search functionality. I want to trigger a modal to open only when the user clicks on the option that says "Add new contractor." However, this modal is currently opening for all options, even though I only want it to open for the one with the value "addnewcon." I'm having trouble identifying what's wrong with the code.

Since the default selectpicker isn't working correctly in BS4, I've opted to use a different one. Please note that the search function isn't functioning in my JSFiddle link due to it referencing a different JS file.

Flexible Bootstrap 4 Dropdown

Here's a link to my JSFiddle for reference:

JSfiddle

Below is the code for the selectpicker:

<head>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>

<body>
  <div class="panel-body">
    <div class="col-md-12 col-md-offset-1">
      <div class="row">
        <div class="help-block with-errors"></div>
        <div class="col-md-3">
          <div class="form-group">
            <label for="form_contractor">Select Contractor *</label>
            <select class="selectpicker form-control" data-live-search="true" id="contractor" name="contractor" required="required" data-error="Contractor is required.">
                            <option value="">Please select contractor</option>
<option value="addnewcon">Add new Contractor</option>
                            <?php  foreach ($all_contractors as $con): ?>
                              <option value="<?php echo $con['ID'] ?>">
                                <?php echo $con['Name'] ?>
                              </option>
                             <?php endforeach; ?>
                    </select>
          </div>
        </div>

        <!-- Modal -->
        <div id="addnewcon" class="modal fade" tabindex="-1" role="dialog">
          <div class="modal-dialog" role="document">
            <div class="modal-content">
              <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">Modal title</h4>
              </div>
              <div class="modal-body">
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Exercitationem omnis aliquid voluptatibus, distinctio soluta eligendi officiis voluptatem necessitatibus magnam illum.</p>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save</button>
              </div>
            </div>
          </div>
        </div>
        
        (Remaining HTML code omitted for brevity)
      </div>
    </div>
  </div>
  <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>

  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
  <script src="js/bootstrap-select.js"></script>
</body>

Below is my JavaScript code to trigger the modal:

 $("#contractor").change(function() {
  if ($(this).val() === 'addnewcon') {
    $('#addnewcon').modal('show');
  }
});

Answer №1

After some investigation, I managed to come up with my own solution. I suspected that the issue might be related to the JS, so I devised the following code snippet that successfully resolved the problem:

// Implementing the functionality to add new contractors
$("#contractor").change(function () {
  if ($(this).val() === 'addnewcon') {
    $('#addnewconmodal').modal({show: true});
  } else if ($(this).val() !== 'addnewcon') {
    $('#addnewconmodal').modal({show: false});
  }
});

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

Tips for discovering the exact positions of child divs that are Nth siblings within a parent div

I have designed a new calendar interface with dynamic functionality. When the user clicks on any time slot displayed in IMAGE1, a span element is created dynamically to represent 8 hours starting from that clicked time. My question is, how can I access th ...

A customizable and adaptable Tetris-inspired CSS design perfect for any screen size

If we imagine having a block like this: <div class="block"></div> There are different sizes of the block: <div class="block b1x1"></div> <div class="block b2x1"></div> <div class="block b1x2"></div> For i ...

Element enclosed within a territory of mongoose Schema

In the midst of developing an API that provides detailed information about laptops, I am utilizing Node.js and MongoDB with Mongoose. The schema I am working with is as follows: const productSchema = mongoose.Schema( { name: { type: String, ...

Combine an array of objects using the main key in each object

I have an array of objects with different years and details var worksSummaryDetailsArr = [ { year: 2020, worksSummaryDetailsObj: [ [Object], [Object], [Object], [Object] ] }, { year: 2021, worksSummaryDetailsObj: [ [Object], [Object], ...

The react component is not defined within the <Popup></Popup> tag

SOLVED: Big thanks to everyone who offered their assistance. Upon further investigation, I discovered that in the library I was using, the trigger={} functionality is specifically designed to work only with a button element. To address this issue, I took ...

The width of the HTML page seems to adjust or shift when I click on

I'm encountering an issue with my navbar. Whenever I open the dropdown menu, the width of my page changes but returns to normal when it is closed. <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="styl ...

The jQuery mobile Multiselect feature is not correctly updating the selected attribute

In my jQuery mobile custom multiselect, when I choose an item, the list of items in the HTML select tag does not update with the selected attribute. Check out the Multiple selects example on the page: <div data-role="fieldcontain" class="ui-field- ...

Magical Stylist - Eradicate Indicators while Preserving Labeling

Recently, I've been experimenting with the Google styling wizard in an effort to remove markers while retaining labels for businesses. My objective is to eliminate the marker icons but still display the text labels such as "Jimmy Johns," "Boone Saloon ...

Cause a bootstrap column to have overflowing content rather than expanding

I've searched extensively for the solution to my problem, but haven't found a satisfactory answer yet. My goal is to create a location finder with a map on the right and a list on the left. With over 18,000 locations to search through, the list ...

Error encountered while using Google Translate with XMLHttpRequest (Missing 'Access-Control-Allow-Origin' header)

Trying to access a page that utilizes Google Translate is resulting in the following error: XMLHttpRequest cannot load http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit. No 'Access-Control-Allow-Origin' heade ...

Creating Sliding Panels: A Step-by-Step Guide

I am new to JavaScript and jQuery, and I am looking to create a panel system similar to Spotify's design. Here is a description of what I am trying to achieve: When a user clicks on an artist or song/album on Spotify, a panel slides in from the righ ...

The onPlayerReady function in the YouTube API seems to be experiencing a delay and

After following a tutorial on integrating the YouTube API into my website, I encountered difficulties trying to play a YouTube video in fullscreen mode when a button is pressed. Despite following the provided code closely, I am unable to get it to work as ...

What is the best way to have a form open upwards when hovered over or clicked on?

Attempting to create a button in the bottom right corner that will reveal a form when clicked or hovered over. The form should slide open slowly and close after clicking on login, but currently the button is moving down as the form opens. The button also ...

Accessing form data using Vue on submit

I'm working on a project that involves creating a form with a single input field and saving the data to a database. The technology I am using is Vue.js. Here is the template I have designed: <form class="form-horizontal" @submit.prevent="submitBi ...

An error has occurred in the Shadow Dom due to the inability to access the property 'style' of an

While working on a component using shadow DOM, I encountered the following error in the console: "Cannot read property 'style' of undefined". This issue seems to be related to my HTML code in PHP. The main challenge I am facing is figuring out ho ...

`Is there a way to sort a deeply nested object by its values?`

I need assistance sorting an array of hospitals based on the lowest value of the amountinINR key, especially when dealing with deeply nested arrays of hospital objects. Does anyone know how to achieve this without using third-party libraries like lodash or ...

Using Google Maps to Cluster Markers on Your Website

I need to display numerous markers on a map for my website. My inquiry is whether the google maps api for javascript still supports clustering for websites? I attempted using marker cluster and it seems like it's not functioning properly. If so, can ...

Enhancing Animation Speed with jQuery

I've provided the code snippet at this link: http://jsfiddle.net/LnWRL/4/: Here is the HTML: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script> <div id="wrap_demo"> <div id="demo"></di ...

Dilemma: Navigating the Conflict Between Context API and Next.js Routing in React

Recently, I was following a Material UI tutorial on Udemy and decided to set up a Context API in Create React App without passing down props as shown in the tutorial. Later on, when I tried migrating to Next JS with the same Context API, I started encounte ...