jQuery: Extracting text labels from checkboxes

My custom select dropdown includes checkboxes that are hidden until the user clicks on the dropdown:

---Select----
-option1-
-option2-
-option3-

When a user clicks on the Select, the options appear as checkboxes. I want to be able to retrieve the labels of the selected checkboxes and display them in the "select" field. Additionally, I need to figure out how to reset the text back to "Select" if all checkboxes are deselected.

The JavaScript code for this custom select function looks like this:

$('.custom-select').click(function() {
$(this).children('.custom-select-drop').toggleClass('not-showed');
)};

Each checkbox receives a selected class when it is checked.

EDIT: The HTML structure is as follows:

<div class="custom-select">
<span class="selectTitle">Something</span>
<div class="custom-select-drop not-showed">

<label for="check1">
<input type="checkbox" class="ch" id="check1" />Check1
</label>

<label for="check2">
<input type="checkbox" class="ch" id="check2" />Check2
</label>

<label for="check3">
<input type="checkbox" class="ch" id="check3" />Check3
</label>

If a user selects check2 and check3, I want to extract their label texts (Check2 and Check3) and replace the initial text ("Something") inside the span. When the user deselects the checkboxes, the text should revert back to "Something".

Answer №1

If my understanding of the task is correct, this solution could prove to be useful

Here is a snippet of sample HTML code:

<select id="select_element">
    <option id="default"> - select - </option>
</select>

<div>
    <label><input type="checkbox" class="checkboxes" value="someval1">Box value 1</label><br>
    <label><input type="checkbox" class="checkboxes" value="someval2">Box value 2</label><br>
    <label><input type="checkbox" class="checkboxes" value="someval3">Box value 3</label><br>
    <label><input type="checkbox" class="checkboxes" value="someval4">Box value 4</label><br>
</div>

The following code demonstrates how checkboxes can be manipulated:

$(document).ready( function() {
    var default_opt = false;

    $(".checkboxes").change( function() {
        var opt_id = 'opt' + $(this).val();

        if( $(this).is(":checked") ) {

            // Save the default value
            if( !default_opt ) {
                default_opt = $( '#select_element > #default').clone();
                $( '#select_element > #default').remove()
            }

            var text = $(this).parent().text().trim(); ///< Retrieve trimmed label's text
            var item = $('<option></option>').attr({ id: opt_id, value: text }).text( text ); ///< Create a new <option> element with that text

            $('#select_element').append( item ); ///< Add this <option> to the <select>
        }
        else {
            $( '#select_element > #' + opt_id ).remove();

            // Restore default value if no checkboxes are selected
            if( ! $( '#select_element' ).children().length ) {
                $( '#select_element' ).append( default_opt );
            }
        }
    });
});

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

The AngularJS directive is failing to run the Jquery-ui menu component

I'm struggling to implement a jquery-ui menu within an AngularJS directive. I attempted to use this fiddle as a reference for my project. html: <div ng-app="myApp" ng-controller="mainController"> <ul j-menu> <li>Test 1</l ...

Adjust the parent div's background when hovering over it

Here is the code snippet I am working with: <div class="thumb_image_holder_orange"> <img src="http://dummyimage.com/114x64/000/fff.png" /> </div> I want to change the background of the div when hovering over the image, rather than j ...

Assistance needed with dynamically resizing a background image

Is there a way to automatically adjust the size of a background image for an element? For instance, I want my links in HTML to have a background image with slanted borders and rounded corners. Usually, you would set the width of the anchor element to fit t ...

Determining the decimal width of an element using jQuery

I've been searching everywhere for a method to accurately determine the width of an element without rounding. The reason behind this is that I have multiple elements floated to the left with display inline-block and I am attempting to automatically ad ...

Using jQuery-ias in combination with masonry to generate an endless scrolling feature is experiencing issues in PHP

Struggling to integrate jquery-ias with masonry, facing issues in getting it to work properly. Utilizing a mysql database and php for loading images. Through numerous trials and errors, I have almost achieved correct functionality. Successfully displayi ...

