Implementing dynamic element selection with jQuery: combining onClick and onChange events

I am looking to update the appearance of the arrow on a select option. By default, it is styled as caret-down. When a user clicks in the input area, I want to change the style to caret-up. If the select option has been changed or no action has been taken, then revert back to the default style.

Here is my HTML :

<div class="form-group row">
    <div id="select" class="col arrow-down">
      <select name="idBengkel" class="form-control custom-select" required>
        <option value="" disabled selected>Select Item</option>
        <?php foreach($bengkel as $row):?>
          <option value="<?= $row['idBengkel'];?>"><?= $row['nmBengkel'];?></option>
        <?php endforeach;?>
      </select>
    </div>
  </div>

This is my CSS :

.custom-select{
  position:relative !important;
  background: transparent !important;
  -webkit-appearance: none;
}

.arrow-down::after{
  font-family: FontAwesome;
  content: '\f0d7';
  position: absolute;
  right:10%;
  bottom: 15%;
  font-size: 120%;
  pointer-events: none;
}

.arrow-up::after{
  font-family: FontAwesome;
  content: '\f0d8';
  position: absolute;
  right:10%;
  bottom: 15%;
  font-size: 120%;
  pointer-events: none;
}

This is my JavaScript :

<script>
  $('#select').on('click', function () {
    // Button clicked
    $("#select").removeClass("arrow-down");
    $("#select").addClass("arrow-up"); 
  });
  $('select').change(function () {
    // Option selected
    $("#select").addClass("arrow-down");
  });
</script>

Kind regards!

Answer №1

I have replaced a addClass() function with toggleClass(), and then implemented a hasClass check within the second on('click') event. Additionally, I made modifications to the CSS for the arrow icon changing it to a border tag.

jQuery

$('.custom-selectbox select[name=idBengkel]').on('click', function( e ) {
$(this).parent().toggleClass("open");
return false;
});
$(document).on('click', function(e) {
var $arrow = $('.custom-selectbox');
if ($arrow.hasClass('open')) {
    $arrow.removeClass('open');
} else {
    return false;
}
});

CSS

 select { /* For Example */
    color: #000;
    outline: none;
    display: inline-block;
    -moz-appearance: none;
    appearance: none;
    cursor: pointer;
    height: 20px;
    padding-right: 20px;
 }

 .custom-selectbox{
    position: relative;
    display: inline-block;
 }
 .custom-selectbox:after{
  content: '';
    height: 0;
    width: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 5px solid #000;
    position: absolute;
    right: 6px;
    top: 8px;
    transition: all 0.3s linear;
}
.custom-selectbox.open:after{
    -webkit-transform: rotate(-180deg);
    -moz-transform: rotate(-180deg);
    -o-transform: rotate(-180deg);
    transform: rotate(-180deg);
}

HTML:

  <div class="form-group row">
   <div id="select" class="col custom-selectbox">
    <select name="idBengkel" class="form-control custom-select" required>
      <option value="" disabled selected>Select Item</option>
      <option value="1">1</option>
      <option value="1">1</option>
      <option value="1">1</option>
    </select>
   </div>
 </div>

Example

$('.custom-selectbox select[name=idBengkel]').on('click', function( e ) {
   $(this).parent().toggleClass("open");
   return false;
});
$(document).on('click', function(e) {
    var $arrow = $('.custom-selectbox');
    if ($arrow.hasClass('open')) {
        $arrow.removeClass('open');
    } else {
        return false;
    }
});
select { /* For Example */
    color: #000;
    outline: none;
    display: inline-block;
    -moz-appearance: none;
    appearance: none;
    cursor: pointer;
    height: 20px;
    padding-right: 20px;
}

.custom-selectbox{
    position: relative;
    display: inline-block;
}
.custom-selectbox:after{
  content: '';
    height: 0;
    width: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 5px solid #000;
    position: absolute;
    right: 6px;
    top: 8px;
    transition: all 0.3s linear;
}
.custom-selectbox.open:after{
    -webkit-transform: rotate(-180deg);
    -moz-transform: rotate(-180deg);
    -o-transform: rotate(-180deg);
    transform: rotate(-180deg);
}

.arrow-down::after{
  font-family: FontAwesome;
  content: '\f0d7';
  position: absolute;
  right:10%;
  bottom: 15%;
  font-size: 120%;
  pointer-events: none;
}

