Jquery checkbox val array? - javascript

Html
<td>
<input type="checkbox" value="1" id="t1" checked="checked" class="filter" /><label
for="t1">T1</label>
</td>
<td>
<input type="checkbox" value="2" id="t2" checked="checked" class="filter" /><label
for="t2">T2</label>
</td>
<td>
<input type="checkbox" value="3" id="t3" checked="checked" class="filter" /><label
for="t3">T3</label>
</td>
<td>
<input type="checkbox" value="4" id="t4" checked="checked" class="filter" /><label
for="t4">Toplam</label>
</td>
Script:
$(document).ready(function () {
$(".filter").click(function () {
drawChart();
});
});
function drawChart()
{
// I want to get checkboxes value here.
var filters = {$("#t1").val(),$("#t2").val(),$("#t3").val(),$("#t4").val()};
var view = new google.visualization.DataView(new google.visualization.DataTable(evalledData, 0.5));
view.setColumns([0, 4]); //here you set the columns you want to display
}
I want to get checkboxes value like above but I dont know correct syntax? Or I would pass array to drawChart. Could you write correct syntax to create an array of checkboxes values?
Edit
I want to set view columns with view.setColumns([0, 4]); with using checkboxes. I mean I want to use view.setColumns([array]); instead of view.setColumns([0, 4]);
Thanks.

var myValues = $(".filter").map(function () {
return this.value;
}).get();
console.log(myValues.join(","));
If you want only the checked ones:
var myValues = $(".filter:checked").map(function () {
return this.value;
}).get();
console.log(myValues.join(","));
http://api.jquery.com/map/

