Enable/disable button based on accepting the 2 checkbox conditions - javascript

I have gone through the stackoverflow regarding enable/disable button conditionally and was able to find some help but NOT EXACT what I was looking for.
Instead of 1 checkbox condition, I have 2 checkbox conditions. So unless if the two checkboxes have been accepted, the button should not be enabled.
Following is my html:
<input type="checkbox" id="f_agree" value="1" onchange="checked(this, 'f_agree2')"/>
<input type="checkbox" id="f_agree2" value="1" onchange="checked('f_agree', this)"/>
<button type="submit" disabled="disabled" id="acceptbtn">Continue</button>
Following is javascript:
function checked(element1, element2) {
var myLayer = document.getElementById('acceptbtn');
if (element1.checked == true && element2.checked == true) {
myLayer.class = "submit";
myLayer.disabled = "";
} else {
myLayer.class = "button:disabled";
myLayer.disabled = "disabled";
};
}
I have tried like above, but it is not working. I don't know where I am going wrong.

it won't work because you are not removing that attribute disabled.
function checked(element1, element2) {
var myLayer = document.getElementById('acceptbtn');
if (element1.checked == true && element2.checked == true) {
myLayer.class = "submit";
myLayer.removeAttribute("disabled");
} else {
myLayer.class = "button:disabled";
myLayer.setAttribute("disabled","disabled");
};
}
Update
use any other name then checked as it seems to be reserved and not working.
you also need to do getElementById for element1 and element2.
function checkedFunc(element1Id, element2Id) {
var myLayer = document.getElementById('acceptbtn');
var element1 = document.getElementById(element1Id);
var element2 = document.getElementById(element2Id);
if (element1.checked == true && element2.checked == true) {
myLayer.class = "submit";
myLayer.removeAttribute("disabled");
} else {
myLayer.class = "button:disabled";
myLayer.setAttribute("disabled","disabled");
};
}
<input type="checkbox" id="f_agree" value="1" onchange="checkedFunc('f_agree', 'f_agree2')"/>
<input type="checkbox" id="f_agree2" value="1" onchange="checkedFunc('f_agree','f_agree2')"/>
<input type="button" value="check" id="acceptbtn" />

You can try the following code
if (element1.checked == true && element2.checked == true) {
myLayer.class = "submit";
myLayer.removeAttribute("disabled");
} else {
myLayer.class = "button:disabled";
myLayer.setAttribute("disabled", "disabled");
};

