Get checked values of checkbox list using jquery - javascript

I have a couple of checkbox with the name etapes. I'd like to get all the checked etapes's value and store it in a single string.
So tried this :
$('[name="etapes"]:checked').each(function() {
indexer = indexer + 1;
if (indexer == 1) selectedEtapes = $(this).val();
else selectedEtapes = selectedEtapes + "," + $(this).val();
});
but it didn't work. SO how can I fix this issue?

Easier solution is to use jQuery.map
var mapped = $('[name="etapes"]:checked').map(function() {
return this.value;
}).get();
console.log(mapped.join(','));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="checkbox" name="etapes" value="Ouverte1" checked>
<input type="checkbox" name="etapes" value="Ouverte2">
<input type="checkbox" name="etapes" value="Ouverte3" checked>
Fix for your code:
You never accepted index argument,
var selectedEtapes = '';
$('[name="etapes"]:checked').each(function(index) {
if (!index) selectedEtapes += $(this).val();
else selectedEtapes += "," + $(this).val();
});

You can do it using map() method like following.
var str = $('[name="etapes"]:checked').map(function() {
return $(this).val();
}).get().join();
console.log(str)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="etapes" value="Ouverte1" checked="checked">
<input type="checkbox" name="etapes" value="Ouverte2">
<input type="checkbox" name="etapes" value="Ouverte3" checked="checked">
<input type="checkbox" name="etapes" value="Ouverte4" checked="checked">

Related

javascript change and send multiple checkbox values

