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

Storing data locally in PhoneGap using localStorage via AJAX calls is a common requirement for

Our mobile application is built with cordova [phonegap] and we are looking to implement offline saving of results into the cache memory. The results are fetched from a PHP server and displayed in a webview using ajax and javascript. I have tried using loc ...

What is the best way to include an image in a bootstrap carousel?

Can anyone help me troubleshoot my issue with fitting an image into the bootstrap carousel? I've tried adjusting the CSS, but it's not working. Any advice or suggestions would be greatly appreciated! Here is a screenshot for reference: Below is ...

Resetting the check status in html can be accomplished by using the checked

I am currently working on a popup feature in HTML <div id="term_flags" class="term_flags"> <div class="modal-users-content flagsContent"> <div class="modal-users-header"> <span class="close" ng-clic ...

Decode my location and input the address before validating it

While I have come across numerous plugins that enable geolocation and display it on a map, I am searching for something unique. I am interested in implementing geocoding when a user visits the page with an option to "allow geolocation." If the user agrees ...

Is it possible to create an HTML dropdown menu with integer values?

What is the best way to create a dropdown menu in HTML with integer values ranging from 1 to 12? How can I ensure that when a value is selected, it gets saved into a variable? All I need is a simple select field in HTML that displays options from 1 to 12 ...

Having Trouble with Your Instafeed Script

I've been working on a project that involves integrating an Instagram feed into a website. However, I'm facing difficulties getting it to function properly. Here's the code that I have implemented. <script type="text/javascript"> ...

Is it possible to deactivate a button using jQuery without changing its visibility to transparent?

In my current project, I am utilizing jQuery and exploring its unique methods. I have a scenario where I need to disable two buttons based on a specific condition: if (...condition...) { $('button#submit, #hint').prop("disabled", true); } Ho ...

Struggling to make a form submit work with AngularJS and a Bootstrap datetime picker

Struggling to create a post and include name and datetime using a bootstrap datetimepicker. After selecting the datetime and clicking add, nothing happens. However, if I manually type in the field and click add, it submits successfully. Despite reading up ...

Exploring Problems with Implementing the Jquery .click() Function on a Class

My goal is to create a simple JQuery code that triggers a pop-up message saying hello when any element of the specified class is clicked. Here's what I've tried: $(document).ready(function(){ $(".thumb_radio").click(function(){ aler ...

When the user hits the enter key, automatically submit a form without the need for

Is it possible to submit a form on enter using type="button"? Here are my input fields: <input type="text" id = "login-user" class="form-control log-input" placeholder="Username" required="required"> <input type="password" id="login-password" clas ...

The model binder fails to bind my model class by default

I am facing an issue with utilizing the Default Model Binder functionality in ASP.NET MVC 2 while trying to create a post... Upon clicking the checkout button, I dynamically populate a form using jQuery code and then proceed to submit it to the server. He ...

interacting with data tables using a jQuery selector or through an application programming

I encountered a problem like the following: First, I attempted to initialize the datatable as shown below: var oTable = table.dataTable(); Although my script ran well, I found that I couldn't use the datatables ajax reload function. oTable.ajax.rel ...

Display a button only when hovering over it

Seeking assistance for a simple task that is eluding me at the moment. I am currently using scss and trying to make a button only appear when hovered over. The button is hidden in the code snippet below, nested within a block alongside some svgs. Any hel ...

Launch the file explorer using JavaScript/HTML

Is there a way to launch a real explorer window instead of the browser's directory look? For example, like the windows key + e window... Is there a method using html or JavaScript? I've noticed it in a Firefox add-on called new tab king, but I c ...

HTML / CSS / JavaScript Integrated Development Environment with Real-time Preview Window

As I've been exploring different options, I've noticed a small but impactful nuance. When working with jQuery or other UI tools, I really enjoy being able to see my changes instantly. While Adobe Dreamweaver's live view port offers this func ...

Alter the font color upon clicking the menu using jQuery

When I click on the menu and sub-menu items, I want to change their colors along with their parent. You can see an example of how I want it to work here. However, currently, when I click on a sub-menu item, the color of the parent menu item gets removed. ...

Troubleshooting Problem with Button Image Display in CSS

I have created a custom CSS for a PayPal sprite that I made. Below is an image comparison showing how it appears in Internet Explorer and Firefox. Here is the code to display the sprite: .ppsprite { background: url('/images/paypal_sprite.png') ...

JavaScript utilizes regex patterns to modify the value located between the characters within an input's name attribute

Can anyone assist me in creating a unique regex pattern to extract specific characters from the attribute values of HTML inputs? I'm dynamically cloning select elements and input text with button clicks, so I need to maintain the attribute name synta ...

Insert an svg element into the content property

Is it possible to insert an SVG link within the content property? .selectedItem::before{ content: " any svg link "; ...

The subpage on Github Pages is failing to load despite the correct URL being entered

While working on a multipage website using React and hosting it on Github pages, I encountered an issue. The website functions perfectly on localhost, but encounters errors when accessing a subpage on Github pages. Upon clicking the subpage link, Github p ...