How to use jQuery to get the checked checkboxes values, and put it into a textarea immediately?
Just like this code:
<html> <head> </head> <body> <div id="c_b"> <input type="checkbox" value="one_name" checked> <input type="checkbox" value="one_name1"> <input type="checkbox" value="one_name2"> </div> <textarea id="t"></textarea> </body> </html>
If the id="c_d"
is updated by Ajax, the below of altCognito's code doesn't work. Is there any good solution?
Using jQuery, we first set an onclick event on the button after the document is loaded. In the onclick event, we created a function in which we first declared an array named arr. After that, we used a query selector to select all the selected checkboxes. Finally, we print all the vales in an alert box.
If you want to get checked checkboxes from a particular checkbox group, depending on your choice which button you have clicked, you can use $('input[name=”hobbies”]:checked') or $('input[name=”country”]:checked'). This will sure that the checked checkboxes from only the hobbies or country checkbox group are selected.
To get an array of selected checkboxes values we need to use jQuery each() method and :checked selector on a group of checkboxes. The each() method will loop over the checkboxes group in which we can filter out selected checkboxes using :checked selector.
Here's one that works (see the example):
function updateTextArea() { var allVals = []; $('#c_b :checked').each(function() { allVals.push($(this).val()); }); $('#t').val(allVals); } $(function() { $('#c_b input').click(updateTextArea); updateTextArea(); });
Some number of months later another question was asked in regards to how to keep the above working if the ID changes. Well, the solution boils down to mapping the updateTextArea function into something generic that uses CSS classes, and to use the live function to monitor the DOM for those changes.
You can also return all selected checkboxes value in comma separated string. This will also make it easier for you when you send it as a parameter to SQL
Here is a sample that return all selected checkboxes values that have the name "chkboxName" in comma separate string
And here is the javascript
function showSelectedValues() { alert($("input[name=chkboxName]:checked").map(function () { return this.value; }).get().join(",")); }
Here is the HTML sample
<html> <head> </head> <body> <div> <input name="chkboxName" type="checkbox" value="one_name" checked> <input name="chkboxName" type="checkbox" value="one_name1"> <input name="chkboxName" type="checkbox" value="one_name2"> </div> </body> </html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With