H, I have 4 checkboxes that i need to set values when clicked and unclicked. I have code that works for the first one but struggling to make it work with the other 3?
The code is
<label><input type="checkbox" name="colorCheckbox" value="red"> Return journey required?</label>
<div align="left"> <label><input type="checkbox" name="signs" id="signs"> Non sign written</label></div>
<div align="left"> <label><input type="checkbox" name="disabled" id="disabled"> Disabled access</label></div>
<div align="left"> <label><input type="checkbox" name="female" id="female"> Female driver</label></div>
and the js that works for the first on is :
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
var inputValue = $(this).attr("value");
$("." + inputValue).toggle();
if (this.checked){
document.getElementById("return_required").value = "YES";
}
else {
document.getElementById("return_required").value = "NO";
}
});
});
Because they don't have a value like the first one. They have an id.
You are getting the input value and working on it, so if the input don't has a value, you won't be able to select it.
var inputValue = $(this).attr("value"); // Offending line, because only your first input has a value.
$("." + inputValue).toggle();
The easiest way would be to check the name of the clicked element using this.name and manually match it to the checkboxes, then code the logic for each checkbox. An example is provided below:
$(document).ready(function() {
$('input[type="checkbox"]').click(function() {
var inputValue = $(this).attr("value");
$("." + inputValue).toggle();
if (this.name == "colorCheckbox")
if (this.checked) {
document.getElementById("return_required").value = "YES";
} else {
document.getElementById("return_required").value = "NO";
}
else if (this.name == "signs") {
console.log("signs"); // replace with logic
} else if (this.name == "disabled") {
console.log("disabled"); // replace with logic
} else if (this.name == "female") {
console.log("female"); // repalce with logic
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input type="checkbox" name="colorCheckbox" value="red"> Return journey required?</label>
<div align="left"> <label><input type="checkbox" name="signs" value="signs"> Non sign written</label></div>
<div align="left"> <label><input type="checkbox" name="disabled" value="disabled"> Disabled access</label></div>
<div align="left"> <label><input type="checkbox" name="female" value="female"> Female driver</label></div>
<br>
<input id="return_required" value="NO"></input>

checkbox - Check uncheck functionality is not working

My situation :
I am working on an shopping cart application and it contains some filters:
Filter by color (checkboxes)
Filter by style (checkboxes)
on selecting some of the colors my url becomes like this:
http://example.com/women/try.php?color=10,11,12,13
My issue :
On unchecking some colors the related params are not getting cleared from the url.
Also when I select some styles , I want the url to be like this:
http://example.com/women/try.php?color=10,11,12,13&style=1,2,3
Please help me how to achieve this functionality.
My code :
<?php
$colors = $_GET['color'];
$sel_colors = explode(',', $colors);
foreach($sel_colors as $k=>$v) {
$c['check'][$v] = $v;
}
for($i=10;$i<=14;$i++) { ?>
<input type="checkbox" name="color[]" value="<?php echo $i; ?>" <?php echo $check_value = ($c['check'][$i]) ? 'checked' : '0'; ?> >
<label>Color #<?php echo $i.'--'.$check_value; ?></label><?php
}
?><br/><br/><br/>
<input type="checkbox" name="type" value="1" >
<label>style #1</label>
<input type="checkbox" name="type" value="2" >
<label>style #2</label>
<input type="checkbox" name="type" value="3" >
<label>style #3</label>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js" ></script>
<script type="text/javascript">
var baseUrl = 'http://website/women/try.php?color=';
$(document).ready(function () {
// listen to change event (customize selector to your needs)
$('input[type=checkbox]').change(function (e) {
e.preventDefault();
if ($(this).is(':checked')) {
// read in value
var queryString = $(this).val();
// loop through siblings (customize selector to your needs)
var s = $(this).siblings();
$.each(s, function () {
// see if checked
if ($(this).is(':checked')) {
// append value
queryString += ',' + $(this).val();
}
});
// jump to url
window.location = baseUrl + queryString;
}
});
});
</script>
Here is a code snippet of working solution. Name of the color checkbox is changed from color[] to just color
var baseUrl = 'http://website/women/try.php?';
$(document).ready(function () {
// listen to change event (customize selector to your needs)
$('input[type=checkbox]').change(function (e) {
//Get all the selected color values
var queryString = "color="+$('[name="color"]:checked')
.map(function() {return this.value;}).get().join(',');
//Append all the selected styles
queryString += "&style="+$('[name="type"]:checked').map(function() {return this.value;}).get().join(',');
//reload page - commented for this snippet
//window.location = baseUrl + queryString;
alert(baseUrl + queryString);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Color filter -->
<input type="checkbox" name="color" value="1" checked >
<label>Color 1</label>
<input type="checkbox" name="color" value="2" checked >
<label>Color 2</label>
<input type="checkbox" name="color" value="3" checked >
<label>Color 3</label>
<input type="checkbox" name="color" value="4" checked >
<label>Color 4</label>
<BR><BR>
<!-- Style filter -->
<input type="checkbox" name="type" value="1" >
<label>style #1</label>
<input type="checkbox" name="type" value="2" checked>
<label>style #2</label>
<input type="checkbox" name="type" value="3" checked>
<label>style #3</label>
Use map() function to get all checked color and style checkbox values like following.
var baseUrl = 'http://website/women/try.php?color=';
$('input[name="color[]"], input[name="type"]').change(function () {
var colors = $('input[name="color[]"]:checked').map(function () { return this.value; }).get().join();
var styles = $('input[name="type"]:checked').map(function () { return this.value; }).get().join();
window.location = baseUrl + colors + '&style=' + styles;
});

jquery: remove the selected value if checkbox is unchecked

I'm displaying list of items with checkbox, if checkbox is checked the value of selected item is displayed in different div.
Now, if I uncheck the checkbox I should remove the items displayed in the div.
Please help me how to fix this?
$('input[name="selectedItems1"]').click(function(){
if (this.checked) {
}else{
//what should go here
}
});
This example can help you:
html
<input type="checkbox" name="selectedItems1" value="val1" />
<input type="checkbox" name="selectedItems1" value="val2" />
<input type="checkbox" name="selectedItems1" value="val3" />
<div id="result"></div>
jquery
$('input[name="selectedItems1"]').click(function(){
if (this.checked) {
var span = "<span id='" + this.value + "'>" + this.value + "</span>";
$("#result").append(span);
}else{
$("#" + this.value).remove();//what should go here
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="selectedItems1" value="val1" />
<input type="checkbox" name="selectedItems1" value="val2" />
<input type="checkbox" name="selectedItems1" value="val3" />
<div id="result"></div>
Here is a way to accomplish your task. The following way also preserves the order in which the selected data is displayed.
var selectedItemsContainer = $('#selected');
var items = $('input[name="items"]');
items.on('change', function(){
selectedItemsContainer.empty();
var appendData = '';
$.each(items, function(i, item)
{
if ($(item).prop('checked'))
{
appendData +=$(item).val() + ' ';
}
});
selectedItemsContainer.append(appendData);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="checkbox" name="items" value="Data 1">Data 1
<input type="checkbox" name="items" value="Data 2">Data 2
<input type="checkbox" name="items" value="Data 3">Data 3
<br>
<div id="selected"></div>

How to pass values of selected checkboxes to the javascript function?

I need to pass values of selected check boxes to the javascript method but it does not detect the checkbox.
<form name="cat" method="POST" action="myaction">
<c:forEach items="${items}" var="item">
<input type="checkbox" id="pro" name="pro" value="${item.id}"/>
</c:forEach>
...
<input type="button" value="getItem" onclick="getItem(this.form)"/>
</form>
Javascript
function getItem(frm) {
alert("size:" + frm.pro.length); <<< it returns size:unidentified
var values = "";
for (var i = 0; i < frm.pro.length; i++)
{
if (frm.pro[i].checked)
{
values = frm.pro[i].value + ",";
}
}
alert(values); << it is empty
....
//pass values to the back-end
I think your approach is old fashioned. Here's a jQuery version.
NOTE: you are adding multiple id="pro" and this is just wrong remove it
First add id="form" to your form
Here you can find a fiddle. :D
http://jsfiddle.net/SXffG/3/
HTML:
<form id="form" name="cat" method="POST" action="myaction">
<input type="checkbox" name="pro" value="1"/>
<input type="checkbox" name="pro" value="2"/>
<input type="checkbox" name="pro" value="3"/>
<input type="checkbox" name="pro" value="4"/>
<input type="checkbox" name="pro" value="5"/>
<input type="checkbox" name="pro" value="6"/>
<input type="button" class="getItem" value="getItem"/>
</form>
<div id="info">Click the button</div>
JavaScript
var allVals = [];
$(function() {
$('#form .getItem').click(function() {
allVals = []
$('#form :checked').each(function() {
allVals.push($(this).val());
});
//alert("Values " + allVals);
$.ajax({
type: "POST",
url: "http://localhost:8080/example/ajaxSubmit.action",
data: "allVals=" + allVals,
success: function(response){
$('#info').html("OK! Data [" + allVals + "] Sent with Response:" + response);
},
error: function(e){
$('#info').html("OH NOES! Data[" + allVals +"] Not sent with Error:" + e);
}
});
});
});
var check = document.getElementsByName("pro");
var textArray = [];
for(var c = 0; c < check.length;c++){
if(check[c].checked){
textArray .push(check[c].value);
}
}
textArray = textArray .join("~");
you will get the data as tilde separated. Hope this helps you.

Make a matrix with input inside a DIV by mixing input values

Take a look at this:
<div id="main">
<div id="a">
<input value="1" />
<input value="2" />
<input value="3" />
</div>
<div id="b">
<input value="4" />
<input value="5" />
</div>
</div>
I need to get each input value inside div#a and each input value in div#b and build a matrix/mixing of those values, taking the same example as before, this is what the code should return:
<div id="mixed">
<input value="1" /><input value="4" />
<input value="1" /><input value="5" />
<input value="2" /><input value="4" />
<input value="2" /><input value="5" />
<input value="3" /><input value="4" />
<input value="3" /><input value="5" />
</div>
I have tried to move inside div#main using this code:
$("#main div").each(function() {
var that = $(this);
console.log("that.attr('id')");
});
But console.log() never logs something so I must doing something wrong. This is a advanced topic for me and need some help, any?
UPDATE
At this point I have this maded:
$("#choices div").each(function() {
var that = $(this);
that.each(function() {
var thati = $(this);
console.log(thati);
});
});
And I think in the second .each() is where I can get the input values and try to build the matrix
Should help:
var arr = [];
$('#a input').each(function () {
var that = $(this);
$('#b input').each(function () {
arr.push(that.val());
arr.push($(this).val());
});
});
Then go through the array and dynamically generate the HTML. You can treat this like a matrix by stepping every 2 values.
var a = $('#a input');
var b = $('#b input');
var html = '';
a.each(function () {
var first = this;
b.each(function () {
html += '<div>' + first.outerHTML + this.outerHTML + '</div>'
});
});
$('#mix').html(html);
jsFiddle here
update: code for what's asked for in comments.
var divs = $('#main > div');
var html = '';
divs.each(function (index) {
var divsLength = divs.length,
inputs = $('input', divs[index]),
inputsLength = inputs.length;
for (var i = 0; i < divsLength; i++) {
if (i === index) {
continue;
}
for (var j = 0; j < inputsLength; j++) {
$('input', divs[i]).each(function () {
html += inputs[j].outerHTML + this.outerHTML + '<br />';
});
}
}
});
$('#mix').html(html);

Categories