I want to check if the checkbox is checked or no.
I have the following code:
<div class="checkbox">
#Html.HiddenFor(model => model.VehicleTypeSelected)
#Html.ValidationMessageFor(model => model.VehicleTypeSelected)
<br>
#foreach (VehicleType vt in ViewBag.VehicleTypes)
{
<label><input type="checkbox" value="#vt.VehicleTypeID" name="VehicleTypeIds" class="vehicle-type-selector" /> #vt.Name
<br></label>
}
I want to use this approach:
$('#checkBoxForm :checkbox').click(function() {
var $this = $(this);
if ($this.is(':checked')) {
// the checkbox was checked
} else {
// the checkbox was unchecked
}
});
if the checkbox (isUniversal) is checked, I want to disable all the checkboxes(vehicleTypes)
You can check if any vehicle type is checked, using just this:
$(function(){
var isAnyVehicleTypeChecked = $(".vehicle-type-selector").is(":checked").length > 0
});
Furthermore, using the following
$(function(){
var checkedVehicleTypes = $(".vehicle-type-selector").is(":checked");
});
you can pick all the checkboxes that has the class vehicle-type-selector and they are checked.
if( $('.vehicle-type-selector').is(":checked") ){
// Do something
}
use the attr() function
Try (assuming isUniversal is a class ):
$(".isUniversal").on('click',function(){
if ($("this").attr('checked') == 'checked') {
$('.vehicle-type-selector').removeAttr('checked').attr('disabled','disabled');
}
})
or
$(".isUniversal").on('click',function(){
if( $('this').is(":checked") ){
$('.vehicle-type-selector').removeAttr('checked').attr('disabled','disabled');
}
})
Related
I have some number fields set based on a large number of factors in an eCommerce site. I want an option that will clear out those numbers if a radio option is clicked, but then return to their previous numbers if a different radio option is clicked. I have the following code to set the values to 0, but I dont know how to continue for setting them back. My values are defined in several different places, so I can't easily refer to them, but is there a way to read the fields before they're set to 0, and then set them back to their previous state?
$('input[type="radio"]').click(function() {
if($(this).attr('id') == 'yes-option') {
$('#option1').val('0');
$('#option2').val('0');
$('#option3').val('0');
$('#option4').val('0');
}
else if($(this).attr('id') == 'no-option') {
???
}
You can use data-attributes to store the previously entered/selected value:
$('input[type="radio"]').click(function() {
var $optionOne = $('#option1');
var $optionTwo = $('#option2');
var $optionThree = $('#option3');
var $optionFour = $('#option4');
if($(this).attr('id') == 'yes-option') {
$optionOne.data('previous-value', $optionOne.val());
$optionOne.val('0');
$optionTwo.data('previous-value', $optionTwo.val());
$optionTwo.val('0');
$optionThree.data('previous-value', $optionThree.val());
$optionThree.val('0');
$optionFour.data('previous-value', $optionFour.val());
$optionFour.val('0');
} else if($(this).attr('id') == 'no-option') {
$optionOne.val($optionOne.data('previous-value'));
$optionTwo.val($optionTwo.data('previous-value'));
$optionThree.val($optionThree.data('previous-value'));
$optionFour.val($optionFour.data('previous-value'));
}
});
A possible approach would be to always keep your options' previous state in an array.
var previousStates = [];
$('input[type="radio"]').click(function() {
if($(this).attr('id') == 'yes-option') {
$.saveState(); //Save the current state before changing values
$( "option" ).each(function( index ) {
$(this).val('0');
});
}
else if($(this).attr('id') == 'no-option') {
$.restoreState();
}
});
$.saveState = function() {
previousStates = []; //Empty the array
$( "option" ).each(function( index ) {
previousStates[index] = $(this).val();
});
}
$.restoreState = function() {
$( "option" ).each(function( index ) {
$(this).val(previousStates[index]);
});
}
Note: as this method uses indexes to identify options, be careful if you need to dynamically add or remove an option!
Use data-attributes to store the old values, so you can read them later on.
It's better to use a loop to go trough each element, so you don't need to modify it every time a new input field was added.
You can also change the selector to $('input') or anything that suit your needs.
$('input[type="radio"]').click(function() {
if($(this).attr('id') == 'yes-option') {
$('[id^="option"]').each(function(){
$(this).data('oldval', $(this).val());
$(this).val(0);
});
}
else if($(this).attr('id') == 'no-option') {
$('[id^="option"]').each(function(){
$(this).val($(this).data('oldval'));
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input name="clr" type="radio" id="yes-option">
<span>YES</span>
</label>
<label>
<input name="clr" type="radio" id="no-option">
<span>NO</span>
</label>
<div>
<input type="number" id="option1" value="15">
</div>
<div>
<input type="number" id="option2" value="23">
</div>
<div>
<input type="number" id="option3" value="100">
</div>
<div>
<input type="number" id="option4" value="86">
</div>
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));
});
I want to use jQuery to see if three text boxes are changed so I can send data through AJAX.
I tried a simple script:
$("#name, #position, #salary").change(function()
{
console.log("All data are changed");
});
Where name, position and salary are the respective IDs of three text box.
The result was that when I change the first one:
And when I changed the second:
And here is the third one:
So, I've got the message when separately each text box is changed. What I do need is when the three are changed, display the message. I am new to jQuery, so I want to know if I can use something like IF ... AND ... AND in jQuery.
A lot of validation frameworks have the concept of a dirty input once a user has changed the value. You could implement this and check when all your fields are dirty.
$("#name, #position, #salary").change(function() {
this.classList.add("dirty");
if ($(".dirty").length === 3) {
console.log("All data are changed");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="name" />
<input id="position" />
<input id="salary" />
We can abstract this out into a jQuery plugin for re-usability
$.fn.allChange = function(callback) {
var $elements = this;
$elements.change(function() {
this.classList.add("dirty");
if (callback && $elements.filter(".dirty").length === $elements.length) {
callback.call($elements);
}
});
return $elements;
}
$("#name, #position, #salary").allChange(function() {
console.log("All data are changed");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="name" />
<input id="position" />
<input id="salary" />
You can store changed inputs in an array, and check it's length to detect if all of them where changed.
var changedInputs = [];
$("#name, #position, #salary").change(function()
{
changedInputs.push(this.id);
if(changedInputs.length === 3) {
alert('All 3 inputs where changed!');
}
});
You can try:
var changedInputs = [];
$("#name, #position, #salary").change(function()
{
if !(changedInputs.include(this.id) ){
changedInputs.push(this.id);
if(changedInputs.length == 3) {
alert('All 3 inputs where changed!');
}
});
You can also use this approach. Fiddle
var isNameChanged, isPositionChanged, isSalaryChanged = false;
function fieldsChanged()
{
var id = $(this).attr('id');
if (id == 'name') isNameChanged = true;
else if (id == 'position') isPositionChanged = true;
else if (id == 'salary') isSalaryChanged = true;
if (isNameChanged && isPositionChanged && isSalaryChanged) {
console.log('All have been changed');
isNameChanged = isPositionChanged = isSalaryChanged = false;
}
}
$(function(){
$('#name, #position, #salary').change(fieldsChanged);
});
Try using a class:
<input class="need">
<input class="need">
<input class="need">
$(".need").change(function()
{
var all = 0;
$(".need").each(function(i,v){
if ($(v).val().length >0 ) {
all+=1;
}
});
if(all.length == 3) {
alert('All 3 inputs where changed!');
}
});
Store the multiple selectors in a variable. On .change() loop through the elements in the multiple selector to test the input values. If all inputs have content an additional function can be called.
$(document).ready(function(){
var $selectors = $('#input1, #input2, #input3');
$selectors.change(function(){
var allChanged = true;
console.log($(this).attr('id') + ' was changed.');
$selectors.each(function(){
if ($(this).val() == '') {
allChanged = false;
}
});
if (allChanged) {
// $().ajax();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input1">
<input id="input2">
<input id="input3">
one possible solution:
var needed = ["name", "position", "salary"];
$("#name, #position, #salary").change(function()
{
if(needed.length == 0) return;
needed.splice(needed.indexOf($(this).attr('id')), 1);
if(needed.length == 0)
console.log("All data are changed");
});
first, you need to init the array "needed" to all required fields
then, when a field is changed, you remove that field from the needed array
once the array is empty, all required values are changed ;)
the first condition is to ensure not to log the message more than once
You can compare current input value to default one, then the logic could be like following:
btw, i set a common class for all inputs to check, because this is how it should be done imho...
$('.inputToCheck').on('change', function() {
var allInputsChanged = !$('.inputToCheck').filter(function() {
return this.value === this.defaultValue;
}).length;
if (allInputsChanged) alert('All inputs changed!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="name" class="inputToCheck">
<input id="position" class="inputToCheck">
<input id="salary" class="inputToCheck">
So I've got code that looks like this:
<input class="messageCheckbox" type="checkbox" value="3" name="mailId[]">
<input class="messageCheckbox" type="checkbox" value="1" name="mailId[]">
I just need Javascript to get the value of whatever checkbox is currently checked.
EDIT: To add, there will only be ONE checked box.
None of the above worked for me but simply use this:
document.querySelector('.messageCheckbox').checked;
For modern browsers:
var checkedValue = document.querySelector('.messageCheckbox:checked').value;
By using jQuery:
var checkedValue = $('.messageCheckbox:checked').val();
Pure javascript without jQuery:
var checkedValue = null;
var inputElements = document.getElementsByClassName('messageCheckbox');
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
checkedValue = inputElements[i].value;
break;
}
}
I am using this in my code.Try this
var x=$("#checkbox").is(":checked");
If the checkbox is checked x will be true otherwise it will be false.
in plain javascript:
function test() {
var cboxes = document.getElementsByName('mailId[]');
var len = cboxes.length;
for (var i=0; i<len; i++) {
alert(i + (cboxes[i].checked?' checked ':' unchecked ') + cboxes[i].value);
}
}
function selectOnlyOne(current_clicked) {
var cboxes = document.getElementsByName('mailId[]');
var len = cboxes.length;
for (var i=0; i<len; i++) {
cboxes[i].checked = (cboxes[i] == current);
}
}
This does not directly answer the question, but may help future visitors.
If you want to have a variable always be the current state of the checkbox (rather than having to keep checking its state), you can modify the onchange event to set that variable.
This can be done in the HTML:
<input class='messageCheckbox' type='checkbox' onchange='some_var=this.checked;'>
or with JavaScript:
cb = document.getElementsByClassName('messageCheckbox')[0]
cb.addEventListener('change', function(){some_var = this.checked})
$(document).ready(function() {
var ckbox = $("input[name='ips']");
var chkId = '';
$('input').on('click', function() {
if (ckbox.is(':checked')) {
$("input[name='ips']:checked").each ( function() {
chkId = $(this).val() + ",";
chkId = chkId.slice(0, -1);
});
alert ( $(this).val() ); // return all values of checkboxes checked
alert(chkId); // return value of checkbox checked
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="checkbox" name="ips" value="12520">
<input type="checkbox" name="ips" value="12521">
<input type="checkbox" name="ips" value="12522">
Use this:
alert($(".messageCheckbox").is(":checked").val())
This assumes the checkboxes to check have the class "messageCheckbox", otherwise you would have to do a check if the input is the checkbox type, etc.
<input class="messageCheckbox" type="checkbox" onchange="getValue(this.value)" value="3" name="mailId[]">
<input class="messageCheckbox" type="checkbox" onchange="getValue(this.value)" value="1" name="mailId[]">
function getValue(value){
alert(value);
}
None of the above worked for me without throwing errors in the console when the box wasn't checked so I did something along these lines instead (onclick and the checkbox function are only being used for demo purposes, in my use case it's part of a much bigger form submission function):
function checkbox() {
var checked = false;
if (document.querySelector('#opt1:checked')) {
checked = true;
}
document.getElementById('msg').innerText = checked;
}
<input type="checkbox" onclick="checkbox()" id="opt1"> <span id="msg">Click The Box</span>
If you're using Semantic UI React, data is passed as the second parameter to the onChange event.
You can therefore access the checked property as follows:
<Checkbox label="Conference" onChange={(e, d) => console.log(d.checked)} />
Surprised to see no working vanilla JavaScript solutions here (the top voted answer does not work when you follow best practices and use different IDs for each HTML element). However, this did the job for me:
Array.prototype.slice.call(document.querySelectorAll("[name='mailId']:checked"),0).map(function(v,i,a) {
return v.value;
});
If you want to get the values of all checkboxes using jQuery, this might help you. This will parse the list and depending on the desired result, you can execute other code. BTW, for this purpose, one does not need to name the input with brackets []. I left them off.
$(document).on("change", ".messageCheckbox", function(evnt){
var data = $(".messageCheckbox");
data.each(function(){
console.log(this.defaultValue, this.checked);
// Do something...
});
}); /* END LISTENER messageCheckbox */
pure javascript and modern browsers
// for boolean
document.querySelector(`#isDebugMode`).checked
// checked means specific values
document.querySelector(`#size:checked`)?.value ?? defaultSize
Example
<form>
<input type="checkbox" id="isDebugMode"><br>
<input type="checkbox" value="3" id="size"><br>
<input type="submit">
</form>
<script>
document.querySelector(`form`).onsubmit = () => {
const isDebugMode = document.querySelector(`#isDebugMode`).checked
const defaultSize = "10"
const size = document.querySelector(`#size:checked`)?.value ?? defaultSize
// 👇 for defaultSize is undefined or null
// const size = document.querySelector(`#size:checked`)?.value
console.log({isDebugMode, size})
return false
}
</script>
Optional_chaining (?.)
You could use following ways via jQuery or JavaScript to check whether checkbox is clicked.
$('.messageCheckbox').is(":checked"); // jQuery
document.getElementById(".messageCheckbox").checked //JavaScript
To obtain the value checked in jQuery:
$(".messageCheckbox").is(":checked").val();
In my project, I usually use this snippets:
var type[];
$("input[name='messageCheckbox']:checked").each(function (i) {
type[i] = $(this).val();
});
And it works well.
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.