I assume that by value, you actually mean whether the checkbox is checked or not. (A checkbox always has the same value, regardless of whether it's checked or not.)
To get an array of boolean values:
var filters = $('.filter').map(function(i, e){
return $(e).is(':checked');
}).get();

Related

Jquery loop over checkbox and check for non checked

I am wanting to loop over an checkbox input and check if the checkbox ISNT selected then add the value of the checkbox to an array which im wanting to POST through ajax.
I have an example below of looping through checkboxes which are selected but how would i do the inverse of this while still including the .each?
var categories = [];
$("input[name='categories[]']:checked").each(function () {
categories.push(this.value);
});
You mean this?
$("input[name='categories[]']").each(function () {
if (!this.checked) categories.push(this.value);
});
or
const categories = $("input[name='categories[]']").not(":checked") // or ]:not(:checked)")
.map(function() { return this.value })
.get();
console.log(categories)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="categories[]" value="1" checked />
<input type="checkbox" name="categories[]" value="2" />
<input type="checkbox" name="categories[]" value="3" checked />

Pass Dynamically Generated Checked CheckBox's Value to Method in ASP.NET MVC

I have a form in View that on button click sends Model full of data to my Controller's ActionResult method.
In View I am generating checkboxes based on ViewModel's certain list content. Basically the number of checkboxes depends on number of items in the list while the page loads, so it may vary from session to session.
It the moment checkboxes are getting values corresponding to the items from the list.
I want to include checkboxes in the form. I don't know however how to pass their values dynamically to the Method along with Form's Model for other controls in the Form as their Id's, Names and number of them may vary.
ANyone has some idea how I can identify values of checkboxes that are checked?
In Razor/CSHTML:
<input type="checkbox" id="GB" class="CHK" onchange="selectCountry()" /> GB
<input type="checkbox" id="IE" class="CHK" onchange="selectCountry()" /> IE
<input type="checkbox" id="FI" class="CHK" onchange="selectCountry()" /> FI
<input type="checkbox" id="SE" class="CHK" onchange="selectCountry()" /> SE
<input type="checkbox" id="DK" class="CHK" onchange="selectCountry()" /> DK
In JS (to identify the variable):
var CountryChosen=''; //create empty variable to be filled
function selectCountry() {
if (document.getElementById("GB").checked == true) {
CountryChosen = "GB";
}
if (document.getElementById("IE").checked == true) {
CountryChosen = "Ireland";
}
if (document.getElementById("FI").checked == true) {
CountryChosen = "Finland";
}
if (document.getElementById("SE").checked == true) {
CountryChosen = "Sweden";
}
if (document.getElementById("DK").checked == true) {
CountryChosen = "Denmark";
}
}
You could also do an empty array for multiple selections:
CountriesChosen = [];
and instead of CountryChosen = X, do .push() to add to the full array and call the variables as part of the array...food for thought anyhow.
You can then use the JS variables to pass to the controller and action result but it depends what the action result is doing (e.g. JSON call could be through AJAX/JQUERY call and use the CountryChosen as a variable).
You can do it easily by using jQuery selectors as below. Keep the name of all checkboxes as the same and use the selector as below.
function getChecked() {
var checked_items = '';
$("input[name='item']:checked").each(function () { // get the checked items
checked_items = checked_items + "&item=" + $(this).val();
});
alert('JQUERY : Checked items are : ' +checked_items)
checked_items = ''
var items = document.getElementsByName("item")
for (i=0;i<items.length;i++){
if (items[i].checked)
checked_items = checked_items + "&item=" + items[i].value;
}
alert('JAVASCRIPT : Checked items are : ' +checked_items)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<input type="checkbox" name="item" value="1" />1
<input type="checkbox" name="item" value="2" />2
<input type="checkbox" name="item" value="3" />3
<input type="checkbox" name="item" value="4" />4
<input type="button" value="Submit" onclick="getChecked()">

How to replace input values with new values accordingly in jquery

just want to ask if how can I set a default values according to the number of checkboxes available. For example I have 3 checkboxes and I want to have a default values of 0,0,0 since I have 3 checkboxes. And if the user click the first checkbox the first 0 will be replaced with 1 since the value of the first checkbox has a value of 1 and the same as the rest checkboxes. And if the user uncheck the first checkbox it will return to it's default value which is 0. I have embedded my snippet. Thank you guys in advance.
$('input#category').on('change', function () {
var selectedCategories = $('.category:checkbox:checked').map(function () {
return this.value;
}).get();
$('#post_category').val(selectedCategories);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" value="1" id="category" name="category" class="category category_1">Category 1
<input type="checkbox" value="2" id="category" name="category" class="category category_2">Category 2
<input type="checkbox" value="3" id="category" name="category" class="category category_3">Category 3
<br />
<h5>Result:</h5>
<input type="text" id="post_category">
Check that in your code you have multiple elements with the same id and name attributes and should be unique.
On the change event handler there is no need to make a map/iterate over all the checked checkbox inputs because the changed element checkbox have properties value and checked:
var arr = [0, 0, 0],
setPostCategory = function() {
arr[this.value - 1] = (this.checked) ? this.value : 0;
$('#post_category').val(arr.join(', '));
};
$('input.category').on('change', setPostCategory);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" value="1" name="category1" class="category">Category 1
<input type="checkbox" value="2" name="category2" class="category">Category 2
<input type="checkbox" value="3" name="category3" class="category">Category 3
<br>
<h5>Result:</h5>
<input type="text" id="post_category" value="0, 0, 0">
You're already doing it, just check if the boxes are checked inside the mapping
var elems = $('.category[type="checkbox"]').on('change', function() {
var selectedCategories = elems.map(function() {
return this.checked ? +this.value : 0;
}).get();
$('#post_category').val(selectedCategories);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" value="1" id="category1" name="category" class="category category_1">Category 1
<input type="checkbox" value="2" id="category2" name="category" class="category category_2">Category 2
<input type="checkbox" value="3" id="category3" name="category" class="category category_3">Category 3
<br />
<h5>Result:</h5>
<input type="text" id="post_category">
Note the selector change. You can have the same classname for all three inputs, but they can not have the same ID, as ID's are unique
$('#post_category').empty();
$('#post_category').val(selectedCategories);

Return a string based on checkbox checked

I have a table with 2 checkboxes:
<table>
<tr>
<td>
<label for="A">
<input type="checkbox" name="A" id="A" value="true" />
A
</label>
<label for="B">
<input type="checkbox" name="B" id="B" value="true" />
B
</label>
</td>
</tr>
</table>
and I want to be able to identify which box is checked (by id), and be able to store a string as a variable, depending on the box. Here is my javascript:
var getCheck = function() {
if (document.getElementById('A').checked) {
return "A";
}
else if (document.getElementById('B').checked){
return "B";
}
else if ((document.getElementById('A').checked) && (document.getElementById('B').checked)) {
return "Both"
}
console.log(getCheck); // for debugging
};
So if I check 'A', I want getCheck to = 'A' as a string. Curious as to how to fix my Javascript to get it to work.
Here's an example of how you would do it with jQuery, it's just easier to do with it and since there's a jQuery tag...
Basically, you add a handler for elements that are checkboxes. Then you select only checked checkboxes with :checked and then you just access each element with the jQuery each function.
$(function(){
$('input[type=checkbox]').on('change', function(){
var checked = [];
$('input[type=checkbox]:checked').each(function(index, checkbox){
checked.push($(checkbox).attr('id'));
});
$('#result').text(JSON.stringify(checked, '/t'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<label for="A">
<input type="checkbox" name="A" id="A" value="true" />
A
</label>
<label for="B">
<input type="checkbox" name="B" id="B" value="true" />
B
</label>
</td>
</tr>
</table>
<pre id="result"></pre>
You need to check both first, since otherwise the function will return "A" and never reach the code that would return both. It is also possible to eliminate all the if-else complexity when returning from each if.
A helper function and some variables can reduce repetition and code length.
var isChecked = function(id){
var e = document.getElementById(id);
return (e && e.checked);
}
var getCheck = function() {
var A = isChecked("A");
var B = isChecked("B");
if (A && B) return "Both";
if (A) return "A";
if (B) return "B";
return "None";
}
For testing, you could add
window.onclick = function(){ console.log(getCheck()); }
demo via jsfiddle
fiddle example
The answer others provided is quite good for. And I want to make some addition:
If you want to get the value whenever user check the box, you can add a eventListen to the parent table as a delegation for the checkbox. Just as I show in the fiddle example
<table id="mytable">
<tr>
<td>
<label for="A">
<input type="checkbox" name="A" id="A" value="true" />
A
</label>
<label for="B">
<input type="checkbox" name="B" id="B" value="true" />
B
</label>
</td>
</tr>
</table>

Checks if a value exists in an array input value by jquery

I want check if id in array value input:cheched 3, alert (true) else alert (false). I tried as following js code, but don't work for me.
How can fix it?
DEMO: http://jsfiddle.net/VAwHR/4/
HTML:
<input value="3" type="text" id="seeid">
<div class="paginate">
<input name="ch[]" type="checkbox" value="1" checked>
<input name="ch[]" type="checkbox" value="2">
<input name="ch[]" type="checkbox" value="3" checked>
<input name="ch[]" type="checkbox" value="4">
</div>
<input type="submit" class="sub">
JQUERY:
$('.sub').click(function(){
var seeid = $('#seeid').val();
var db = $('.paginate :checkbox:checked').map(function (i, n) {
return $(n).val();
}).get();
alert($.inArray(seeid, db))
})
Here is the problem in id place you are having #
<input value="3" type="text" id="#seeid">
use this
<input value="3" type="text" id="seeid">
You have two errors. The first:
<input value="3" type="text" id="#seeid"> // id should be "seed"
The second:
$.inArray(seeid, db) > 0
should be
$.inArray(seeid, db) > -1 // or ~$.inArray(seeid, db)
Your code will fail to detect value 1 for example, because indexOf will return 0 in this case.
$('.sub').click(function(){
var seeid = $('#seeid').val();
var db = $('.paginate :checkbox:checked').map(function (i, n) {
return $(n).val();
}).get();
var flag;
if(flag = $.inArray(seeid, db) > -1){
alert(flag);
}
else {
alert(flag);
}
})
paste this into fiddle - it should give you the correct true/false alerts

Categories

Resources