Checkbox check or uncheck value null - javascript

I'm trying to set the value of a checkbox, if checked the value is active, but if unchecked the value is disabled.
The next code works for text, the text changes when the checkbox is checked or unchecked, but the value that is posted to the database is null when the checkbox is unchecked.
HTML
<input type="checkbox" name="cat_status" class="inline checkbox" id="checkbox" checked value="active" onclick="cat_check()">
<label id="text" style="display:Active">Active</label>
JS
function cat_check() {
var checkBox = document.getElementById('checkbox');
var text = document.getElementById('text');
if (checkBox.checked == false) {
text.style.display = "inline";
document.getElementById('checkbox').value = "active";
} else {
text.style.display = "none";
document.getElementById('checkbox').value = "disable";
}
}
I expect the value posted to database to be disabled when the checkbox is unchecked, but currently getting a null.
Update:
Added a fixed version including the AJAX call based on the provided feedback of the answers. This is just in case someone fall into the same issue.
If you play with the example on the bottom of serialize() documentation you will see that value is not appended for checkboxs that are uncheked. You will have to do it manually. Maybe this can help you: how can I override jquery's .serialize to include unchecked checkboxes
HTML
<form method="post" class="add_sub_categories">
<input type="checkbox" name="cat_status" class="inline checkbox" id="checkbox" checked value="active" onclick="cat_check()">
<label id="text" style="display:Active">Active</label>
<a class="btn btn-xs btn-info save_main_cat">GO!</a>
</form>
JS
function cat_check() {
var checkBox = document.getElementById('checkbox');
var text = document.getElementById('text');
if (checkBox.checked == true) {
text.style.display = "inline";
} else {
text.style.display = "none";
}
}
AJAX
$(document).ready(function() {
$(".save_main_cat").click(function() {
var data = $('.add_main_categories').serialize();
/* This code will include the value for the checkbox when unchecked */
$(".add_main_categories input:checkbox:not(:checked)").each(function(e) {
data += "&"+this.name+'=disable';
});
$.ajax({
type: 'POST',
url: "<?= base_url() ?>admin_ajx/categories_ajx/update_main_categories",
data: data,
success: function() {
$('#addCat').modal('hide');
$(".add_main_categories")[0].reset();
dttable.destroy();
$(document).ready(function() {
main_cat(), main_cat_option(), dt_tables();
});
}
});
});
});

If I understood correctly, the problem is on your click handler. When you unchek the checkbox by clicking on it, the checked property will be false when you observe it inside the click handler. And you are doing this:
if (checkBox.checked == false)
{
text.style.display = "inline";
document.getElementById('checkbox').value = "active";
}
So, in other words, you are setting the value to active when the checkbox is unchecked, but instead, that setting should be associated to checked state equal to true. I believe you are looking for something like this:
function cat_check()
{
var checkBox = document.getElementById('checkbox');
var text = document.getElementById('text');
if (checkBox.checked === true)
{
text.style.display = "inline";
checkBox.value = "active";
}
else
{
text.style.display = "none";
checkBox.value = "disable";
}
console.log(checkBox.value);
}
.as-console {background-color:black !important; color:lime;}
<input type="checkbox" name="cat_status" class="inline checkbox" id="checkbox" checked value="active" onclick="cat_check()">
<label id="text" style="display:inline">Active</label>
There are other fixs on the code also:
A) The initial display:Active is not a valid CSS configuration in reference to <label id="text" style="display:Active">Active</label>. So I changed it to display:inline.
B) Use the already defined variable checkBox inside the click handler instead of doing multiple calls to document.getElementById('checkbox').

You can set value 1 , as if it is checked then value posts 1 otherwise can checked null or not;
// In view
//On post time you can check if value is 1 then cheked otherwise null

Related

How to set radio button value as checked or unchecked situation

<input type="radio" name="imgsel" value="" checked />
My requirement is : This radio button by default checked then value of this button is 'present'. When this button is unchecked , then value this button is 'absent'.
how can i do this?
please, help me .
Thanks in advance .
function valChange(element)
{
if (element.checked)
{
alert("present");
} else
{
alert("absent");
}
}
<input id="button" type="checkbox" name="imgsel"
onchange="valChange(this)" value="" checked />
The following example replaces the value of the checkbox when clicked.
First the click event must be bound to the checkbox. The EventHandler checks whether the box has already been checked. If not, it checks it and sets the value in the checkbox. And if it has not been checked, the other way round.
let i = document.querySelector('input');
i.addEventListener('click', (ev) => {
let el = ev.target;
if (el.getAttribute('checked') === null) {
el.setAttribute('checked', true);
el.value = "present"
} else {
el.removeAttribute('checked');
el.value = "absent"
}
let checkValue = document.querySelector('input').value
alert(checkValue)
})
<input type="radio" name="imgsel" value="" checked />

JavaScript button that changes the value in the checkbox field

