checkbox disable/enable inquiry using javascript function - javascript

I'm fairly new to JavaScript and I have been Googling all day for this but I only found how to enable and disable one textbox using one checkbox. I tweaked the code a bit to work with what I want and here is what I got. I'm thinking of instructing JS function to follow only the id of the checkbox, but I can't seem to figure out how to do it.
Here is my code:
JavaScript
<script>
function enableText(checked){
if(!checked){
document.getElementById('sel1').disabled = true;
document.getElementById('txt1').disabled = false;
}
else{
document.getElementById('sel1').disabled = false;
document.getElementById('txt1').disabled = true;
}
}
function enableText(checked){
if(!checked){
document.getElementById('sel2').disabled = true;
document.getElementById('txt2').disabled = false;
}
else{
document.getElementById('sel2').disabled = false;
document.getElementById('txt2').disabled = true;
}
}
</script>
HTML
<form name=sr2 method=post>
<select name="pt" id="sel1">
<option>test</option>
</select>
<input type="checkbox" name="cb1" checked="checked" onclick="enableText(this.checked)">
Others
<input type="text" name="pt" id="txt1" disabled="disabled">
<select name="dept" id="sel2">
<option>test</option>
</select>
<input type="checkbox" name="cb2" onclick="enableText(this.checked)" checked="checked">
Others
<input type="text" name="dept" id="txt2" disabled="disabled">
</form>
My question is how can I set the function in js to instruct cb1 to only enable txt1 and disable sel1 and cb2 to only enable txt2 and disable sel2? My code works but, for some reason, it enables txt1 and txt2 and disables sel1 and sel2 at the same time.
Any help is greatly appreciated.

You have created two functions with the same name: enableText. Simplifying your code:
function enableText(checked, index){
var sel = true, txt = false;
if(checked) {
sel = false;
txt = true;
}
document.getElementById('sel' + index).disabled = sel;
document.getElementById('txt' + index).disabled = txt;
}
And in your HTML:
onclick="enableText(this.checked, 1)"
And change the 2nd parameter for the next items.
A second version of your function with ternaries, but with the same purpose:
function enableText(checked, index) {
document.getElementById('sel' + index).disabled = (checked ? false : true);
document.getElementById('txt' + index).disabled = (checked ? true : false);
}

Related

Javascript check a radio button in form based on a text box value

I have a form which inserts and retrieves data from a google sheet.
Example:
I have two radio buttons on my form
<input id="Rdio_1" name="RdioSelect" type="radio" class="FirstCheck"
value="1" onchange="RadioValInsert ()"/>
<input id="Rdio_2" name="RdioSelect" type="radio" class="FirstCheck"
value="2" onchange="RadioValInsert ()" />
when the above is clicked the value of the radio button is stored in a text box..the RadioValInsert () does it
<input type="text" id="DatafromRadio" name="DatafromRadio">
I am able to insert this value of 1 or 2 into the corresponding cell in google sheet.
When I want to EDIT it, I retrieve the data and the Textbox value is 1 or 2
The button which retrieves the data has a function to check the corresponding radio button based on the value of the Text box.
function RadioChk() {
var val = document.getElementById("DatafromRadio").value;
if (val == 1) {
document.getElementById("Rdio_1").checked = true;
}
if (val == 2) {
document.getElementById("Rdio_2").checked = true;
}
}
This is not working
Thanks in advance for your help
You are doing your check and uncheck related code inside RadioChk function however you haven't bind click event on radio inputs . If i correctly understood your question , here is how you can select and deselect your radio buttons.
function RadioValInsert() {
console.log('checked');
var val = document.getElementById("DatafromRadio").value;
if(val ==1 || val ==2){
uncheckAll();
document.getElementById("Rdio_"+val).checked = true;
}else{
uncheckAll();
console.log('choose only between 1 or 2');
}
}
function uncheckAll(){
let ele = document.getElementsByName("RdioSelect");
for(var i=0;i<ele.length;i++){
ele[i].checked = false;
}
}
<input id="Rdio_1" name="RdioSelect" type="radio" class="FirstCheck"
value="1" onchange="RadioValInsert ()"/>
<input id="Rdio_2" name="RdioSelect" type="radio" class="FirstCheck"
value="2" onchange="RadioValInsert ()" />
<input type="text" id="DatafromRadio" name="DatafromRadio">
Try this example where radio selection and textbox value changes as per selection/input
document.addEventListener('DOMContentLoaded', function(dce) {
var radios = document.querySelectorAll('[name="RdioSelect"]');
var textbx = document.querySelector('[name="DatafromRadio"]');
radios.forEach(function(r) {
r.addEventListener('click', function(e) {
textbx.value = this.value;
});
});
textbx.addEventListener('input', function(e) {
radios.forEach(function(r) {
r.checked = (r.value === textbx.value);
});
});
var fillTxt = function(txt) {
textbx.value = txt;
textbx.dispatchEvent(new Event('input')); //<-- trigger event
};
fillTxt('2'); //<--- update text box
});
<input id="Rdio_1" name="RdioSelect" type="radio" value="1" />
<input id="Rdio_2" name="RdioSelect" type="radio" value="2" />
<input type="text" id="DatafromRadio" name="DatafromRadio" />
this works only if data is input physically in the text box - in my case the data is retrieved via a function and it populates the text box
In that, just trigger event on textbox

