What is the most effective way to populate an element using jQuery?

When you click a button with jQuery, I am generating a modal (Bootstrap modal) as a string. This modal has two option classes: Call Today and Call Tomorrow, which seems fine so far.

Upon clicking the button, the modal is created, prompting me to add two attributes to the button: data-open-hours and data-closed-hours. To illustrate what I intend to do, here's an example:

For instance:

My data-open-hours is : 09:00 And my data-closed-hours is : 22:00

Then, populate my .when-call select from 09:00 to 22:00 with the option Call Now.

If you choose Call Tomorrow, then populate the select from 09:00 to 22:00 without including the string Call Now.

Check out my working example below:

// JavaScript function to create agency modal
function agencyModal(modalTitle, modalWidth, modalHeight, openHours, closedHours) {
  console.log("Open: " + openHours + ", Closed hours: " + closedHours);
  var html =
    '<div class="modal fade agencyModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"><div class="modal-dialog" role="document" style="width:' + modalWidth + ';height:' + modalHeight + '"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>';
  html = html + '<h4 class="modal-title" id="myModalLabel">' + modalTitle + "</h4></div>";
  html = html + '<div class="modal-body">';
  html = html + '<div class="row"><div class="col-lg-6"><select class="when-call form-control"><option class="call-today">Call Today</option><option class="call-tomorrow">Call Tomorrow</option></select></div><div class="col-lg-6"><select class="form-control"><option class="call-now">Call Now</option></select></div></div>';
  html = html + '</div></div></div></div>';
  
  // Append HTML if not added before
  !$(".agencyModal").length && $(document.body).append(html);
  $(".agencyModal").modal();
}

// Event listener for opening agency modal on button click
$(document).on("click", ".open-agency", function() {
  var openHours = $(this).data("open-hours");
  var closedHours = $(this).data("closed-hours");
  agencyModal("Test Title ", "70%", "500px", openHours, closedHours);
});
// CSS styling for the open-agency button
.open-agency {
  border: 3px solid #ccc;
  display: inline-block;
  padding: 12px;
  font-size: 14px;
  margin: 100px;
  cursor: pointer;
  box-shadow: 0px 0px 10px #ccc;
}