I am trying to create a button that when clicked replaces the value in the field true false. If we click the first time the field becomes true, if the second time the field becomes false. But I still can't get the results. The field only changes true.
Checkbox: <input type="checkbox" id="myCheck">
<button onclick="check()">Check Checkbox</button>
<script>
function check() {
var value = document.getElementById("myCheck");
if (value = "false") {
document.getElementById("myCheck").checked = true;
} else {
document.getElementById("myCheck").checked = false;
}
}
</script>
Avoid inline handlers ("onclick"). You can simplify this using:
const checkUncheck = () => {
const cb = document.querySelector("#myCheck");
cb.checked = !cb.checked;
};
document.querySelector("button").addEventListener("click", checkUncheck);
<input type="checkbox" id="myCheck" disabled>
<button>check/uncheck</button>
You need to check if the checked attribute of your checkbox is true or false.
Checkbox: <input type="checkbox" id="myCheck">
<button onclick="check()">Check Checkbox</button>
<script>
function check() {
var checkbox = document.getElementById("myCheck");
if (checkbox.checked !== true) {
checkbox.checked = true;
} else {
checkbox.checked = false;
}
}
</script>
Also, you can re-use the checkbox variable.

Get value from textbox based on checkbox on change event

I have two textboxes and one checkbox in a form.
I need to create a function javascript function for copy the first txtbox value to second textbox on checkbox change event.
I use the following code but its shows null on first time checkbox true.
function ShiptoBill()
{
var billing = document.getElementById("txtbilling").value;
var shipping = document.getElementById("txtshipping").value;
var check = // here i got checkbox checked or not
if(check == true)
{
// here I need to add the txtbilling value to txtshipping
}
}
Given that form controls can be accessed as named properties of the form, you can get a reference to the form from the checkbox, then conditionally set the value of txtshipping to the value of txtbilling depending on whether it's checked or not, e.g.:
<form>
<input name="txtbilling" value="foo"><br>
<input name="txtshipping" readonly><br>
<input name="sameas" type="checkbox" onclick="
this.form.txtshipping.value = this.checked? this.form.txtbilling.value : '';
"><br>
<input type="reset">
</form>
Of course you might want to set the listener dynamically, the above just provides a hint. You could also conditionally copy the contents over if the user changes them and the checkbox is checked, so a change event listener on txtbilling may be required too.
Try like following.
function ShiptoBill() {
var billing = document.getElementById("txtbilling");
var shipping = document.getElementById("txtshipping");
var check = document.getElementById("checkboxId").checked;
if (check == true) {
shipping.value = billing.value;
} else {
shipping.value = '';
}
}
<input type="text" id="txtbilling" />
<input type="text" id="txtshipping" />
<input type="checkbox" onchange="ShiptoBill()" id="checkboxId" />
function ShiptoBill()
{
var billing = document.getElementById("txtbilling");
var shipping = document.getElementById("txtshipping");
var check = document.getElementById("checkboxId").checked; // replace 'checkboxId' with your checkbox 'id'
if (check == true)
{
shipping.value = billing.value;
}
}
To get the event when it changes, do
$('#checkbox1').on('change',function() {
if($(this).checked) {
$('#input2').val($('#input1').val());
}
});
This checks for the checkbox to have a change, then checks if it is checked. If it is, it places the value of Input Box 1 into the value of Input Box 2.
EDIT: Here's a pure JS solution, and a JSBin too.
function ShiptoBill()
{
var billing = document.getElementById("txtbilling").value;
var shipping = document.getElementById("txtshipping").value;
var check = document.getElementById("thischeck").checked;
console.log(check);
if(check == true)
{
console.log('checked');
document.getElementById("txtshipping").value = billing;
} else {
console.log('not checked');
}
}
with
<input id="thischeck" type="checkbox" onclick="ShiptoBill()">

How to disable a text-box when clicking on other radio-buttons using a single function in javaScript?

I want to disable the text-box (its id is text1), when clicking on other radio buttons using a single function. According to my code the text-box is showing when the user is clicking on the radio button (its id is rd_other). But when the user clicking on the other radio buttons, after clicking the above radio button (its id is rd_other) the text-box is not disabling.
Here is HTML my code.
<input type="radio" name="rd_other" id="rd_other" value="rd_other" data-toggle="radio" onchange="enableText()">Other (please specify)
<input type="text" name="text1" id="text1"class="form-control input-sm jfl" readonly="readonly" style="display: none;"/>
<input type="radio" name="rdn1" id="rdn1" value="rdn1" data-toggle="radio">I haven't received the disc
<input type="radio" name="rdn2" id="rdn2" value="rdn2" data-toggle="radio">I lost or damaged the protective cover
Here is my javaScript code.
function enableText() {
var text1 = document.getElementById('text1');
text1.readOnly = false;
text1.style.display = 'block';
}
Firstly, to make sure there are no confusions, onchange will only fire when a radio button is selected.
Secondly, you would have to hook up an onchange function to the two other radio buttons. The function below should work.
function disableText() {
var text1 = document.getElementById('text1');
text1.readOnly = true;
text1.style.display = 'none';
}
like this
function disable() {
//one radio button
var radio = document.getElementById("your_radio_button_id");
var checkbox = document.getElementById("your_checkbox_id");
if (radio.checked == true) {
checkbox.disabled = true;
}
}
or like this
function disable() {
var radios = document.getElementsByName("your_radio_button_group_name");
var checkbox = document.getElementById("your_checkbox_id");
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked == true) {
checkbox.disabled = true;
}
}
}
You can fix this like this:
window.enableText = function(e) {
var text1 = document.getElementById('text1');
if(e.id == "rd_other2") {
text1.readOnly = false;
text1.style.display = 'block';
}
else{
text1.readOnly = true;
text1.style.display = 'none';
}
}
please check the full example here :)

Javascript checkbox onChange

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.

Categories