Alter the display style of the nearest span using jQuery when the select option is modified

Here is the code block that I am working with:

<div class="user-select-dropdown">
    <span class="filter-header">User:</span>
    <span class="remove-option">✖</span>
    <select class="form-control" ng-model="filter.UserId" ng-change="filterModel(filter)" ng-options="item.Id as item.Name for item in usersList">
       <option value="" disabled selected>Select user...</option>
    </select>
</div>

The X span serves as a button to reset the select option. However, when the select has no options, the remove-option span should have the style display: none;. It needs to be displayed once an option is chosen. The CSS styles are defined as follows:

.remove-option {
    display: none;
    bottom: 14%;
    color: darkgrey;
    font-size: 15px;
    position: absolute;
    right: 7%;
    z-index: 99999;
    cursor: pointer;
}

.user-select-dropdown {
    position: relative;
    display: inline-block;
    margin-left: 10px;
    width: 250px;
}

I've also included some jQuery code:

$(".remove-option").click(function () {
    $(this).next("select").val($("select option:first").val());
});

$(".form-control").change(function () {
    if ($(this).val() >= 0)
        $(this).next(".remove-option").css("display: block");
    else
        $(this).next(".remove-option").css("display: none");
});

The .form-control class is from Bootstrap.

The issue lies with

$(this).next(".remove-option").css(...)
not functioning properly. Any assistance on resolving this problem would be greatly appreciated.

Answer №1

If you examine your html, you will notice that the span comes before the form-control element so you can use .prev()

$(".form-control").change(function() {
    $(this).next(".remove-option").toggle($(this).val() >= 0);
});

You can simplify changing the display using .toggle() as shown above in a single line


Given that it appears you are working with angularjs

var app = angular.module('my-app', [], function() {})

app.controller('AppController', function($scope) {
  $scope.usersList = [{
    Id: 1,
    Name: '1'
  }, {
    Id: 2,
    Name: '2'
  }, {
    Id: 3,
    Name: '3'
  }, {
    Id: 4,
    Name: '4'
  }];
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
<div ng-app="my-app" ng-controller="AppController">
  <div class="user-select-dropdown">
    <span class="filter-header">User:</span>
    <span class="remove-option" ng-show="filter.UserId > 0">✖</span>
    <select class="form-control" ng-model="filter.UserId" ng-change="filterModel(filter)" ng-options="item.Id as item.Name for item in usersList">
      <option value="" disabled selected>Select user...</option>
    </select>
  </div>
</div>

Answer №2

When the remove-option element comes before your form-control, remember to use prev instead of next.

$(".form-control").change(function () {
    if ($(this).val() >= 0)
        $(this).prev(".remove-option").css("display: block");
    else
        $(this).prev(".remove-option").css("display: none");
});

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

Discover additional features in Angular 4 by reading further

I am struggling with incorporating a "read more" feature in my paragraph on my website. The challenge I'm facing is determining how to trigger the feature to display only when there are more than 5 lines of text. <p>Contrary to popular belief, ...

Stop the submission of a form more than once

I created a form for users to share their reviews on movies. However, I am facing an issue where if a required field is left empty, an error alert is displayed prompting the user to fill in the field. The problem arises when the submit button is clicked ...

There is an unnecessary gap between the parent div and the image contained within it

Snippet of HTML code showcased below: <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link href="css/style.css" rel="style ...

Interact with multiple links within a table using Python

In an attempt to automate the process of clicking on multiple links within a table, I have crafted the following HTML code: <div id="gadget-34365" class="gadget-inline" style="height: 905px;"> <div class="results-wrap search-results-dashboard-ite ...

jQuery does not support displaying output using console.log

I have a JavaScript code that uses jQuery. However, when I click the #button_execute button, the console.log inside the callback function of .done doesn't display anything on the console. I'm not sure how to troubleshoot this issue. $("#button_e ...

Tips for preventing a bootstrap modal from being dragged beyond its parent container

I need help figuring out how to prevent my bootstrap modal from being dragged outside of its parent container. Is there a way to constrain the modal within its parent? $(document).ready(function() { ShowValidationResult(); }); function ShowValidation ...

Perform a jQuery callback when an image finishes loading after changing its src

After successfully changing the img src once I've loaded a json file, I want to ensure that the image is fully loaded. I have implemented the following method: .one("load",function(){ alert("image has load yay"); }); ...

What is the best way to remove all elements in jQuery?

I need to remove the selected element in my demo using jstree. I have consulted the plugin's API at http://www.jstree.com/api/#/?f=deselect_all([supress_event]), but it seems that it does not deselect the item properly. Here are the steps I have follo ...

jsTree unable to locate node using the provided ID

Implementing the jsTree on the webpage is not a problem for me. I have experimented with numerous suggestions from different sources. $('#myTree').jstree({ .... }) .on('loaded.jstree', function (e, dta) { var t = $('#myTree&a ...

What is the best way to automatically show the last two digits of a phone number in a second text field?

Is there a way to automatically display the last 2 digits of a phone number input into the first text field onto the second text field using AJAX, JavaScript, or jQuery? I am looking for a script for my website similar to what was shown in this video. I ...

Refreshing the MarkerCluster following an AJAX request

My current challenge involves an AJAX function that retrieves posts based on users with a specific role. While the query itself works fine, I am encountering an issue with refreshing the markers on Google Maps after the AJAX request is complete and the pos ...

Using Python Selenium to extract data - a step-by-step guide

Here is the link you are looking for: I have successfully accessed this website using Selenium-Webdriver in Python. My next task is to extract the information about the battery type. https://i.sstatic.net/mSd6Y.jpg ...

Designing GWT FlexTable using pure CSS styling

Is there a way to style a GWT FlexTable using CSS alone? The API doesn't provide information on available CSS classes. Are there no predefined classes and do I need to define them myself? I am particularly interested in styling the "th" element. ...

Creating dependent dropdown lists is a useful way to streamline data entry and ensure accuracy in your

I am looking to create a series of 4 connected dropdown lists, structured like this: District: <select id="district"> <option>Select a District</option> <option value="district1">dstrict1</optio ...

bootstrap used for creating horizontal radio buttons

I'm attempting to horizontally align radio buttons within a form without relying on the Bootstrap library. The following code achieves this: <form id="test_form"> <div class="control-group"> <label for="Q1">First question</ ...

How do I attach an event listener to a select box that is created dynamically using JavaScript?

I'm new to web development and I'm currently working on a project where I need to create a select box dynamically within a div that is also created dynamically when the page loads. However, I'm facing an issue with adding an onchange Event L ...

What is the maximum number of JavaScript functions allowed in a single HTML file?

My HTML5 file includes JavaScript (created from CoffeeScript) directly within the HTML file, as I prefer this approach for my HTML/JavaScript programming. The code consists of four JavaScript functions that convert one temperature unit to another. Strang ...

How can you determine if all specified events have been triggered in jQuery?

I am implementing custom triggered events following asynchronous calls, and I'm in need of a method to determine when all the events have been triggered. For instance: var ajaxCall1 = function(){ $.ajax({ url: "someUrl.html", com ...

Utilizing dynamic jQuery events with variable integration

I'm having some trouble incorporating a variable into a dynamically added jQuery event. Every time I click, the message displayed is "The number is 3" for all div elements. $( document ).ready(function() { for (var i = 0; i < 3; i++) { ...

Changing the Color of Navbar Links in Bootstrap 4

Good evening everyone, Recently, I've been experimenting with Bootstrap 4 to create a simple Navbar. I encountered an issue where I attempted to adjust the font-size and color (or hover color) in the Navbar. Strangely, the font-size adjustments seem ...