How to get every checkbox status base on same name attribute? - javascript

$("#btn").click(function() {
var vals = [];
$("body").find('input[name^=tc]:checked').each(function(e){
console.log(e + $(this).val());
vals.push($(this).val());
});
alert(vals);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
1<input type="checkbox" name="tc0" value="Y">
<br />
2<input type="checkbox" name="tc1" value="Y">
<input type="checkbox" name="tc1" value="N">
<br />
3<input type="checkbox" name="tc2" value="Y">
<input type="checkbox" name="tc2" value="N">
<br />
<button id="btn">click</button>
If I check Y for tc0, Y for tc1 and Y for tc2, and click the button and I will get Y,Y,Y.
What If I check Y for tc0, nothing for tc1, and N for tc2 and click the button and I will get Y,N.
What I except is to get Y,"",N.
How can I do that?

You can iterate over all the checkboxes
$("#btn").click(function() {
var tmp = {};
var vals = $('input[name^=tc]').map(function(e) {
var checked = $('input[name="' + this.name + '"]:checked');
if (!tmp[this.name]) {
tmp[this.name] = true;
if (checked.length > 1) {
return [checked.map(function() {
return this.value;
}).get()];
} else {
return checked.val() || '';
}
};
}).get();
snippet.log(JSON.stringify(vals));
});
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
1
<input type="checkbox" name="tc0" value="Y">
<br />2
<input type="checkbox" name="tc1" value="Y">
<input type="checkbox" name="tc1" value="N">
<br />3
<input type="checkbox" name="tc2" value="Y">
<input type="checkbox" name="tc2" value="N">
<br />
<button id="btn">click</button>

Related

jquery checkbox get value text input

I have list input checkbox
<input type="checkbox" name="id_image" value="homies_01" class="id_image" />
<input type="checkbox" name="id_image" value="homies_02" class="id_image" />
<input type="checkbox" name="id_image" value="homies_03" class="id_image" />
<input type="text" name="id_image" value="" class="id_image_check" />
How to check multiple input checkbox i have show value to input type="text"as
<form>
<input type="text" name="id_image" value="homies_01, homies_02, homies_03" class="id_image_check" />
</form>
There is a perfecly solution with Vanilla Javascript
function attachListeners() {
var checkboxes = document.getElementsByClassName('id_image')
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('click', getAndPutValues, false);
}
}
function getAndPutValues() {
var result = [];
document.querySelectorAll(".id_image:checked").forEach(function(item) { result.push(item.value);});
document.querySelector('.id_image_check').value = result.join(', ');
}
attachListeners();
With jquery
$(".id_image").on("click",function(){
$(".id_image_check").val(
$(".id_image :checked").map((i,el) => el.value).join(", ")
)
});
First of all you should use array notation for checkbox names
<input type="checkbox" name="id_image[]" value="homies_01" class="id_image" />
<input type="checkbox" name="id_image[]" value="homies_02" class="id_image" />
<input type="checkbox" name="id_image[]" value="homies_03" class="id_image" />
It will help you to post multiple values simultaneously
After that for checking values in jQuery you can use
<script type="text/javascript">
$('[name="id_image[]"]').click(function(){
var value = '';
$('[name="id_image[]"]:checked').each(function(){
value += $(this).val();
});
$('#id_image_check').val(value);
});
</script>
Try this :
<input type="checkbox" name="id_image" value="homies_01" class="id_image" onchange="toggleCheckbox(this)" />
<input type="checkbox" name="id_image" value="homies_02" class="id_image" onchange="toggleCheckbox(this)" />
<input type="checkbox" name="id_image" value="homies_03" class="id_image" onchange="toggleCheckbox(this)" />
<input type="text" name="id_image" id="id_image" value="" class="id_image_check" />
<script type="text/javascript">
var arrImages = [];
function toggleCheckbox(element) {
console.log('element', element.value);
arrImages.push(element.value);
document.getElementById("id_image").value = arrImages;
}
</script>
Just use square brackets [] at end of name if you want to submit it using form or use the following method in jQuery to get values of multiple selected checkboxes.
$('#show').click(function(){
values = "";
$('input.id_image:checked').each(function(){
values += $(this).val() + " ";
});
if(values){
$('#values').html(values);
}else{
$('#values').html("None");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="id_image[]" value="homies_01" class="id_image" /> Homies 1
<input type="checkbox" name="id_image[]" value="homies_02" class="id_image" /> Homies 2
<input type="checkbox" name="id_image[]" value="homies_03" class="id_image" /> Homies 3
<br>
<button id="show">Show</button>
<br>
<div id="values"></div>

Different groups of checkbox not working in jquery

I prefer to get checked checkboxes from a specific checkbox group, depending on which button I have clicked, I used $('input[name="' + groupName + '"]:checked'). This will ensure that the checked checkboxes from only the coffee or animals checkbox group are selected. But it's not working as I expected.
<body>
<div>
<input type="checkbox" value="Lion" name="animals" checked />Lion<br>
<input type="checkbox" value="Tiger" name="animals" />Tiger<br>
<input type="checkbox" value="Elephant" name="animals" />Elephant<br>
<input type="checkbox" value="Girafee" name="animals" />Girafee<br>
<input type="submit" id="__mainAnimals" />
<br><br><br><br><br><br>
<input type="checkbox" value="Coffe" name="drinks" checked />Coffe<br>
<input type="checkbox" value="Tea" name="drinks" />Tea<br>
<input type="checkbox" value="Milk" name="drinks" />Milk<br>
<input type="checkbox" value="Mocha" name="drinks" />Mocha<br>
<input type="submit" id="__mainDrinks" />
</div>
<div id="__DIVresult"></div>
<script type="text/javascript">
$(document).ready(function () {
$('#__mainAnimals').click(function () {
getSelectedCheckBoxes('animals');
});
$('#__mainDrinks').click(function () {
getSelectedCheckBoxes('drinks');
});
var getSelectedCheckBoxes = function (groupName) {
var result = $('input[name="' + groupName + '"]:checked');
if (result.length > 0) {
var resultString = result.length + " checkboxe(s) checked<br/>";
result.each(function () {
resultString += $(this).val() + "<br/>";
});
$('__DIVresult').html(resultString);
}
else {
$('__DIVresult').html("No checkbox checked");
}
};
});
</script>
</body>
1st id selector is # so $('__DIVresult') should be $('#__DIVresult')
2nd An ID should start with a letter for compatibility
Using characters except ASCII letters and digits, '_', '-' and '.' may cause compatibility problems, as they weren't allowed in HTML 4. Though this restriction has been lifted in HTML 5, an ID should start with a letter for compatibility.
REF: https://developer.mozilla.org/en/docs/Web/HTML/Global_attributes/id
3rd some small update, added two result div, one for animal one for drink:
<hr>
animals Result:
<div id="DIVresultanimals"></div>
<hr>
drinks Result:
<div id="DIVresultdrinks"></div>
Then target them dynamically with $('#DIVresult'+groupName).html(resultString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="checkbox" value="Lion" name="animals" checked />Lion
<br>
<input type="checkbox" value="Tiger" name="animals" />Tiger
<br>
<input type="checkbox" value="Elephant" name="animals" />Elephant
<br>
<input type="checkbox" value="Girafee" name="animals" />Girafee
<br>
<input type="submit" id="mainAnimals" />
<br>
<br>
<br>
<br>
<br>
<br>
<input type="checkbox" value="Coffe" name="drinks" checked />Coffe
<br>
<input type="checkbox" value="Tea" name="drinks" />Tea
<br>
<input type="checkbox" value="Milk" name="drinks" />Milk
<br>
<input type="checkbox" value="Mocha" name="drinks" />Mocha
<br>
<input type="submit" id="mainDrinks" />
</div>
<hr>
animals Result:
<div id="DIVresultanimals"></div>
<hr>
drinks Result:
<div id="DIVresultdrinks"></div>
<script type="text/javascript">
$(document).ready(function() {
$('#mainAnimals').click(function() {
getSelectedCheckBoxes('animals');
});
$('#mainDrinks').click(function() {
getSelectedCheckBoxes('drinks');
});
var getSelectedCheckBoxes = function(groupName) {
var result = $('input[name="' + groupName + '"]:checked');
if (result.length > 0) {
var resultString = result.length + " checkboxe(s) checked<br/>";
result.each(function() {
resultString += $(this).val() + "<br/>";
});
$('#DIVresult'+groupName).html(resultString);
} else {
$('#DIVresult'+groupName).html("No checkbox checked");
}
};
});
</script>
In your drink and animal section you are not separating the two so when you use your click function it doesn't discriminate between the tow sections. Once you add each one to a class then the button will only call the checked items that are actually checked.
<html>
<form>
<input name="selector[]" id="ani" class="ads_Checkbox" type="checkbox" value="Lion" />Lion</br>
<input name="selector[]" id="ani" class="ads_Checkbox" type="checkbox" value="Tiger" />Tiger</br>
<input name="selector[]" id="ani" class="ads_Checkbox" type="checkbox" value="Elephant" />Elephant</br>
<input name="selector[]" id="ani" class="ads_Checkbox" type="checkbox" value="Girafee" />Girafee</br>
<input type="button" id="save_value" name="save_value" value="Save" /></br>
<textarea id="t"></textarea>
</form>
<script>
function updateTextArea() {
var allVals = [];
$('.ads_Checkbox:checked').each(function() {
allVals.push($(this).val());
});
$('#t').val(allVals);
}
$('#save_value').click(function(){
$('.ads_Checkbox:checked').each(function(){
updateTextArea();
});
});
Inside this code I have named each animal and placed them in a class so I could recall them from an array. I hoped this helped.

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>

Check random checkboxes using JQuery

I know how to check and uncheck particular checkbox with ID and CLASS.
But I want to randomly select 10 checkbox using Jquery.
I will have 100,40 or XX number of checkbox everytime. (HTML Checkbox)
It might be 100 checkbox or 50 checkbox or something else. It will be different everytime.
I want to check 10 checkboxes randomly when a button is pressed.
User can manually select those 10 checkboxes. Or they can just press the random button.
I am using Jquery.
$(':checkbox:checked').length;
But i want to find the length of all the checkboxes and i want to check 10 random checkbox.
Are you looking for something like this?
http://jsfiddle.net/qXwD9/
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script>
//Creating random numbers from an array
function getRandomArrayElements(arr, count) {
var randoms = [], clone = arr.slice(0);
for (var i = 0, index; i < count; ++i) {
index = Math.floor(Math.random() * clone.length);
randoms.push(clone[index]);
clone[index] = clone.pop();
}
return randoms;
}
//Dummy array
function createArray(c) {
var ar = [];
for (var i = 0; i < c; i++) {
ar.push(i);
}
return ar;
}
//check random checkboxes
function checkRandom(r, nodeList) {
for (var i = 0; i < r.length; i++) {
nodeList.get(r[i]).checked = true;
}
}
//console.log(getRandomArrayElements(a, 10));
$(function() {
var chkCount = 100;
//this can be changed
var numberOfChecked = 10;
//this can be changed
var docFrag = document.createElement("div");
for (var i = 0; i <= chkCount; i++) {
var chk = $("<input type='checkbox' />");
$(docFrag).append(chk);
}
$("#chkContainer").append(docFrag);
$("#btn").click(function(e) {
var chks = $('input[type=checkbox]');
chks.attr("checked", false);
var a = createArray(chkCount);
var r = getRandomArrayElements(a, numberOfChecked);
//console.log(r);
checkRandom(r, chks);
});
});
</script>
</head>
<body>
<div id="chkContainer"></div>
<div>
<input type="button" id="btn" value="click" />
</div>
</body>
How about this:
Working example: http://jsfiddle.net/MxGPR/23/
HTML:
<button>Press me</button>
<br/><br/>
<div class="checkboxes">
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</div>
JAVASCRIPT (JQuery required):
$("button").click(function() {
// How many to be checked?
var must_check = 10;
// Count checkboxes
var checkboxes = $(".checkboxes input").size();
// Check random checkboxes until "must_check" limit reached
while ($(".checkboxes input:checked").size() < must_check) {
// Pick random checkbox
var random_checkbox = Math.floor(Math.random() * checkboxes) + 1;
// Check it
$(".checkboxes input:nth-child(" + random_checkbox + ")").prop("checked", true);
}
});

getting selected value of radio button in case of action

Hi here is the codes bellow, I've tried many things but I couldnt get value of selected radio button.As you can see I need to get that value for diffrent situations.
<div style="display: inline-block">
<div>
Log Out<span> Welcome </span>YS User 1 noName </div>
<br />
<br />
<br />
<br />
<input type="button" onclick="submitCreate();" value="New Survey" /><br />
<input type="button" onclick="submitEdit();" value="Edit Survey" /><br />
<input type="button" onclick="submitDelete();" value="Delete Survey" /><br />
<input type="button" onclick="submitPreview();" value="Preview Survey" />
</div>
<div style="display: inline-block">
<div>
<table class="MyTable"><thead><tr class="columnHead"><th scope="col"></th><th scope="col">CreatedBy</th><th scope="col">Created Date</th><th scope="col">Is Running</th></tr></thead><tbody><tr><td> <input name="selected" id="1"
type="radio" value="1" /></td><td>1</td><td>12/12/2011 3:43:57 PM</td><td>False</td></tr><tr class="altRow"><td> <input name="selected" id="2"
type="radio" value="2" /></td><td>1</td><td>12/13/2011 4:42:37 PM</td><td>False</td></tr><tr><td> <input name="selected" id="3"
type="radio" value="3" /></td><td>1</td><td>12/13/2011 6:27:38 PM</td><td>False</td></tr></tbody></table>
</div>
</div>
</body>
</html>
<script type="text/javascript">
// var value = $$('input[name=selected]:checked')[0].get('value');
// var selectFoo;
// $$('input[name=selected]').each(function (el) {
// if (el.checked == true) {
// selectFoo = el.value;
// }
// });
function getCheckedValue(radioObj) {
if (!radioObj)
return "";
var radioLength = radioObj.length;
if (radioLength == undefined)
if (radioObj.checked)
return radioObj.value;
else
return "";
for (var i = 0; i < radioLength; i++) {
if (radioObj[i].checked) {
return radioObj[i].value;
}
}
return "";
};
function submitCreate() {
var adress = "/User/CreateSurvey/";
document.location = adress;
};
function submitEdit() {
var adress = "/Den/Index/" + getCheckedValue('selected');
document.location = adress;
};
function submitDelete() {
var adress = "/User/DeleteSurvey/" + getCheckedValue('selected');
document.location = adress;
};
function submitPreview() {
var adress = "/User/PreviewSurvey/" + getCheckedValue('selected');
document.location = adress;
};
</script>
You can use document.getElementsByName(<button_name>) or document.getElementsByTagName("input") to get an array of input elements. Loop through those elements to check which is checked.
Here is an example of how to get the value of the checked button from a set of radio buttons with the name "selected":
<html>
<head>
<script type="text/javascript">
function get_radio_value() {
var inputs = document.getElementsByName("selected");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
return inputs[i].value;
}
}
}
function onSubmit() {
var id = get_radio_value();
alert("selected input is: " + id);
}
</script>
</head>
<body>
<form onsubmit="onSubmit();">
<input name="selected" value="1" type="radio"/>1<br/>
<input name="selected" value="2" type="radio"/>2<br/>
<input name="selected" value="3" type="radio"/>3<br/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
I choose let number of code for a required function. The one worked for me is given below from api.jquery.com. Hope this helps others.
HTML
<input type="radio" name="option" value="o1">option1</input>
<input type="radio" name="option" value="o2">option2</input>
JavaScript
var selectedOption = $("input:radio[name=option]:checked").val()
The variable selectedOption will contain the value of the selected radio button (i.e) o1 or o2

Categories