Refreshing div with updated form/content using jQuery and AJAX

Is it possible to use jQuery/AJAX functions to replace a form (or any content) with another form when a button is clicked, without reloading the page? Essentially creating a multi-part form dynamically. Can I achieve this with the following code snippet? ...

What is the best way to transfer variables between PHP and an external JavaScript file?

I need to transfer 2 variables (which store data for a chart) to an external JS file that contains the chart settings. In my PHP code, I have: <script type='text/javascript'> var final_values = '$final_values'; var final_names = ...

Is it possible to incorporate Nth child into JavaScript?

Is it feasible to implement an Nth Child in the following code snippet? $(function() { var count = $(".parent a").length; $(".parent div").width(function(){ return ($(".parent").width()/count)-5; }).css("margin-right","5px"); }); ...

Splitting a td tag into multiple columns dynamically with Angular

I am attempting to dynamically split the table element into separate columns. My desired layout should resemble this: The values for name and surname are fixed at 1, but the values for subjects and grades can vary (there may be 2 or more columns). Below ...

I specialize in optimizing blog content by omitting the final line within a React framework

https://i.stack.imgur.com/WKOXT.png Currently, I have 4 lines and the 5th line in the current input field. This is my React code snippet: import { FC, useEffect, useState } from "react"; interface BlogWitterProps {} const BlogWitter: FC<B ...

Guide on stacking a transformed 3D div on top of a masked layer with higher Z-index without success

I am attempting to stack a green div on top of a blue div using CSS transformations. The blue div acts as a masked layer, while the green div is a dialog that should appear on top. I have tried adjusting the z-index property, but the blue div always ends ...

Step-by-step guide on generating a fluid list with Express and HTML

Looking to create a dynamic list by fetching data from a JSON file. I want the list items to redirect me to specific content based on their IDs when clicked. However, my current approach is not working as expected, and the list needs to be truly dynamic. ...

sending information from a PHP form to a JavaScript window

Currently, I am in the process of developing a game using javascript and jquery. In this game, when a player interacts with another character, it triggers the opening of text from an external file using the window.open('') function. At the start ...

How can I change the transparency of a CSS background color using JavaScript?

I have a question about CSS: .class1 { background: #fff } Now, I need to achieve the following: .class2 { background: rgba(255,0,0,0.5) }; Is there a way to use JavaScript only to change the background property of .class1 and give it an opacity of 0.5? ...

"Unexpected discrepancy: Bootstrap Glyphicon fails to appear on webpage, however, is visible

I am having some trouble getting the glyphicon to display properly in my side nav. The arrow head should rotate down, which is a pretty standard feature. Here is the link to the page: The glyphicon should be visible on the "Nicky's Folders" top leve ...

Is it possible to access the DOM element within which the registerHelper is being used?

My current challenge involves using Template.registerHelper to create a helper that can output either class1 or class2 based on a boolean value. Additionally, I want the output to include an initial class only if it's the first time the helper is call ...

Does Dominate library for Python have a feature akin to .replace() function?

I have a specific task where I need to extract text from a .txt file, add HTML tags, and then save the content as HTML. My goal is to identify certain words within the text and wrap them in anchor tags for styling purposes. Here is an example of what I am ...

Prevent triggering postback while validating during form submission in MVC

Is there a way to prevent postback for validation upon clicking Submit? I've noticed that after clicking submit, the page reloads/postbacks before displaying any validation errors. @model X.Models.ModelVm @using (Html.BeginForm()) { @Html.AntiFo ...

I am having trouble with my image not resizing properly within the flexbox when using height and max-height properties

In my flexbox setup, I have two columns, each taking up 50% of the width. My goal is to insert a large square image in the right column, with its height being determined by the contents' height in the left column. (Additional content will be added to ...

data being returned twice onpopstate

After experimenting with onpopstate, I encountered an issue. When I click the back button in my browser, the URL changes as expected, but the page code loads twice, resulting in duplicate lists and div elements. Why is this happening and how can it be reso ...