.open-agency:hover {
  background: #050505;
  color: #fff;
  border-color: #000;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<p class="open-agency" data-toggle="modal" data-target=".agencyModal" data-open-hours="09:00" data-closed-hours="22:00">See Agency</p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>

Check out the CodePen Demo

Answer №1

Upon inspection of the code, several issues have been identified. These include a lack of name in the select element, no values for the option elements, and improperly using classes instead of IDs. It is recommended to address these concerns.

For the current setup, if the goal is to populate the second select with options representing each hour between opening and closing times, you should: - Populate the second select based on the specified open/close hours; - Implement a listener for the first select that dynamically adds or removes the "Call now" option based on user selection.

This approach should work, albeit requiring refinement.

function agencyModal(modalTitle, modalWidth, modalHeight, openHours, closedHours) {
  // Implementation omitted for brevity
}

$(document).on("click", ".open-agency", function() {
  var openHours = $(this).data("open-hours");
  var closedHours = $(this).data("closed-hours");
  agencyModal("Test Title ", "70%", "500px", openHours, closedHours);
});

function callNow() {
  return '<option class="call-now">Call Now</option>';
}

// Function getOptions implementation omitted

$(document).on("change", ".when-call", function(event) {
  // Logic to handle 'Call now' functionality
});
.open-agency {
  // CSS styling rules
}

.open-agency:hover {
  // Hover effect styling
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<p class="open-agency" data-toggle="modal" data-target=".agencyModal" data-open-hours="09:00" data-closed-hours="22:00">See Agency</p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>

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

What is the process for invoking a websocket from an HTML client?

I have created a WCF Service using netHttpBinding binding and it is hosted on IIS 8 (Windows Server 2012). The interfaces for the service are as follows: [ServiceContract(CallbackContract = typeof(IDuplexCallbackContract))] public interface IHelloWebSocke ...

What is the best way to empty textfields following an ajax query in jquery?

Here's the jQuery function I'm using to perform an AJAX query: $("#add").click(function() { val1 = $('#add_lang_level').val(); val = $('#add_lang').val(); listitem_html = '<li>'; listitem_html ...

Transfer external variables into the image's onload function

I am trying to retrieve image dimensions and then execute additional actions. Since the image onload function is asynchronous, I have decided to handle everything within the onload call. This is my current approach: function getMeta(url, callback) { v ...

Creating a rectangular pyramid using three.js r68: a step-by-step guide

Currently working on r68, I'm in search of a modern example showcasing the creation of a rectangular pyramid that will allow me to implement THREE.MeshFaceMaterial(). Many existing examples are outdated and lead to errors with my current setup. My re ...

Exploring the potential of Python loops within Selenium capabilities

My latest project involves scraping data from a search page. Specifically, I need to extract the title, price, and link for each of the 25 results on the page. To achieve this, I'm working with Xpath and utilizing an incremental div number associated ...

Discovering the offset location using touchmove

Struggling with a code for dragging/moving an element via touchscreen. The code is functional, but encounters a common issue - unable to drag from the touchpoint itself. Every movement initiates from the edge of the element, no matter where the touch begin ...

Is it possible to create distinct overlapping divs without using absolute positioning?

I'm seeking assistance in developing the view shown below. I am familiar with using position absolute, but I'm wondering if there is a way to achieve this without relying on absolute values. ...

Load the values into the dropdown list based on the selection from the previous dropdown menu

Currently, I am working on implementing cloning functionality for select boxes. There are 3 select boxes: country, state, city. The user selects the country first which then populates the state select box based on the ID, and similarly, the city dropdown ...

What is the best method for transforming an HTML file into an ICS (iCal) file?

Hello there! I am interested in converting an HTML file (website) to an iCalendar file (iCal). Is this even possible? If so, how can it be achieved? Does anyone have any ideas or recommendations on how to proceed? Thank you in advance! ...

Loop through the ng-content elements and enclose each one within its own individual nested div

Although it is currently not supported, I am curious to know if anyone has discovered a clever solution to this problem. In my current setup, I have a parent component with the following template: <dxi-item location='after' class="osii-item- ...

Create dynamic combo boxes using jQuery

My goal is to display a text field on the page if a user has only one credit card number in the database. However, if the user has multiple credit card numbers stored, I want to display all of them in a combo box. Below is the ajax response that I am rece ...

Introduction to Flask with GAE (blank Firefox tab)

Recently, I completed the Getting Started with Flask on App Engine Standard Environment tutorial. If you are interested, you can find the source code here. During my testing using Firefox and Chrome, I noticed that both browsers did not render the HTML te ...

Items in a CSS masonry container with a 'column count' feature showcasing drop shadows that elegantly span across multiple lines

I've been experimenting with CSS column count to create a masonry effect for my items. Everything was going smoothly until I added a subtle drop shadow to the items. Upon closer inspection in the jsfiddle link provided, you'll notice that the dr ...

Is it possible to change cases within a switch statement after one case condition has been satisfied?

I am currently working on implementing a game that involves rolling dice in Javascript/jQuery. The game has different "Phases" that the player must complete one by one without any interference from previous phases. The goal is to smoothly transition betw ...

Developing a custom mixin to alert a banner at the top of the webpage

I currently have a feature on my website that triggers a pop-up notification whenever a message is received from another user. The pop-up consists of a div displaying the content of the message along with a close button. After exploring various methods to ...

Having trouble getting the form input max-width to work properly within a flex-box

My webpage features a header containing various icons, a title, and a search box that triggers an animation when the search button is clicked. While this setup works seamlessly on larger screens, I encounter issues on smaller screens. My goal is for the se ...

Testing the unit with a customized header in the interceptor

I've been struggling to execute a unit test within an Angular 6 interceptor, but despite numerous attempts, I keep encountering the following error: Error: Expected one matching request for criteria "Match by function: ", found none. I'm rela ...

I am seeing an empty dynamic HTML table

I have been working on creating a dynamic HTML table, but I am facing an issue where the data is not displaying in the table. I have verified that the query is correct by testing it in SQL and confirming that it outputs the data. The problem seems to lie w ...

Retrieving JSON data from PHP using jQuery

I've been struggling with this issue for two whole days now, and I feel like I've hit a dead end in trying to solve it on my own. Here's the situation: I have two pages - one that contains a form with an address field that gets auto-filled ...

Retrieve unique elements from an array obtained from a web API using angular brackets

I've developed a web application using .NET Core 3.1 that interacts with a JSON API, returning data in the format shown below: [ { "partner": "Santander", "tradeDate": "2020-05-23T10:03:12", "isin": "DOL110", "type ...