Check random checkboxes using JQuery - javascript

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);
}
});

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>

How i can Do dynamic checkboxes for java jsp?

i need to do six checkboxes for one image , and this image need to change if one or more checkboxes is cheked , how i can do it? please help me , i attach my code.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<img src="img/fotodiente/1.jpg" width="78" height="107" alt="1" id="diente1" onclick="changeImage1()"/>
<form name="form1" onsubmit="checkBoxValidation()">
<p><input type="checkbox" name="chbdiente1" value="1"/>Vestibular</p>
<p><input type="checkbox" name="chbdiente1" value="2"/>Mesial</p>
<p><input type="checkbox" name="chbdiente1" value="3"/>Oclusal</p>
<p><input type="checkbox" name="chbdiente1" value="4"/>Distal</p>
<p><input type="checkbox" name="chbdiente1" value="5"/>Palatino</p>
<p><input type="checkbox" name="chbdiente1" value="6"/>Lingual</p>
<p><input type="submit" value="submit"/>
</form>
<%String chbdiente1[] = request.getParameterValues("chbdiente1");
if (chbdiente1 != null) {%>
<script>
function changeImage1() {
var image = document.getElementById('diente1');
image.src = "img/fotodiente/1.1.jpg";
}
;
</script>
<ul><%for (int i = 0; i < chbdiente1.length; i++) {%>
<li><%=chbdiente1[i]%></li><%}%>
</ul><%}%>
</body>
</html>
i have this code and send me the value of selected checkboxes , but the image not change. help please. thanks
If you want to change the image after click of checkboxes you need to call changeImage1() into onchange or onclick method of checkbox.
Example:
<script>
$('document').ready(function(){
$('input[type="checkbox"]').click(function(){
changeImage1();
});
});
function changeImage1() {
var image = document.getElementById('diente1');
image.src = "img/fotodiente/1.1.jpg";
}
</script>
function changeImage1() {
var image = document.getElementById('diente1');
var checkboxes = document.getElementById("form1");
var cont = 0;
try {
for (var x = 0; x < checkboxes.length; x++) {
if (checkboxes[x].checked) {
cont = cont + 1;
}
}
} catch (e) {
}
try {
if (cont > 0) {
image.src = "img/fotodiente/1.1.jpg";
d1 = 2;
array.push("Pieza 1");
var chb2 = document.getElementsByName("form1");
} else if (cont === 0) {
image.src = "img/fotodiente/1.jpg";
d1 = 1;
array.splice(1, 1);
}
} catch (e) {
}
}
;
<img src="img/fotodiente/1.jpg" class="item_thumb" width="78" height="107" alt="1" id="diente1" onclick="changeImage1()"/>
<form id="form1" method="post" action="">
<input type="checkbox" id="chbdiente1" value="1" onclick="changeImage1();" /><label>Vestibular</label>
<input type="checkbox" id="chbdiente1" value="2" onclick="changeImage1();" /><label>Mesial</label>
<input type="checkbox" id="chbdiente1" value="3" onclick="changeImage1();" /><label>Oclusal</label>
<input type="checkbox" id="chbdiente1" value="4" onclick="changeImage1();" /><label>Distal</label>
<input type="checkbox" id="chbdiente1" value="5" onclick="changeImage1();" /><label>Palatino</label>
<input type="checkbox" id="chbdiente1" value="6" onclick="changeImage1();" /><label>Lingual</label>
<input type="button" name="Submit" value="Contar" hidden="">
</form>
Well, this changes the image when there are 1 or more checkboxes clicked, if all the checkboxes are unchecked the image returns to the first one.
I hope also I can help others and thanks

Checkbox alert, select max 4 items

