Using jQuery to Retrieve Check Box Labels and Populate Them into Textboxes

I would like to display the name of the selected checkbox label in a textbox. If multiple checkboxes are selected, I want their labels to be separated by commas and displayed in the textbox. Please excuse my poor English.

$(document).ready(function() {
  $('.dropdown').click(function() {
    $('.dropdown-content').fadeToggle();
  });
});
.dropdown {
  width: 250px;
  height: 30px;
}
.dropdown-content {
  width: 253px;
  height: 100px;
  overflow-y: auto;
  border: 1px solid #ff8800;
  border-top: 0px;
  display: none;
}
.dropdown-content ul {
  padding: 0px;
}
.dropdown-content li {
  list-style: none;
  width: 100%;
  color: #fff;
  background: #ff8800;
  height: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="dropdown" placeholder="Select Values" />
<div class="dropdown-content">
  <ul>
    <li>
      <input type="checkbox" /><span>one</span>
    </li>
    <li>
      <input type="checkbox" /><span>two</span>
    </li>
    <li>
      <input type="checkbox" /><span>three</span>
    </li>
    <li>
      <input type="checkbox" /><span>four</span>
    </li>
    <li>
      <input type="checkbox" /><span>five</span>
    </li>
    <li>
      <input type="checkbox" /><span>six</span>
    </li>
    <li>
      <input type="checkbox" /><span>seven</span>
    </li>
    <li>
      <input type="checkbox" /><span>eight</span>
    </li>
    <li>
      <input type="checkbox" /><span>nine</span>
    </li>
  </ul>
</div>

Answer №1

Take a look at this code snippet

$(document).ready(function(){
$('.dropdown').click(function(){
$('.dropdown-content').fadeToggle();
}); 
$("input:checkbox").click(function() {
        var selection = "";
        $("input:checked").each(function() {
            selection += $(this).next('span').text() + ", ";
        }); 
        $(".dropdown").val(selection.trim().slice(0,-1));  
  }); 
});
.dropdown{
 width:250px;
 height:30px;
}
.dropdown-content{
  width:253px;
  height:100px;
  overflow-y:auto; 
  border:1px solid #ff8800;
  border-top:0px;
  display:none;
}
.dropdown-content ul{padding:0px;}
.dropdown-content li{
  
   list-style:none;
   width:100%;
   color:#fff;
   background:#ff8800;
   height:25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="dropdown" placeholder="Select Values"/>
<div class="dropdown-content">
<ul>
  <li><input type="checkbox"/><span>one</span></li>  
  <li><input type="checkbox"/><span>two</span></li> 
  <li><input type="checkbox"/><span>three</span></li> 
  <li><input type="checkbox"/><span>four</span></li> 
  <li><input type="checkbox"/><span>five</span></li> 
  <li><input type="checkbox"/><span>six</span></li> 
  <li><input type="checkbox"/><span>seven</span></li> 
  <li><input type="checkbox"/><span>eight</span></li> 
  <li><input type="checkbox"/><span>nine</span></li> 
</ul>
</div>

Answer №2

To implement a change event handler for checkboxes:

//Store checkbox elements in a variable
var checkboxes = $('.dropdown-content :checkbox');

//Bind the change event handler 
checkboxes.on('change', function() {

    var selectedValues = checkboxes
        .filter(':checked') //filter checked checkboxes
        .map(function() { //iterate through each
            return $(this).next().text(); //Get text of the next sibling span element 
        })
        .get() //return an array
        .join(','); //combine into a string

    $('label').text(selectedValues); //update label text
});

$(document).ready(function() {
  $('.dropdown').click(function() {
    $('.dropdown-content').fadeToggle();
  });
  
  //Store checkbox elements in a variable
  var checkboxes = $('.dropdown-content :checkbox');
  
  //Bind the change event handler 
  checkboxes.on('change', function() {
    
    var selectedValues = checkboxes
    //filter checked checkboxes
    .filter(':checked')
    //iterate through each and get text of the next sibling span element 
    .map(function() {
      return $(this).next().text();
    })
    //return an array
    .get()
    //combine into a string
    .join(',');
    
    $('label').text(selectedValues)
  });
  
  
});
.dropdown {
  width: 250px;
  height: 30px;
}
.dropdown-content {
  width: 253px;
  height: 100px;
  overflow-y: auto;
  border: 1px solid #ff8800;
  border-top: 0px;
  display: none;
}
.dropdown-content ul {
  padding: 0px;
}
.dropdown-content li {
  list-style: none;
  width: 100%;
  color: #fff;
  background: #ff8800;
  height: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="dropdown" placeholder="Select Values" />
<div class="dropdown-content">
  <ul>
    <li>
      <input type="checkbox" /><span>one</span>
    </li>
    <li>
      <input type="checkbox" /><span>two</span>
    </li>
    <li>
      <input type="checkbox" /><span>three</span>
    </li>
    <li>
      <input type="checkbox" /><span>four</span>
    </li>
    <li>
      <input type="checkbox" /><span>five</span>
    </li>
    <li>
      <input type="checkbox" /><span>six</span>
    </li>
    <li>
      <input type="checkbox" /><span>seven</span>
    </li>
    <li>
      <input type="checkbox" /><span>eight</span>
    </li>
    <li>
      <input type="checkbox" /><span>nine</span>
    </li>
  </ul>
</div>
<label></label>

Answer №3

Give this a shot:

$(document).ready(function(){

    var data = [];

    $('.dropdown').click(function(){

        $('.dropdown-content').fadeToggle();

    })

    $(".dropdown-content :checkbox").on("change",function(){

        if ($(this).prop("checked"))
            data.push($(this).next().text());

        else {
            var index = data.indexOf($(this).next().text());
            data.splice(index,1);
        }

        $(".dropdown").val(data);

    })

})

Here is the updated code :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <style>
        .dropdown{
 width:250px;
 height:30px;
}
.dropdown-content{
  width:253px;
  height:100px;
  overflow-y:auto;
  border:1px solid #ff8800;
  border-top:0px;
  display:none;
}
.dropdown-content ul{padding:0px;}
.dropdown-content li{

   list-style:none;
   width:100%;
   color:#fff;
   background:#ff8800;
   height:25px;
}
    </style>
</head>
<body>

   <input type="text" class="dropdown" placeholder="Select Values"/>

    <div class="dropdown-content>
    <ul>
      <li><input type="checkbox"/><span>one</span></li>
      <li><input type="checkbox"/><span>two</span></li>
      <li><input type="checkbox"/><span>three</span></li>
      <li><input type="checkbox"/><span>four</span></li>
      <li><input type="checkbox"/><span>five</span></li>
      <li><input type="checkbox"/><span>six</span></li>
      <li><input type="checkbox"/><span>seven</span></li>
      <li><input type="checkbox"/><span>eight</span></li>
      <li><input type="checkbox"/><span>nine</span></li>
    </ul>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js}</script 
   <script>

    $(document).ready(function(){

        var data = [];

        $('.dropdown').click(function(){

            $('.dropdown-content').fadeToggle();

        })

        $(".dropdown-content :checkbox").on("change",function(){

            if ($(this).prop("checked"))
                data.push($(this).next().text());

            else {
                var index = data.indexOf($(this).next().text());
                data.splice(index,1);
            }

            $(".dropdown").val(data);

        })

    })


    </script>
    </body>
</html>

Answer №4

This code snippet is designed to dynamically update the value of an input field based on which checkboxes are checked.

$("input[type='checkbox']").change(function(){
    var values =  $("input[type='checkbox']:checked")
        .map(function () {
            return $(this).closest("li").find("span").text();
        })
        .get()
        .join(',');

    $("input[type='text']").val(values);
});

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

Using callback functions in a JavaScript AJAX request

I am currently working on a function to handle an Ajax request with a callback. The main goal of this code is to send a request and display the response within a div element on my HTML page. However, I have been facing issues with the callback functionalit ...

Accordion not appearing on the webpage

I'm currently working on implementing a helpful feature at the bottom of my webpage to assist users with navigation. I was thinking of using an accordion as a dropdown helper, but I've been facing some challenges getting it to function properly. ...

Unveiling the Solution: Deactivating CSS Style Hints in VS Code!

click here to view the image Can anyone guide me on how to turn off the style hint feature in VS Code while working with CSS? ...

Create a new div element in your HTML structure that is not currently defined in your Sass/CSS

Currently, I am developing a React Component that includes a DatePicker feature using PrimeReact's Calendar component. I have a specific requirement to display an arrow on top of the datepicker when it pops up. You can view the desired layout in the ...

What are the essential files needed in Kendo UI Core for a mobile app?

Several months ago, I created a trial Kendo mobile app but now I want to verify it using the most recent version of Kendo UI Core. In my previous project, I referenced the following files: <link href="../styles/kendo.common.min.css" rel="stylesheet" / ...

Press a single button to toggle between displaying and hiding the table

$(document).ready(function() { $("#t1").hide(); // hide table by default $('#sp1').on('click', function() { $("#t1").show(); }); $('#close').on('click', function() { $("#t1").hide(); }); }); <li ...

The icon will vary based on the configuration in the database

For several weeks now, I have been attempting to set up my new LAN-based homepage on a Raspberry Pi running Raspbian. My goal is to save the status of some RC switches in a database and display their current states on my website. The database is already se ...

Add a new to-do list item to the current list using jQuery

Currently, I am in the process of developing a todo list application using jQuery. However, I have encountered some issues and bugs that are causing challenges. Initially, my objective was to set the first element through HTML code, which is functioning as ...

Achieving Vertical Alignment of Two Divs with CSS

I've come across several solutions to my issue, but none of them seem to work in my current situation. I have a banner at the top of my site with two floated columns, and suspect that the navigation menu in the right column may be causing the problem. ...

Shifting the final child to the front position proves unsuccessful with jQuery

I have attempted to move the last element in my list to the first position upon clicking, but unfortunately, it is not working as expected. I followed the advice provided in response to a question on the following page: Move last child to first position. W ...

Detection of numerous Google Analytics tags

To troubleshoot a client's Google Analytics account connected to their website, I decided to utilize the Tag assistant by Google extension. Upon running it, an alert popped up displaying "Multiple Google Analytics tags detected." One tag was the one I ...

JSRender: A guide on accessing variables from outside the block

I am currently using jsrender to display the details of my JSON object. One thing I'm trying to figure out is how to access an external variable from within the list. Any help would be greatly appreciated. <script id="itemTemplate" type="text/x ...

Bootstrap navigation bar collapsing horizontally instead of vertically

My Navbar is collapsing correctly, but when I click the toggle icon after it's collapsed, the items appear in a horizontal row instead of the intended vertical block. I have checked the code on the Bootstrap 5 example page and tried to replicate it, b ...

Upgrade the arrow accordion in bootstrap by incorporating images instead

I have implemented a Bootstrap accordion with a toggle arrow. Here is an example: http://jsfiddle.net/zessx/r6eaw/12/ My question is, if I want to change the arrow with an image, what do I need to edit? Or how can I implement it? This is the image I want ...

ClickAwayListener in MUI has the potential to impact all the elements within a popper when attempting

As a new react developer, I have encountered a small problem with my ClickAwayListener. It should close the Popper component when clicking 'x' or outside of it, which it does successfully. However, I have another component inside my Paper, and wi ...

how can I convert div attributes into JSON format

I am working with the following div element: <div class="specialbreak"> This div has been saved in a JavaScript variable. My goal is to convert this div into JSON format so that I can easily access the class name. Although I attempted to use JSON ...

Issue with Bootstrap small column vertical alignment not functioning as expected

I am working on a bootstrap layout with two columns. One column contains multiple elements and text, making it quite long, while the other column only has an image. I am trying to center this image vertically within the left column of content. Here is the ...

Differences in HTML animations can be seen when comparing Google Chrome to Microsoft Edge. Looking for a workaround for autoplay to ensure

My intro video animation is facing recording difficulties due to the autoplay policy in Google Chrome. It seems nearly impossible to capture it accurately. If only autoplay could function for an offline HTML file, my issue would be resolved. Unfortunately ...

Encountered a 400 error when attempting to send a request to a RestController in Spring MVC

I keep getting a "bad request 400" error when sending a request with parameters to the controller. I have double-checked the syntax but can't find any mistakes. Can someone please review my code and see what's wrong? var url = contextPath+"/bill ...

What could be the reason why my AJAX error is not displaying the exception from my Webmethod?

I am currently utilizing Google Chrome for my work tasks. After referring to , I attempted to throw an exception from a webmethod. However, no output is shown in the console.log. The only information I received is a generic error message from the network ...