What steps should I follow to design a unique select element using divs?

In my process of creating a unique custom design, I opted not to utilize a select element. Instead, I attempted to retrieve the value in handleSubmit(), but it kept displaying as undefined in the console.

https://i.sstatic.net/xZLuo.png

const handleSubmit = (event) => {
  event.preventDefault();
  var timing = document.getElementById("timings-id");
  console.log(timing.value);
}
<form>
  <div class="timings" id="timings-id">
    <div value="01:00">01:00</div>
    <div value="02:00">02:00</div>
    <div value="03:00">03:00</div>
    <div value="04:00">04:00</div>
    <div value="05:00">05:00</div>
    <div value="06:00">06:00</div>
    <div value="07:00">07:00</div>
    <div value="08:00">08:00</div>
    <div value="09:00">09:00</div>
    <div value="10:00">10:00</div>
    <div value="11:00">11:00</div>
    <div value="12:00">12:00</div>
  </div>
  <button type="submit" onclick="handleSubmit()">BOOK<button>
</form>

Answer №1

If you need a module to calculate the chosen hours, consider using the code snippet provided below:

function SelectTime(node) {
  var selectedHours = {};
  
  function getChosenTimes() {
    return Object.keys(selectedHours).filter(function(hour) {
      return selectedHours[hour];
    });
  }
  
  function toggleTimeSelection(ev) {
    var timeKey = ev.target.dataset.value;
    var isSelected = ev.target.classList.contains('selected');
    
    selectedHours[timeKey] = !isSelected;
    ev.target.classList.toggle('selected');
  }
  
  node.addEventListener('click', toggleTimeSelection);
  
  return {
    getChosenTimes: getChosenTimes
  };
}

const form = document.querySelector('form');
const timeSelector = SelectTime(document.querySelector('#timings-id'));

form.addEventListener('submit', function(ev) {
  ev.preventDefault();
  console.log(timeSelector.getChosenTimes());
})
.timings div {
  padding: .25rem .5rem;
  cursor: pointer;
}

.selected {
  background: skyblue;
}
<form>
   <div class="timings" id="timings-id">
     <div data-value="01:00">01:00</div>
     <div data-value="02:00">02:00</div>
     <div data-value="03:00">03:00</div>
     <div data-value="04:00">04:00</div>
     <div data-value="05:00">05:00</div>
     <div data-value="06:00">06:00</div>
     <div data-value="07:00">07:00</div>
     <div data-value="08:00">08:00</div>
     <div data-value="09:00">09:00</div>
     <div data-value="10:00">10:00</div>
     <div data-value="11:00">11:00</div>
     <div data-value="12:00">12:00</div>
   </div>
  <button type="submit">CONFIRM</button>
</form>

Answer №2

To achieve this, one method is to set click event handlers on your inner divs and then utilize the onclick function to add a data-value attribute to the parent container.

const timeDiv = document.getElementById("time-container");
const valueContainers = timeDiv.querySelectorAll("div");
const confirmButton = document.getElementById("confirm-button");

valueContainers.forEach((container) => {
  container.addEventListener("click", (e) => {
    timeDiv.dataset.value = e.target.dataset.value;
  });
});

const handleConfirm = (event) => {
  event.preventDefault();
  var selectedTime = document.getElementById("time-container");
  console.log(selectedTime.dataset.value);
}

confirmButton.addEventListener("click", handleConfirm);

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

Ways to mandate adjusting an option in <select> tag

Using the code $('select').change(function(){alert('changed');});, I am able to trigger an alert every time the option is changed. However, I also need to trigger the alert when the default option, which is the first one in the list, is ...

Exploring the combination of Babel and Next.js: Integrating custom scripts into a project

Hello, I am currently learning next.js and facing a common issue that I need help with. I have created my own ES6 JavaScript library and now I want to convert it to babel so I can use it in my next.js application. Is there a way to configure babel for sp ...

Issue with Swiper js "autoheight" not resizing correctly for the height of the first slide upon page initialization

Hey everyone, I'm encountering a problem with my reactapp and I'm not sure how to resolve it. I've spent a considerable amount of time searching on stackoverflow but haven't come across any helpful solutions. The issue is related to a ...

Start a timer in CodeIgniter when a button is clicked and show the time elapsed

Just a heads up: I am currently in the learning process. While I have some experience with PHP, my knowledge of Java is very limited or non-existent. In the past, I've received negative feedback due to this lack of experience. So, here I am giving it ...