.arrow-up::after{
  font-family: FontAwesome;
  content: '\f0d8';
  position: absolute;
  right:10%;
  bottom: 15%;
  font-size: 120%;
  pointer-events: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div class="form-group row">
  <div id="select" class="col custom-selectbox">
    <select name="idBengkel" class="form-control custom-select" required>
      <option value="" disabled selected>Select Item</option>

      <option value="1">1</option>
      <option value="1">1</option>
      <option value="1">1</option>

    </select>
  </div>
</div>

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

Anticipate await and fulfill promises

I'm encountering issues when attempting to refactor nested Promise.all's into async/await. It seems like there might be a misunderstanding in how I should be utilizing Promise.all and await. The goal is to iterate through an array, perform an ac ...

Real-time chat system using PHP for one-on-one inquiries with server-sent events (not a group chat)

I'm currently working on developing a live chat inquiry form for a website using HTML server-sent events. I'm utilizing this tutorial as a foundation Here is my plan based on the tutorial: On the client side, users are prompted to enter a use ...

Utilizing Three.js to employ raycasting from the camera in order to choose specific items

Hi everyone, I'm currently attempting to create a ray that extends straight out from the camera and intersects with objects in my line of sight. However, all the resources I've come across involve using the mouse for this interaction, and I' ...

JavaScript date formatting without using jQuery

Looking for help to apply a date mask (dd/mm/yyyy) on an ASP.net textbox. I have tried several JavaScript solutions found through Google search, but none seem to work seamlessly, especially with backspacing. Any suggestions for a reliable script would be ...

Switch out text and calculate the frequency of letters in a given string

I have a string that looks like this: "061801850010300-09/A/B". My goal is to replace all "/" with "-" and also change "A" to "1" and "B" to "2". My objective is to assign each letter in the alphabet a numerical value - for example, A as 1, B as 2, C as 3 ...

javascript: restrict the quantity of products

As a beginner in javascript, I am currently working on creating a simple RSS reader. However, I am facing a challenge in limiting the number of feeds to 5 items, especially since the target site may have 100 or more feeds. Here's the code snippet I&ap ...

When storing array values in objects, only the first value is saved and is repeatedly replaced with the same value

As a newcomer to JavaScript, my programming skills are not very strong at the moment. I have been working on a web scraper that returns an array of information including names, posts, bios, and more using the following code: let infoOfPost = await newTab(b ...

Unable to retrieve the URL using the getDownloadURL function from Firebase

I have been using Firebase storage to successfully store images, however I am encountering an issue when trying to retrieve the image URL from a promise. const imageSaveHandler = (e) => { e.preventDefault(); const uploadTask = storage.ref(`i ...

Ways to extract single JSON entities from a consolidated JSON structure

I am facing a challenge with parsing multiple JSON objects within a single large JSON object. Currently, the entire JSON object is being stored as one entity, but I need to parse and store them separately in MongoDB. Below is the code snippet I am using. ...

Executing Ionic function before application shutdown

Does anyone know of a function that can be triggered when the app is about to exit, close, or go into the background? Essentially any event that indicates "the user has stopped using the app"? In my app, I create a 'user log' that keeps track of ...

Can you explain the process for setting the css property text-fill-color in IE and Mozilla browsers, similar to how I set -webkit-text-fill-color for Webkit?

The color displays correctly in Chrome, but how can I make it work in both IE and FF? CSS #Grid td.note div.has-note i { -webkit-text-fill-color: #b4efa8; } ...

By setting up a keydown event listener, I am unable to inspect HTML elements by using the F-12 key shortcut in Chrome

Recently, I encountered an issue where adding a keydown event listener in my JavaScript code prevented F-12 from working properly. window.addEventListener("keydown", function (event) { if (event.defaultPrevented){ retu ...

The input box fails to show larger values on the user's page

Show me the biggest number that the user enters in an input box and then display it back to them. I need some improvements to my code, ideally making it possible with just one input box instead of two. <!DOCTYPE html> <html la ...

Enhancing jQuery performance on mobile Safari

I've been faced with a puzzling issue concerning CORS on multiple web applications I developed, particularly when it comes to mobile Safari on our corporate iPads. To elaborate on the setup, there is a front-end server hosting the web pages and two d ...

The Minimax algorithm experiencing issues in Next.js

I recently wrote some code in Next.js, but unfortunately, it's not functioning as expected. Despite my best efforts and attempts at utilizing alpha beta pruning, the code still fails to work properly. The issue lies in the fact that it simply returns ...

Steps for configuring jQuery hide(), adding Class, and remove Class for flawless execution

My HTML Code is structured as follows : ... @foreach($hotel as $key=>$value) ... <div class="iteration"> <input type='hidden' value='<?php echo $value['HCode'].'#' ...

Establish an interval that loops through the elements of an array

I'm currently working on implementing an interval for the length of an array stored in state. The particular array eventDate consists of 4 elements, and I want the function to cycle through values 0, 1, 2, 3, then loop back to 0. This is my code ...

Adjust the size of an element by utilizing a different element

I'm facing a challenge with this code. I need to dynamically set the width of the "wrap-description" divs to be equal to the width of the corresponding "picture-damage" images plus an additional 20 pixels. Since there will be multiple elements for bot ...

Setting up WebPack for TypeScript with import functionality

A tutorial on webpack configuration for typescript typically demonstrates the following: const path = require('path'); module.exports = { ... } Is it more advantageous to utilize ES modules and configure it with import statements instead? Or is ...

The compiled JavaScript is getting messed up by the Grunt build process

I have taken over a project that was incomplete from the beginning. I am facing issues with the deployment as the grunt task is not working correctly, even after following the overrides specified here. The generated vendor.js file seems to be causing error ...