<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 />
Related
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
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()">
I am modifying a functionality in which save button should only get enabled if any pre selected value get changed . For radio button i wrote a blunder code
HTML:
<input type="radio" id="allIB"style="vertical-align:middle;height:10px;width:15px;top:10px;" name="selMethodCode" value="" onClick="selInterface(this.id);enableSave1(this.id)">
<input type="radio" id="allOB" style="vertical-align:middle;height:10px;width:15px;top:10px;" name="selMethodCode" value="" onClick="selInterface(this.id);enableSave1(this.id)">
Javascript:
function enableSave1(id)
{
abc=id;
if(document.getElementById('abc').checked)
{
btnCommit.src='images\\Button\\Normal\\Save.gif';
btnCommit.disabled=false;
}
}
This is not working is there any way by which i can check if a radio button is already selected then clicking on it doesn't cause save button doesn't to get enable
use the else part of the if condition to disable the button and also remove the '' around abc:
else{
btnCommit.disabled=true;
}
change your function as
function enableSave1(id) {
if (document.getElementById(id).checked) {
btnCommit.src = 'images\\Button\\Normal\\Save.gif';
btnCommit.disabled = false;
} else {
btnCommit.disabled = true;
}
}
or your code as
HTML
<input type="radio" id="allIB" style="vertical-align:middle;height:10px;width:15px;top:10px;" name="selMethodCode" value="" onClick="selInterface(this.id);enableSave1(this)">
<input type="radio" id="allOB" style="vertical-align:middle;height:10px;width:15px;top:10px;" name="selMethodCode" value="" onClick="selInterface(this.id);enableSave1(this)">
JavaScript
function enableSave1(radio) {
if (radio.checked) {
btnCommit.src = 'images\\Button\\Normal\\Save.gif';
btnCommit.disabled = false;
} else {
btnCommit.disabled = true;
}
}
I am using tomahawk library for browse button in my project.
Browse button code.
<td><t:inputFileUpload id="file" value="#{sampleService.file}"
valueChangeListener="#{sampleService.file}" /></td>
Radio Button Code
<td><input type="radio" /> This is compulsory</td>
I want to put a validation here,If the user has not checked the radio button,
it should display a message to check radio button.
thanks for any help
Give the radio button a fixed id and check its checked state in the onclick of the file field and if it's false, then display a message (alert?) and return false to block the browse button.
E.g.
<t:inputFileUpload id="file" value="#{sampleService.file}" valueChangeListener="#{sampleService.file}"
onclick="if (!document.getElementById('compulsory').checked) { alert('Please check radio button'); return false; }"
/>
<input type="radio" id="compulsory" /> This is compulsory
You could also wrap it in a JS function:
function checkCompulsory() {
if (!document.getElementById('compulsory').checked) {
alert('Please check radio button');
return false;
} else {
return true;
}
}
with
<t:inputFileUpload id="file" value="#{sampleService.file}" valueChangeListener="#{sampleService.file}"
onclick="return checkCompulsory()"
/>
<input type="radio" id="compulsory" /> This is compulsory
If you search here you will find it but for your intrest
var radios = document.getElementsByTagName('input');
var value;
for (var i = 0; i < radios.length; i++) {
if (radios[i].type === 'radio'){
if(radios[i].checked) {
// get value, set checked flag or do whatever you need to
value = radios[i].value;
} else {
alert('This is compulsory')
}
}
}
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.