The `introJs()` API encounters issues when connected to an element within a jQuery modal dialog box

I am attempting to showcase an Intro.js tour on a specific element located within a <table>. This particular <table> is nested inside a dialog box created using jQuery UI. The rows of the table are dynamically inserted using JavaScript: while ...

Error in hook order occurs when rendering various components

A discrepancy was encountered in React when attempting to render different components Warning: React has detected a change in the order of Hooks called by GenericDialog. This can result in bugs and errors if left unresolved. Previous render Next ren ...

Tips for stopping the current webpage from redirecting to a different page upon refreshing

How do I prevent the Profile page from redirecting to the Homepage every time it is reloaded? After a user logs in, they are directed to the Homepage. On the Homepage, there is a link to the Profile Page. The issue arises when reloading the Profile page, ...

Develop a DIV element that remains constant throughout different web pages without having to reload

How can I create a non-reloading div at the top of my website that contains an MP3 player which plays continuously while users browse through the site? I am working with Joomla and would like to avoid using Iframes for search engine optimization purposes ...

The image upload failed: the server could not locate the requested URL

I am completely new to working with Flask, and I'm currently in the process of creating a basic image uploading application. After comparing my code with various tutorials on how to build similar apps, it seems like everything is in place. However, w ...

When trying to add the @babel/transform-runtime plugin, an error occurs stating "Cannot access the property 'Reactstrap' as it is

Currently, I am developing a frontend website using React JS and the webpack loader. During development mode, everything works smoothly without any issues. However, when I tried to build the project and obtained the static files, I encountered an error: Un ...

using outlines for FontAwesome icons in React Native

I am struggling to use the fontAwesome + icon in the middle of a circle as one item. I have tried placing it inside a circle icon, but it doesn't seem to work properly. import IconFA from 'react-native-vector-icons/FontAwesome'; < ...

execute a function when an image is clicked using jQuery

How can I create an onclick event for the variable imageCatuaba? function setCatuaba(map) { var imageCatuaba = { url: 'images/catuskov.1.png', origin: new google.maps.Point(0, 0), anchor: new google.maps.Point(0, 32) }; I'm ...

Encountered an issue while trying to access the length property of an undefined value within an aside

I am currently utilizing ng-strap's modal, alert, and aside features. Each of them is functioning properly on their own, but when I attempt to place an alert or modal inside an aside, it throws the following error: Uncaught TypeError: Cannot read p ...

Issue with displaying multiple checkboxes using Materialize CSS in combination with Leaflet for web-mapping overlays

I'm currently using Materialize 0.97.7 along with Leaflet 1.0.1 (the latest version). <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.1/leaflet-src.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com ...

Trouble with controlling the speed of ajax requests while using vue-multiselect and lodash

I am working on a Vue application that includes a vue-multiselect component. My goal is to load the multiselect options via ajax. To achieve this, I am using lodash.throttle to limit the frequency of ajax requests as the user types in the search criteria ...

Angular's two-way binding feature allows the use of a variable as a string without directly assigning it to

Sample HTML code: <div tile-component included-svg='::installController.installUpdatesSvg'></div> Install controller: **A scope variable named 'installUpdatesSvg' is defined** this.installUpdateSvg = 'xyzSvg'; ...

Keep an ongoing execution of a node.js file by sending an HTTP request repeatedly

I am working on a project using node.js and express where I have a file named TCPServer.js that is responsible for polling a TCP/IP server. The goal is to send a single HTTP request to a database, retrieve the IP Address and port number, and then utilize t ...

Using JavaScript to halt the playback of HTML5 video in 'injected' HTML code

Although I know there have been similar issues resolved here before, none of the suggested solutions seem to work for me. Let me start by explaining my problem. I have a landing page located here: On the portfolio section of the landing page, I hav ...

sticky position is functional in Chrome, however it does not work in Firefox

I am looking to create a vertical div that stretches to the height of its parent container and contains smaller divs. If there is extra space, all divs except for the last one should be positioned at the top, with the last div placed at the bottom. I used ...

What steps should I take to either combine my two functions in my script or ensure they are executed in a specific sequence?

I'm attempting to incorporate a script into an HTML file (based on the solution provided by "skara9" in this post) and customize it to suit my requirements. However, I'm struggling to figure out how to make it work as intended. The script consis ...