Change the selection box to a checkbox

I am struggling to retrieve the value of a selection box inside jQuery. Specifically, I need to access the selection box value within a function that triggers on a checkbox change event:

This is what I have so far:

$('input').on('change', function()  //need selection box value here
});

<select class="selectclass" id="id" >
 <option  value="22" >option1</option>   
  <option  value="33" >option21</option> 
</select>

I have looked into similar questions on stackoverflow but have not found the solution I need

jquery change select to checkbox

etc...

Answer №1

Here is a simple way to convert the select option to a checkbox when the selection changes:

$('select').on('change', function() {
  var val = $(this).val();
  $('<input/>').attr({
  type: 'checkbox',
  value: val
  }).appendTo('#check');
  console.log(val);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="selectclass" id="id">
 <option  value="22" >option1</option>   
  <option  value="33" >option21</option> 
</select>
<div id="check"></div>

You can also achieve this without using the change function, by simply using onload:

$('select option').each(function() {
  var val = $(this).val();
  $('<input/>').attr({
    type: 'checkbox',
    value: val
  }).appendTo('#check');
})

$('input').on('change', function() {
  alert(this.value);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="selectclass" id="id">
 <option  value="22" >option1</option>   
  <option  value="33" >option21</option> 
</select>
<div id="check"></div>

Answer №2

Here's a snippet of code that extracts values and displays labels.

$('select#selectid option').each(function() {
  var val = $(this).val();

$("#check").append('<input type="checkbox" value="'+$(this).val()+'">'+$(this).val()+'</input>');
   })

$('#selectid').prop('disabled','disabled').hide();

$('input').on('change', function(){
  alert(this.value);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="selectclass" id="selectid">
 <option  value="22" >option1</option>   
  <option  value="33" >option21</option> 
</select>
<div id="check"></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

Having difficulty ensuring DayJs is accessible for all Cypress tests

Currently embarking on a new Cypress project, I find myself dealing with an application heavily focused on calendars, requiring frequent manipulations of dates. I'm facing an issue where I need to make DayJs globally available throughout the entire p ...

Having trouble parsing the body parameter in Express for a POST request

I am encountering difficulty in accessing the body parameters of a request using Express: const bodyParser = require('body-parser'); const cors = require('cors'); const express = require('express'); const app = express(); con ...

What is the equivalent of {...props} in React for destructuring props in Vue?

When working in React, I can destructure props with ease: function MyComponent() { const myProp = { cx: '50%', cy: '50%', r: '45%', 'stroke-width': '10%' } return ( <svg> ...

Activate the overflow feature within native-base cards

I have a unique design element on a website that showcases an image overflowing off a card. The image has a negative margin-top of -50, creating this effect. Now I'm trying to replicate this design in react-native using native-base components. Here i ...

What strategies can I implement to minimize repetition in React when utilizing the useState hook?

I have implemented useState in my React Native application. I defined states named lstandtime and lacttime. Additionally, I have created functions called onSubmitfunc, LsonChangefunc, and LaconChangefunc. We initially required 3 instances of the MainCons ...

Exploring the fundamentals of authentication with Express JS

Currently, I am encountering a challenge while attempting to implement basic authentication with Username and Password using Express JS. The problem lies in the fact that when I try to incorporate an if statement within an app.use() function, it does not s ...

Leverage the PhantomJS variable within the page.evaluateJavaScript function

Currently, I am using PhantomJS to capture a screenshot of the dashboard and save it as a PNG file. Everything works perfectly fine until I try to include additional arguments (line, dFrom, dTo) and use them within the page.evaluateJavaScript() function. U ...

The Ajax script seems to be failing to update the PHP file along with its corresponding variable value

I have a simple form where upon clicking the "=" button, I want the calculated value to be displayed in file process.php. However, this functionality is not working for me. It seems that when the "=" button is clicked, nothing happens. The default value in ...

The browser freezes when attempting to upload an image using an ajax call

I'm currently using this code to upload an image to the server via AJAX, but I've noticed that the browser freezes while the image is being uploaded. Can someone please help me diagnose the issue and find a solution? $(function() { $("#form4 ...

Enhance user experience with PrimeFaces by implementing an Ajax update feature through

I'm interested in using PrimeFaces to ajax update a JavaScript script. <script type="text/javascript"> <!-- function lineChartExtender(){ this.cfg.highlighter = { showTooltip: true, tooltipAxes: &apos ...

Achieving perfect alignment in a CSS grid for form elements vertically

One of my current projects involves creating a form layout using HTML and CSS that follows a Material Design style: <div class="form-group"> <input type="text" id="feedName" name="name" value={nameValue} onChange={this.handl ...

Error: Invalid Request - Nodejs Request Method

As part of my project involving payment gateway integration, I needed to make a call to the orders api. However, I encountered an error message: {"error":{"code":"BAD_REQUEST_ERROR","description":"Please provide your api key for authentication purposes."} ...

Switching from module.exports in Javascript to Typescript format

My Node-express code currently uses module.exports to export functions. As I am converting the code to TypeScript, I need to find out how to replace module.exports in typescript. Can you help me with this? ...

Issues arise when attempting to send an AJAX POST request within WordPress

After going through multiple resources, all mentioning the same approach that I am following, I have two essential files for this process: In the receiver.php file: <?php add_action( 'wp_enqueue_scripts', 'my_enqueue' ); ad ...

Setting up CSS Flexbox so that the first child element is the same height as the

I am striving to ensure that when the layout switches to mobile, the image block matches the height of the title and content blocks. The layout is quite complex; it functions correctly in desktop view with the title block at the top full-width. I suspect ...

Is it possible to implement a validation process that prevents the opening of a modal using data-bs-target until all necessary

I am currently using bootstrap version 5.2.3 and I have encountered an issue where the modal opens regardless of validation rules being met or not. I attempted to modify the data-bs-toggle and data-bs-target attributes using Vue.js, but the changes did no ...

Getting access to the properties of an array containing objects

Check out the data below: [ { "name": "Fluffy", "species" : "rabbit", "foods": { "likes": ["carrots", "lettuce"], "dislikes": ["seeds", "celery"] } }, { "name": "Woofster", "species" : "dog", "foods": { ...

Best practices for sending variables to an HTML page using nodemailer

I am interested in sending an email with an HTML template that includes dynamic data. For example, I want to include a unique id within a link on the page. Is it possible to insert dynamic data into HTML content when sending emails? If yes, I would apprec ...

Node js overlooking non-packaged middleware

I encountered an issue with middleware that used to be included in NODE.js but is no longer bundled. I followed the instructions provided here: Node js Error: Most middleware (like session) is no longer bundled with Express and must be installed separatel ...

A customized Javascript application designed specifically for Blackberry Bold users, enabling them to effortlessly choose a country and seamlessly enter a correctly formatted zip code in the designated text field

I am currently developing a mobile web app for Blackberry Bold 9700 & 9650 devices running on the 5.0 browser. The main functionality of the app involves allowing users to select either US or Canada from a drop-down menu. Based on their selection, the ...