Enable/disable button based on accepting the 2 checkbox conditions

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...

Jquery radio:checked is not working as expected

I am learning jquery. I have made a simple html file with minor validations in jquery , but they are not behaving properly. The issue is:
If Enter name first and then select the checkbox, everything seems to be working fine .
But if I select gender first and then enter name , it keeps alerting me to select gender.
Is there an issue with the way which the code has been implemented?
<script src="jquery.js"></script>
<script>
$(document).ready(function () {
$("#Name").focus();
$("#target").submit(function () {
var fn = $("#Name").val();
if (fn == "" && fn.length == 0) {
alert('Name is mandatory');
$("#Name").focus();
return false;
}
var status = false;
$("#gender").each(function () {
if ($(this).is(":radio:checked")) {
status = true;
}
});
if (!status) {
alert("Select Gender");
$("#gender").focus();
return false;
}
return true;
});
});
</script>
<form id='target' action='MyResult.html'>
First Name:
<input type='text' name='Name' id='Name' />
<br/>Gender:
<input type='radio' name='gender' id='gender' value='male' />Male
<input type='radio' name='gender' id='gender' value='female' />Female
<br/>
<input type='submit' value='Registration' />
</form>
IDs must be unique. You can use Attribute value selector in combination with :checked to filter out whether radio button is checked or not.
var status = $(":radio[name=gender]:checked").length > 0;
instead
var status = false;
$("#gender").each(function () {
if ($(this).is(":radio:checked")) {
status = true;
}
});
DEMO

validatin script for radio button not Working

I am getting errors. The script is not working. Help
thanks in advance.
I want to check if all my set of radio buttons are checked when button next is click.
other ways of doing this also are welcome
<div class="qheader">
9) What's the world's most widely spoken language?</div>
<div class="qselections">
<input type="radio" value="a" name="question9">a) English<br>
<input type="radio" value="b" name="question9">b) Spanish<br>
<input type="radio" value="c" name="question9">c) Mandarin<br>
<input type="radio" value="d" name="question9">d) French<br>
</div><br>
<div class="qheader">
10) Which continent is host to the most countries in the world?</div>
<div class="qselections">
<input type="radio" value="a" name="question10">a) Asia<br>
<input type="radio" value="b" name="question10">b) Africa<br>
<input type="radio" value="c" name="question10">c) Europe<br>
</div>
</div>
<input type="button" value="Next" name="B3" onclick="showdesc()">
<script>
$(function() {
$(document).on('click', 'form', function () {
var validate = true;
var unanswered = new Array();
// Loop through available sets
$('.qselections').each(function () {
// Question text
var question = $(this).prev().text();
// Validate
if (!$(this).find('input').is(':checked')) {
// Didn't validate ... dispaly alert or do something
unanswered.push(question);
validate = false;
}
});
if (unanswered.length > 0) {
msg = "Please answer the following questions:\n" + unanswered.join('\n');
alert(msg);
}
return validate;
});
});
</script>
function clicked() {
var validate = true;
var unanswered = new Array();
// Loop through available sets
$('.qselections').each(function () {
// Question text
var question = $(this).prev().text();
// Validate
if (!$(this).find('input').is(':checked')) {
// Didn't validate ... dispaly alert or do something
unanswered.push(question);
validate = false;
}
});
if (unanswered.length > 0) {
msg = "Please answer the following questions:\n" + unanswered.join('\n');
alert(msg);
}
return validate;
}
JSFiddle
I reproduced your problem with slight modifications, works well for me. I guess it's just a syntax error in the portion of your code, not present in the fiddle. Cross check and let me know.
Try and modify your click call, make it direct like in the fiddle.
//try this script
if(!$(this).find("input[name=radio]").is(':checked')){
alert("hi");
}

Checkbox to display more options

I am using ColdFusion 8 to create a search form and would like the user to be able to check a box if they want the advanced search options to appear.
Here is what I have so far:
In my javascript file:
function showDiv(advancedVal)
{
if(advancedVal == '') {
$('moreOptions').style.display = "";
} else {
$('moreOptions').style.display = "none";
}
}
In my CF file:
<input name="advanced" type="checkbox" value="" id="advanced" onclick="showDiv('');">
<div id="moreOptions" style="display:none;" class="moreOptions">
<table>
drop down boxes
</table>
</div>
The checkbox is in a different table, does this matter?
Anyone know why this isn't working?
Are you using jQuery? Then it should be:
$('moreOptions').style.display = "" should be $('#moreOptions').show()
or
$('moreOptions')[0].style.display = ""
UPD
I guess this is what you want:
function showDiv(obj) {
var more = document.getElementById('moreOptions');
more.style.display = obj.checked ? "" : "none";
}​
And change your markup:
<input name="advanced" type="checkbox" value="" id="advanced" onchange="showDiv(this)">
See demo http://jsfiddle.net/dfsq/Kexbu/2/
If you are not using jQuery, your code should be:
function showDiv(advancedVal)
{
if(advancedVal) {
document.getElementById('moreOptions').style.display = "";
} else {
document.getElementById('moreOptions').style.display = "none";
}
}
and
<input name="advanced" type="checkbox" value="" id="advanced" onchange="showDiv(this.checked)">
Here's an example: http://jsfiddle.net/XN8aK/1/
change $('moreOptions') to $('#moreOptions')

Categories

Resources