I have a form with checkboxes. Max 4 items needs to be selected. If selecting more then an Alert pops up. I have it working when I use the same name="" but that really needs to be different. Anyone knows how to do this?
The script I have: (ckb needs to be ckb1 + ckb2 + ckb3...)
function chkcontrol(j) {
var total=0;
for(var i=0; i < document.form1.ckb.length; i++){
if(document.form1.ckb[i].checked){
total =total +1;}
if(total > 4){
alert("Selecteer a.u.b. maximaal 4 workshops")
document.form1.ckb[j].checked = false ;
return false;
}
}
}
My form html code:
<form enctype="application/x-www-form-urlencoded" method="post" name="form1">
<span>Workshops selection: (max 4)</span><br><br>
<input type="checkbox" name="ckb1" value="blabla first" onclick='chkcontrol(0)'; /> blabla first<br>
<input type="checkbox" name="ckb2" value="blabla 2" onclick='chkcontrol(1)'; /> blabla 2<br>
<input type="checkbox" name="ckb3" value="blabla 3" onclick='chkcontrol(2)'; /> blabla 3<br>
<input type="checkbox" name="ckb4" value="blabla 4" onclick='chkcontrol(3)'; /> blabla 4<br>
<input type="checkbox" name="ckb5" value="blabla 5" onclick='chkcontrol(4)'; /> blabla 5<br>
<input type="checkbox" name="ckb6" value="blabla 6" onclick='chkcontrol(5)'; /> blabla 6<br>
<input type="checkbox" name="ckb7" value="blabla 7" onclick='chkcontrol(6)'; /> blabla 7<br>
<input class="btn" class="cursor" name="Sent" type="submit" value="Sent" />
</form>
My fiddle: https://jsfiddle.net/usq2aeLL/1/
Working one but needs different name="xxx": https://jsfiddle.net/usq2aeLL/2/
Use a common class to select the elements instead
<input type="checkbox" name="ckb1" class="myBox" value="blabla first" />
and then
function chkcontrol() {
var total = 0;
var elems = document.querySelectorAll('.myBox');
for (var i = 0; i < elems.length; i++) {
if (elems[i].checked) {
total = total + 1;
}
if (total > 4) {
alert("Selecteer a.u.b. maximaal 4 workshops")
elems.checked = false;
return false;
}
}
}
FIDDLE
Preferably you'd swap out the inline event handlers with addEventListener as well.

Multiplying text put value with the sum of check box values and display it on a paragraph

I'm trying to multiply the entered text input value with the sum of check box values clicked. So far when you click the check boxes the sumof their avues is displayed instantly on the span emlement with id="Totalcost"....i need some help figuring out how i could multiply the sum of check box selected with the value entered in the text input field.
If it can be easily done using JQuery i will really appreciate
Thanks in advance.
Here is my code
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
var total = 0;
inputBox.onkeyup = function(){
document.getElementById('Totalcost').innerHTML = inputBox.value;
}
function test(item){
var inputBox = document.getElementById('chatinput');
if(item.checked){
total+= parseInt(item.value);
}else{
total-= parseInt(item.value);
}
//alert(total);
document.getElementById('Totalcost').innerHTML = total ;
}
</script>
</head>
<body>
<input type="text" id="chatinput" onchange="myFunction()"><br>
<p id="printchatbox"></p>
<div id="container">
<p id="printc"></p>
<input type="checkbox" name="channcost" value="10" onClick="test(this);" />10<br />
<input type="checkbox" name="chanlcost" value="20" onClick="test(this);" />20 <br />
<input type="checkbox" name="chancost" value="40" onClick="test(this);" />40 <br />
<input type="checkbox" name="chanlcost" value="60" onClick="test(this);" />60 <br />
</div>
Total Amount : <span id="Totalcost"> </span><BR><BR><BR>
</body>
</html>
You have many incongruences in your code.....
Replace it with this:
<!DOCTYPE HTML>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
var total = 0;
function test(){
var checkboxes = document.getElementById('container').getElementsByTagName("input");
var box_value = parseInt(document.getElementById('chatinput').value);
var new_total = 0;
for(var i=0; i<checkboxes.length; i++){
var item = checkboxes[i];
if(item.checked){
new_total += parseInt(item.value);
}
}
if(box_value>0){ total = (new_total>0?new_total:1) * box_value; }
else{ total = new_total; }
document.getElementById('Totalcost').innerHTML = total ;
}
</script>
</head>
<body>
<input type="text" id="chatinput" onchange="test()"><br>
<p id="printchatbox"></p>
<div id="container">
<p id="printc"></p>
<input type="checkbox" name="channcost" value="10" onClick="test();" />10<br />
<input type="checkbox" name="chanlcost" value="20" onClick="test();" />20 <br />
<input type="checkbox" name="chanlcost" value="40" onClick="test();" />40 <br />
<input type="checkbox" name="chanlcost" value="60" onClick="test();" />60 <br />
</div>
Total Amount : <span id="Totalcost"> </span><BR><BR><BR>
</body>
</html>
I changed your script to make these changes
var total = 0;
function test(item){
var inputBox = document.getElementById('chatinput');
if(item.checked){
total+= parseInt(item.value);
}else{
total-= parseInt(item.value);
}
inputValue = $("#chatinput").val();
textValue = (isNaN(inputValue)) ? 1 : parseInt(inputValue);
if(textValue == "NaN"){
textValue = 1;
}
totalAfterMul = total*textValue;
console.log(totalAfterMul);
document.getElementById('Totalcost').innerHTML = totalAfterMul ;
}
It will do what is desired.
It takes the input value and then multiply it with the sum of the check boxes. If the input value is not a number then it will consider it as 1
inputValue = $("#chatinput").val();
textValue = (isNaN(inputValue)) ? 1 : parseInt(inputValue);
if(textValue == "NaN"){
textValue = 1;
}
totalAfterMul = total*textValue;

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