With jQuery:
var btn;
var changed = function() {
//get the length of non checked boxes
var disbl = $('input[id^=f_agree]:not(:checked)').length;
btn.prop('disabled', disbl);//disable if true, else enable
};
$(function() {
btn = $('#acceptbtn');
$('input[id^=f_agree]').on('change', changed).trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="checkbox" id="f_agree" value="1" />1
<input type="checkbox" id="f_agree2" value="1" />2
<input type="button" id="acceptbtn" value="Submit" />

The problem is that there is a difference between the string "f_agree" and the node with id="f_agree".
Your code should work as expected with
checked(this, document.getObjectById('f_agree2'))
Much better would be however to avoid having a widget knowing about the other... I'd implement instead by adding a list of external rules that check all widgets:
function okSubmit() {
return (document.getElementById("f_agree").checked &&
document.getElementById("f_agree2").checked);
}
This is much easier to read/maintain and also scales better in case you need to add more conditions later. In the onchange of all the widgets just call a function that will enable/disable the submit button depending on the conditions.

Try this
if (element1.checked == true && element2.checked == true) {
myLayer.class = "submit";
myLayer.removeAttribute("disabled");
} else {
myLayer.class = "button:disabled";
myLayer.setAttribute("disabled", "disabled");
};

Try the below code -
var chk1 = document.getElementById('chk1');
chk1.addEventListener('click', checked, false);
var chk2 = document.getElementById('chk2');
chk2.addEventListener('click', checked, false);
function checked(){
if(chk1.checked && chk2.checked) {
document.getElementById('btn').removeAttribute('disabled');
} else {
document.getElementById('btn').setAttribute('disabled','disabled');
}
}
<input type="checkbox" id="chk1" />
<input type="checkbox" id="chk2" />
<button id="btn" disabled >Button<button>
I tested it and it's working! Hope it helps u...

Related

if checkbox check but input empty disable another checkbox

i have one chekbox and one textfield
<input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">
<input class="form-control" type="text" id="usr_zipcode" maxlength="10" name="usr_zipcode" required="required">
how to make jquery, when vehiche1 is check but usr_zipcode is empty or no value, it disable another checkbox , name checkme :
<input type="checkbox" id="checkme">
i try to use below code but not working
$('#vehicle1').change(function () {
var input1 = $('#usr_zipcode');
input1.change( function() {
var empty = ( input1.val() == '' );
$("#checkme").prop('checked', false);
$("#checkme").attr('disabled','disabled');
});
}).change();
create a separate function to check or disable another checkbox like below
function checkOrDisableAnotherCheckBox() {
if($('#vehicle1').is(':checked') && $('#usr_zipcode').val() == ''){
$("#checkme").attr('disabled', true);
} else {
$("#checkme").removeAttr('disabled');
}
}
$('#vehicle1').change(function () {
checkOrDisableAnotherCheckBox();
});
$('#usr_zipcode').keyup(function () {
checkOrDisableAnotherCheckBox();
});
You can try my code:
$('#vehicle1').change(function () {
checkEmpty();
});
function checkEmpty(){
var empty = ( $('#vehicle1').prop('checked') && $('#usr_zipcode').val() == '' );
if (empty) {
$("#checkme").prop('checked', false);
$("#checkme").attr('disabled','disabled');
}else {
$("#checkme").removeAttr("disabled");
}
}
This is a demo: https://codepen.io/phuongnm153/pen/zQavrN

how to get the value of checkbox currently unchecked in multi select dropdown list?

I am have created a multi select filter. For each of the options selected the new div element will be created with it's id is the value of checkbox selected. Till here it's working fine. But now I want to remove those div who's options(checkboxes) are un selected. I tried the below,
if(!($(this).is(":checked"))){
alert('is un-checked: ' + $(this).val());
}
but it's not working. Giving value of null. Can anyone please suggest me how can I achieve this?
CODE:
if (window.XMLHttpRequest)
{
areq = new XMLHttpRequest();
} else
{
areq = new ActiveXObject("Microsoft.XMLHTTP");
}
areq.onreadystatechange = function () {
if ((areq.readyState == 4) && (areq.status == 200)) {
document.getElementById("details7").innerHTML= areq.responseText;
var c=areq.responseText;
$('.matrb').SumoSelect({
triggerChangeCombined: false,
okCancelInMulti: true,
});
$('.matrb').on('change', function() {
if ($('option:selected', this).is(':checked')) {
alert('is checked: ' + $(this).val());
am=$(this).val();
nm=$(this).find('option:selected').attr("name");
am = am.toString().match(/\w+$/)[0];
console.log("am is:"+c);
}
else if(!($(this).is(":checked"))){
alert('is un-checked: ' + $(this).val());
}
if (window.XMLHttpRequest)
{
breq = new XMLHttpRequest();
} else
{
breq = new ActiveXObject("Microsoft.XMLHTTP");
}
breq.onreadystatechange = function () {
if ((breq.readyState == 4) && (breq.status == 200)) {
if(!( document.getElementById(am))){
var namee=document.createElement('p');
var newDiv=document.createElement('div');
newDiv.setAttribute('id', am);
newDiv.setAttribute("style","display:inline;");
namee.setAttribute("style","display:inline;");
var htm=breq.responseText;
newDiv.innerHTML=htm;
namee.innerHTML=nm;
console.log(htm);
console.log(newDiv);
document.getElementById("details8").appendChild(namee);
document.getElementById("details8").appendChild(newDiv);
}
var uncheckedValues = $("select#id").find('option').not(':selected');
var uncheckedArray = uncheckedValues.map(function () { return this.value;}).get();
console.log(uncheckedArray);
First of all, you need to bind change event for each checkbox so that whenever any checkbox is clicked (current one in your case) you can check if it is checked or unchecked.
$('#parent_container_selector').find('input[type="checkbox"]').each(function(index, element) {
$(this).on('change', function(){
//this is your current event! Grab it and do your logic here.
if($(this).is(':checked') == false)
{
//delete your required elements..
}
});
});
Something like this perhaps:
$('#checkboxes_container_id').find('input[type="checkbox"]')‌​.on('change', function (e) {
$('#checkboxes_container_id').find('input[type="checkbox"]').each(function(index, element) {
if (!$(this).is(':checked')) {
alert('is un-checked: ' + $(this).val());
return false; // in case you only want ONE alert
}
});
}
$('input[type=checkbox]').not(':checked')
$('#test').on('click', function() {
console.log($('input[type=checkbox]').not(':checked').length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<button id="test">Test</button>
$('input[type=checkbox]').on('change', function() {
if(!this.checked){
console.log('unchecked checkbox');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<button id="test">Test</button>
You can use "not" for the selecion
$('[attribute="value"]:not(":checked")').each(function() {
alert($(this).val());
});
Check this https://jsfiddle.net/wrajesh/3ga508x3/3/
Finally I found the solution. below is the code for that,
$('#myselect').on('change', function() {
var $sel = $(this),
val = $(this).val(),
$opts = $sel.children(),
prevUnselected = $sel.data('unselected');
// create array of currently unselected
var currUnselected = $opts.not(':selected').map(function() {
return this.value
}).get();
// see if previous data stored
if (prevUnselected) {
// create array of removed values
var unselected = currUnselected.reduce(function(a, curr) {
if ($.inArray(curr, prevUnselected) == -1) {
a.push(curr)
}
return a
}, []);
// "unselected" is an array
if(unselected.length){
alert('Unselected is ' + unselected.join(', '));
}
}
$sel.data('unselected', currUnselected)
}).change();
posting this because it may help someone.

javascript implement "select all" check box not working in IE

I have found this code online, and it is okay on Firefox and Chrome, but it doesn't work on IE, do anyone know how to fix it for IE?
the value of the button does toggle, but just the checkbox not able to change
<html>
<head>
<script type="text/javascript">
function do_this(){
var checkboxes = document.getElementsByName('approve[]');
var button = document.getElementById('toggle');
if(button.value == 'select'){
for (var i in checkboxes){
checkboxes[i].checked = 'FALSE';
}
button.value = 'deselect'
}else{
for (var i in checkboxes){
checkboxes[i].checked = '';
}
button.value = 'select';
}
}
</script>
</head>
<body>
<input type="checkbox" name="approve[]" value="1" />
<input type="checkbox" name="approve[]" value="2" />
<input type="checkbox" name="approve[]" value="3" />
<input type="button" id="toggle" value="select" onClick="do_this()" />
</body>
</html>
It is considered a best practice to put your handler in code and not in-line. You can save some code, and put the onclick handler in your code like so:
// add event handler
function init() {
document.getElementById('toggle').onclick = function () {
do_this(this);
};
}
window.onload = init;
// me is the button here
function do_this(me) {
var checkboxes = document.getElementsByName('approve[]');
for (var i = 0; i < checkboxes.length; i++) {
// toggle to what it is not
checkboxes[i].checked = !checkboxes[i].checked;
}
me.value = me.value == 'select' ? 'deselect' : 'select';
}
Sample fiddle to show it in action: http://jsfiddle.net/qK2qS/
You must pass a boolean value to the checked property. The other browsers are understanding your bizarre logic, and converting 'FALSE' to the boolean true (checking the box), and '' to false (unchecking it)
Use the actual true and false booleans, and it might just work ;)

how to check radio buttons with javascript

this is my code in html:
<input type="radio" name="sex" id="boy" value="male" /> Boy<p></p><br>
<input type="radio" name="sex" id="girl" value="female" />Girl
<button id="fine" type="button">Submit</button>
and this is in my javascript file:
var maskio = document.getElementById('boy');
var femmna = document.getElementById('girl');
function prima(){
var fine = document.getElementById('fine');
fine.onclick=chek;
}
function chek(){
if((maskio.checked == false) && (femmna.checked == false)) {
alert('lol');
return false;
}
}
window.onload=prima;
Where is the problem? When i run it and click Submit nothing happens. Why?
Change your JS as follows. The elements were not created by the time you were getting them.
function prima() {
var fine = document.getElementById('fine');
fine.onclick = chek;
}
function chek() {
var maskio = document.getElementById('boy');
var femmna = document.getElementById('girl');
if ((maskio.checked == false) && (femmna.checked == false)) {
alert('lol');
return false;
}
}
window.onload=prima;
Check here: jsFiddle
The issue is your html tags, there is a space "< " remove the space and it will work fine...
<input type="radio" name="sex" id="boy" value="male" /> Boy
<p></p><br>
<input type="radio" name="sex" id="girl" value="female" /> Girl
<button id="fine" type="button">Submit</button>
<script>
var maskio = document.getElementById('boy');
var femmna = document.getElementById('girl');
function prima()
{
var fine = document.getElementById('fine');
fine.onclick=chek;
}
function chek()
{
if(maskio.checked)
{
alert("You are male Eh?");
}
else if(femmna.checked)
{
alert("Femal ;)");
}
else if(!maskio.checked && !femmna.checked)
{
alert("Come on Please check something!");
}
}
window.onload=prima;
</script>
when radio-buttons have the same name, they belong to the group of the name. That means, only one radio-button in a group can be selected. If you check both, there won't be a result, anyway !

making the checkbox to display div

here am trying to display divs ClinicFieldSet and HospitalFieldset by selecting the given text boxes. If both are selected, both ClinicFieldset and HospitalFieldset should display and if one of the check box is selected it should show which div is selected.
The problem with my script is, when one of the checkboxes are clicked, both checkboxes are getting selected and it is not posible to uncheck them also. So please suggest me an idea to fix this problem :(
I used Javascript onClick in both checkboxes to apply on both of them.
<script type="text/javascript>
var clinic = document.getElementById('clinic');
var visit = document.getElementById('visit');
if((clinic.checked = true) && (visit.checked = true) )
{
document.getElementById('ClinicFieldSet').style.display='block';
document.getElementById('HospitalFieldSet').style.display='block';
}
else if((clinic.checked = true) && (visit.checked = false))
{
document.getElementById('ClinicFieldSet').style.display='block';
document.getElementById('HospitalFieldSet').style.display='none';
}
else if((clinic.checked = false) && (visit.checked = true))
{
document.getElementById('ClinicFieldSet').style.display='none';
document.getElementById('HospitalFieldSet').style.display='block';
}
else
{
document.getElementById('ClinicFieldSet').style.display='none';
document.getElementById('HospitalFieldSet').style.display='none';
}
HTML
<input type="checkbox" name="type" id="clinic" onClick="dispp();" >Clinic Practice
<input type="checkbox" name="type" id="visit" onClick="dispp();" >Visiting Hospital
In your if statement use the == equality operator.
The single = is used to assign a value, not test its equality.
May I suggest a revised approach (not using in-line click-handlers) with a slightly amended html, just to make the JavaScript somewhat more simple:
HTML:
<input type="checkbox" name="type" id="clinic" /><label for="clinic">Clinic Practice</label>
<input type="checkbox" name="type" id="hospital" /><label for="hospital">Visiting Hospital</label>
<div id="clinicInfo">
<h2>Clinic information</h2>
</div>
<div id="hospitalInfo">
<h2>Hospital information</h2>
</div>
JavaScript:
document.getElementById('hospitalInfo').style.display = 'none';
document.getElementById('clinicInfo').style.display = 'none';
var inputs = document.getElementsByTagName('input');
function dispp() {
if (this.checked) {
document.getElementById(this.id + 'Info').style.display = 'block';
}
else {
document.getElementById(this.id + 'Info').style.display = 'none';
}
}
for (i = 0; i < inputs.length; i++) {
if (inputs[i].type.toLowerCase() == 'checkbox') {
inputs[i].onchange = dispp;
}
}
JS Fiddle demo.
Try this
if(clinic.checked == true)
{
document.getElementById('ClinicFieldSet').style.display='block';
}
else
{
document.getElementById('ClinicFieldSet').style.display='none';
}
if(visit.checked == true)
{
document.getElementById('HospitalFieldSet').style.display='block';
}
else
{
document.getElementById('HospitalFieldSet').style.display='none';
}
var form=document.forms.add
form.elements.check.addEventListener('change',function(e) {
e.preventDefault()
var check=document.querySelector('.check')
if(check.checked=true)
{
document.querySelector('.inside').style.display='block'
}
else{
document.querySelector('.inside').style.display='none'
}
})

Categories

Resources