I have multiple checkbox, when i check a checkbox two key value pair will generate.
Like this : Object {id: "101", name: "example"}
This will generate for every checkbox checked and i want for multiple checkbox checked array. look like this :
[{id:"id1",name:"name1"},{id:"id2",name:"name2"}]
What I have done
$('.chkCompare').click(function(event) {
var value = [],
projectName = {},
span = $(this).attr('id'),
value = $('.chkCompare:checked').map(function() {
$('#span' + span).text('ADDED').css({
"color": "green"
});
projectName['id'] = $(this).attr('id');
projectName['name'] = $(this).attr('title');
return value.push(projectName);
}).get();
});
When I uncheck checkbox they will be remove from array and want to prevent check maximum 3 checkbox if >3 then show an alert box.
You can check the length property of :checked checkbox's. Based on your condition and use event.preventDefault() to cancel the default action.
$('.chkCompare').click(function(event) {
var checkedElemets = $('.chkCompare:checked');
if (checkedElemets.length > 3) {
event.preventDefault();
alert('Only 3 checkbox can be checked');
}
var values = checkedElemets.map(function() {
return {
id: this.id,
name: this.title
};
}).get();
console.log(values)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="chkCompare" title='t1' id='i1' />
<input type="checkbox" class="chkCompare" title='t2' id='i2'/>
<input type="checkbox" class="chkCompare" title='t3' id='i3'/>
<input type="checkbox" class="chkCompare" title='t4' id='i4'/>
<input type="checkbox" class="chkCompare" title='t5' id='i5'/>
$("input[type='checkbox']").change(function(){
var arr = {};
var count = 0;
$.each($("input[type='checkbox']:checked"), function(){
if(count++<3){
arr[this.id] =this.name;
}else{
$(this).prop('checked', false);
}
});
console.log(JSON.stringify(arr));
});
Related
I want the checked checkboxes to be unchecked when clicking another button:
Below is the HTML
<input type="checkbox" name="checkb" id="Agent" value="Agent"> type=Agent
<br />
<input type="checkbox" name="checkb" id="Customer" value="Customer"> type=Customer
<br />
<input type="checkbox" name="checkb" id="Phone" value="Phone"> type=Phone
<br />
<input type="checkbox" name="checkb" id="ID_Card" value="ID_Card"> type=ID_Card
<br />
<input type=datetime id="Start_Date" value="" placeholder="Start_Date" />
<input type=datetime id="End_Date" value="" placeholder="End_Date" />
<button id="date">
Interval
</button>
On clicking of the Interval button if any checkboxes are checked they should get unchecked.
Below is the event listener for the Interval button:
var check1 = document.getElementById("Agent");
var check2 = document.getElementById("Customer");
var check3 = document.getElementById("Phone");
var check4 = document.getElementById("ID_Card");
var newBtn = document.getElementById("date");
if (newBtn) {
newBtn.addEventListener("click", function() {
if (check1.checked) {
var ischecked1 = check1.checked;
check1.checked != ischecked1;
}
if (check2.checked) {
var ischecked2 = check2.checked;
check2.checked != ischecked2;
}
if (check3.checked) {
var ischecked3 = check3.checked;
check3.checked != ischecked3;
}
if (check4.checked) {
var ischecked4 = check4.checked;
check4.checked != ischecked4;
}
});
}
Below code runs without any errors, but the boxes do not get unchecked if they are checked.
Below is the fiddle
Your statements are just evaluating as booleans, not performing assignments:
check1.checked != ischecked1; // this returns a boolean, doesn't do any assignment
You want to do this to toggle the checked state:
check1.checked = !ischecked1;
Same thing for other checkboxes.
There's also no need to create the extra variables, you can just do the toggling and reading directly:
check1.checked = !check1.checked;
Since you're only toggling checkboxes when they are checked, you can just directly set them to false as well.
if (check1.checked) check1.checked = false;
Instead of having if statements, you can use array iteration to do the toggling:
[check1, check2, check3, check4].forEach(check => {
if (check.checked) {
check.checked = false;
}
});
// or query the checkboxes directly and do the same
[...document.querySelectorAll('input[type="checkbox"]')].forEach(check => {
if (check.checked) {
check.checked = false;
}
});
Your mistake is in this line:
check1.checked != ischecked1;
This actually means "compare if check1.checked is not equal to ischecked1".
Most simple solution would be to remove the if statement and just do this:
check1.checked = !check1.checked
This means "set check1.checked to the opposite of check1.checked".
Since all checkboxes have the same name you could also collect all checkboxes by requesting them by name and use a loop to walk through them. A small example:
// Collect all checkboxes with a CSS selector that matches all input
// elements with a name attribute that's equal to "checkb"
var checkboxes = document.querySelectorAll('input[name="checkb"]');
var newBtn = document.getElementById("date");
if (newBtn) {
newBtn.addEventListener("click", function() {
// this is a for loop, it will run for as long as i
// is smaller than the amount of found checkboxes (checkboxes.length)
for(var i = 0; i < checkboxes.length; i++) {
// Get the checkbox from the checkboxes collection
// collection[i] means get item from collection with index i
var checkbox = checkboxes[i];
// Revert the .checked property of the checkbox
checkbox.checked = !checkbox.checked;
}
});
}
By the looks of it you just want to uncheck everything on click of button
you can just do this
var newBtn = document.getElementById("date");
if (newBtn) {
newBtn.addEventListener("click", function() {
document.getElementById("Agent").checked =
document.getElementById("Customer").checked =
document.getElementById("Phone").checked =
document.getElementById("ID_Card").checked = false;
});
}
I have a hidden input with different values. I want when checkbox is unchecked to remove-replace value.
<input id="test" type="hidden" name="test" value="4220752209,4220752209,4220752094,4220752094">
I Have a table in whose first column I have a checkbox.
Every time when I click I get the hidden value and store it in input like this
if ($("#test").val() == '') {
//this is my data aData.ordercode
$("#test").val(aData.ordercode);
} else {
$('#test').val($('#test').val() + "," + aData.ordercode);
}
Now I want when I unchecked from table to find and replace the same value if you see my value has same numbers i want when uncheck a checkbox to find and I have doing like this
if ($('input[type=checkbox]').is(':checked')) {
$(this).prop('checked', true);
} else {
$(this).prop('checked', false);
if ($("#test").val().indexOf(aData.ordercode) > -1) {
alert("Yes");
}
Please try these code :-
<input id="checkbox" type="checkbox" value="4220752209"/>
<input id="test" type="hidden" name="test" value="4220752209,4220752219,4220752095,4220752096"/>
$('input[type=checkbox]').on('click',function(){
val = $(this).val();
if($(this).is(':checked')) {
var temp_array = $("#test").val().split(",");
temp_array = jQuery.grep(temp_array, function(value) {
return value != val;
});
$("#test").val(temp_array.join());
}
else {
$("#test").val($("#test").val()+","+val);
}
});
So i have 2 categories of checkboxes.
<input type="checkbox" name="foo" value="val1" />
<input type="checkbox" name="foo" value="val2" />
<input type="checkbox" name="bar" value="val1" />
<input type="checkbox" name="bar" value="val2" />
When a box is checked I want to run a jQuery function that will assign two variables
var foo = //the values of the checked boxes with the foo name
var bar = //the values of the checked boxes with the bar name
So lets say only the first check box was checked in the foo group where as both were checked in the bar group. The groups values would be as follows
var foo = val1;
var bar = val1,val2;
What is the best way to search through all checkboxes that share the same name/class Look to see if they are checked and if so add their value to a string?
You can try something like
var foo = $("input:checkbox[name='foo']:checked").map(function(){
return this.value;
}).get().join(',');
var bar = $("input:checkbox[name='bar']:checked").map(function(){
return this.value;
}).get().join(',');
See a working demo
Get all checked checkboxes :
$(':checkbox').is(':checked').each(function() {
if ($(this).value) {
//get values here
}
});
Get all checkboxes :
$(':checkbox').each(function() {
if ($(this).value) {
//get values here
}
});
jQuery :checked selector to the rescue.
Give your checkboxes a common class, then:
$('.classofcheckbox').each(function() {
if ($(this).val()) {
// do stuff...
}
});
Or more directly
$('.classofcheckbox:checked').each(function() {
// do stuff...
});
function checkedBoxesToString(name) {
var checked = [];
$('[name=' + name + ']:checked').each(function (a, b) {
checked.push($(b).val());
});
return checked.join(",");
}
I have a checkbox in a form and I'd like it to work according to following scenario:
if someone checks it, the value of a textfield (totalCost) should be set to 10.
then, if I go back and uncheck it, a function calculate() sets the value of totalCost according to other parameters in the form.
So basically, I need the part where, when I check the checkbox I do one thing and when I uncheck it, I do another.
Pure javascript:
const checkbox = document.getElementById('myCheckbox')
checkbox.addEventListener('change', (event) => {
if (event.currentTarget.checked) {
alert('checked');
} else {
alert('not checked');
}
})
My Checkbox: <input id="myCheckbox" type="checkbox" />
function calc()
{
if (document.getElementById('xxx').checked)
{
document.getElementById('totalCost').value = 10;
} else {
calculate();
}
}
HTML
<input type="checkbox" id="xxx" name="xxx" onclick="calc();"/>
If you are using jQuery.. then I can suggest the following:
NOTE: I made some assumption here
$('#my_checkbox').click(function(){
if($(this).is(':checked')){
$('input[name="totalCost"]').val(10);
} else {
calculate();
}
});
Use an onclick event, because every click on a checkbox actually changes it.
The following solution makes use of jquery. Let's assume you have a checkbox with id of checkboxId.
const checkbox = $("#checkboxId");
checkbox.change(function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
});
HTML:
<input type="checkbox" onchange="handleChange(event)">
JS:
function handleChange(e) {
const {checked} = e.target;
}
Reference the checkbox by it's id and not with the #
Assign the function to the onclick attribute rather than using the change attribute
var checkbox = $("save_" + fieldName);
checkbox.onclick = function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
};
Javascript
// on toggle method
// to check status of checkbox
function onToggle() {
// check if checkbox is checked
if (document.querySelector('#my-checkbox').checked) {
// if checked
console.log('checked');
} else {
// if unchecked
console.log('unchecked');
}
}
HTML
<input id="my-checkbox" type="checkbox" onclick="onToggle()">
try
totalCost.value = checkbox.checked ? 10 : calculate();
function change(checkbox) {
totalCost.value = checkbox.checked ? 10 : calculate();
}
function calculate() {
return other.value*2;
}
input { display: block}
Checkbox: <input type="checkbox" onclick="change(this)"/>
Total cost: <input id="totalCost" type="number" value=5 />
Other: <input id="other" type="number" value=7 />
I know this seems like noob answer but I'm putting it here so that it can help others in the future.
Suppose you are building a table with a foreach loop. And at the same time adding checkboxes at the end.
<!-- Begin Loop-->
<tr>
<td><?=$criteria?></td>
<td><?=$indicator?></td>
<td><?=$target?></td>
<td>
<div class="form-check">
<input type="checkbox" class="form-check-input" name="active" value="<?=$id?>" <?=$status?'checked':''?>>
<!-- mark as 'checked' if checkbox was selected on a previous save -->
</div>
</td>
</tr>
<!-- End of Loop -->
You place a button below the table with a hidden input:
<form method="post" action="/goalobj-review" id="goalobj">
<!-- we retrieve saved checkboxes & concatenate them into a string separated by commas.i.e. $saved_data = "1,2,3"; -->
<input type="hidden" name="result" id="selected" value="<?= $saved_data ?>>
<button type="submit" class="btn btn-info" form="goalobj">Submit Changes</button>
</form>
You can write your script like so:
<script type="text/javascript">
var checkboxes = document.getElementsByClassName('form-check-input');
var i;
var tid = setInterval(function () {
if (document.readyState !== "complete") {
return;
}
clearInterval(tid);
for(i=0;i<checkboxes.length;i++){
checkboxes[i].addEventListener('click',checkBoxValue);
}
},100);
function checkBoxValue(event) {
var selected = document.querySelector("input[id=selected]");
var result = 0;
if(this.checked) {
if(selected.value.length > 0) {
result = selected.value + "," + this.value;
document.querySelector("input[id=selected]").value = result;
} else {
result = this.value;
document.querySelector("input[id=selected]").value = result;
}
}
if(! this.checked) {
// trigger if unchecked. if checkbox is marked as 'checked' from a previous saved is deselected, this will also remove its corresponding value from our hidden input.
var compact = selected.value.split(","); // split string into array
var index = compact.indexOf(this.value); // return index of our selected checkbox
compact.splice(index,1); // removes 1 item at specified index
var newValue = compact.join(",") // returns a new string
document.querySelector("input[id=selected]").value = newValue;
}
}
</script>
The ids of your checkboxes will be submitted as a string "1,2" within the result variable. You can then break it up at the controller level however you want.
<li>
<input type= "checkbox" name="paradigm" id="id_1" value="3"/>
<label for="name_3">foo</label>
</li>
<li>
<input type= "checkbox" name="paradigm" id="id_2" value="4"/>
<label for="name_4">bar</label>
</li>
Here is two checkbox. If I checked checkbox id_1, using jquery I want to read the label foo. If I checked both then it should be ['foo','bar'].
$("input:checkbox:checked").map(function(){
return $(this).next().text();
}).get();
See a working demo
As long as the <label> elements immediately follow their <input> elements, then you can do something like this:
var a = [ ];
$('input[name=paradigm]:checked').next('label').each(function() {
a.push($(this).text());
});
A better solution would be to set proper for attributes on your label elements (i.e. make sure they match up with the id attributes on their checkboxes) and then:
var a = [ ];
$('input[name=paradigm]:checked').each(function() {
a.push($('label[for=' + this.id + ']').text());
});
var checkedLabels = [];
$(':checkbox').each(function() {
if (this.checked) {
var label = $('label[for="' + this.id + '"]').text();
checkedLabels.push(label);
}
});
Try this one:
var vSring = "";
$("input:checkbox[name='paradigm']").click(function(){
if($("input:checkbox[name='paradigm']").filter(":checked").length==2)
{
vSring="";
$("input:checkbox[name='paradigm']").each(function(){
var vText = $(this).next().text();
if(vSring=="")
vSring = vText+",";
else
vSring = vSring+vText+",";
});
alert(vSring);
}
else
{
if($(this).is(":checked"))
{
vSring="";
vSring=$(this).next().text();
alert(vSring);
}
}
});
CLICK HERE TO SEE THE DEMO