jQuery checkbox auto disable and re-enable - javascript

I have my HTML code and my JavaScript code like this (I'm using jQuery)
HTML :
<input type="checkbox" name="type" value="program" id="box-1" /> Desktop Programming
<select name="lang-1" id="select-1" disabled>
<option value="c">C/C++</option>
<option value="vb">VB</option>
<option value="cs">C#</option>
</select><br /><br />
<input type="checkbox" name="type" value="web" id="box-2" /> Web Development
<select name="lang-2" id="select-2" disabled>
<option value="asp">ASP</option>
<option value="php">PHP</option>
<option value="ror">Ruby on Rails</option>
</select><br /><br />
JavaScript (jQuery) :
$(document).ready(function(){
var x;
$("#box-" + x).click(function(){
var $this = $(this);
if ($this.is(":checked")) {
$("#select-" + x).prop('disabled', false);
} else {
$("#select-" + x).prop('disabled', true);
}
});
});
And I want when I checked the programming checkbox, the programming select option (beside the checkbox) is enable. As well as when I checked the web dev checkbox, the web dev select option is enable. But my code doesn't work. Can anybody help me?

You're better off using classes in stead of ID's with a random number.
I would give all my checkboxes the class "box" and the id 1, 2, 3 and so on.
Also, I think $this doesn't work. It has to be $(this).
Then your code would look like (working example):
$(document).ready(function(){
$('.box').click(function(){
var x= $(this).attr("id");
if ($(this).is(":checked")) {
$("#select-" + x).prop('disabled', false);
} else {
$("#select-" + x).prop('disabled', true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="type" value="program" class="box" id="1" /> Desktop Programming
<select name="lang-1" id="select-1" disabled>
<option value="c">C/C++</option>
<option value="vb">VB</option>
<option value="cs">C#</option>
</select><br /><br />
<input type="checkbox" name="type" value="web" class="box" id="2" /> Web Development
<select name="lang-2" id="select-2" disabled>
<option value="asp">ASP</option>
<option value="php">PHP</option>
<option value="ror">Ruby on Rails</option>
</select><br /><br />

For things like this use classes , no need for ID.
Right now your variable x is undefined and without a loop to parse the ID's it won't work
<input type="checkbox" class="box" /> Desktop Programming
<select name="lang-1" class="select" disabled>
JS
$('input:checkbox.box').change(function(){
$(this).next('.select').prop('disabled', !this.checked);
});
If the layout is such that the select is not right after the input we can modify traverse a bit

Hi you can do something like this working demo
Please have one same class to all of your checkbox here i taken as checkbox then your HTML will look like this
<input type="checkbox" name="type" value="program" class="checkbox" id="box-1" /> Desktop Programming
<select name="lang-1" id="select-1" disabled>
<option value="c">C/C++</option>
<option value="vb">VB</option>
<option value="cs">C#</option>
</select><br /><br />
<input type="checkbox" name="type" value="web" class="checkbox" id="box-2" /> Web Development
<select name="lang-2" id="select-2" disabled>
<option value="asp">ASP</option>
<option value="php">PHP</option>
<option value="ror">Ruby on Rails</option>
</select><br /><br />
add write this jquery
$(document).ready(function(){
$('.checkbox').on('change',function(){
var checked_id = $(this).prop('id');
var a = checked_id.slice(4);
$("#select-"+a).prop('disabled',!this.checked);
});
});

So there are lots of answers here, much of which are better ways to do what you are trying with smaller cleaner code. But for the sake of it I am adding this answer to show you what was wrong with code you wrote and a working example.
So you declared variable x but never assigned it a value. It seems like you wanted to loop over the checkboxes and use the index x to assign the event. Since you started using IDs with 1 we need to compensate in the code for it. Then since x has no scope to our event directly we need to find the value of x since when the event runs it will only have the last value of x.
All HTML I left the same and only altered the javascript. As I said there are much better ways to do this and there are many answers here that show it but this is to show you what you were doing wrong.
Fiddle: https://jsfiddle.net/quyn4y23/
$(document).ready(function() {
// Find all checkboxes and get the length of all found
var x, inputs = $('input[type="checkbox"]'), length = inputs.length;
// For each checkbox assign event
for (x = 1; x <= length; x++) {
$("#box-" + x).click(function() {
var $this = $(this);
// Find the number in the checkbox id
var x = $this.attr('id').replace("box-", "");
// Use number to find correct select
if ($this.is(":checked")) {
$("#select-" + x).prop('disabled', false);
} else {
$("#select-" + x).prop('disabled', true);
}
});
}
});

Related

Set class from <select> if selected option contains ID='answer' in HTML/JavaScript (JQuery)

I am completely new to HTML and JQuery, and I can't figure out how I can set a class for my select element if the currently selected option has an ID="answer". I want to do this to check if the multiple choice question is correct.
If this is impossible to do this in JQuery, JavaScript would also be fine. I just want to prevent making a DataBase query and thought that JQuery would be the best route to take.
This is the current html section that I have:
<form id="ansForm" class="testClass1">
<div id="QuestionForm" name="QuestionForm">
<label>Question 1: This is a question </label>
<select class="form-control select-class">
<option value="1" class="ans-class" id="answer">Answer1</option>
<option value="2" class="ans-class">Answer2</option>
<option value="3" class="ans-class">Answer3</option>
<option value="4" class="ans-class">Answer4</option>
</select>
<label>Question 2: This is another question </label>
<select class="form-control select-class">
<option value="1" class="ans-class">Another Answer</option>
<option value="2" class="ans-class">Just some text</option>
<option value="3" class="ans-class" id="answer">Test</option>
<option value="4" class="ans-class">Test2</option>
</select>
</div>
<button type="button" class="btn btn-primary"
onclick="checkAnswers()">Check</button>
</form>
When I click the button it runs a Javascript function called: "checkAnswers()".
This function should check if the option that is selected in the dropdown box, has an id="answer". In this case, that would be if option one is selected. And if that option is selected, I want the background color of the select element to change.
How would I go about checking the currently selected dropdown options' ID? And how do I do this for more than 1 question at a time?
And how would I add a class programaticly in JavaScript to that select element so it can change BG color?
This is what I tried in JavaScript:
var s = document.getElementsByClassName("select-class");
var idSelectedOption = s[s.selectedIndex].id;
alert(idSelectedOption);
But that returns an error: "Uncaught TypeError: Cannot read property 'id' of undefined"
I think that is because it returns an array from all classes. How would I go about checking every single one of them? And changing the background colors of the ones that have the correct option selected?
Thanks in advance,
Mats.
Use data-* attributes instead of id as you should not have multiple elements having same id value in a document.
getElementsByClassName will return nodelist hence you need to iterate through elements and then apply conditions accordingly. Array.prototype.forEach.call is used in example below to iterate through elements.
Try this:
function checkAnswers() {
var s = document.getElementsByClassName("select-class");
Array.prototype.forEach.call(s, function(elem) {
var idSelectedOption = elem[elem.selectedIndex].getAttribute('data-id');
if (idSelectedOption == 'answer') {
var selectedAnswer = elem[elem.selectedIndex].getAttribute('value');
alert(selectedAnswer);
}
});
}
<form id="ansForm" class="testClass1">
<div id="QuestionForm" name="QuestionForm">
<label>Question 1: This is a question</label>
<select class="form-control select-class">
<option value="1" class="ans-class" data-id="answer">Answer1</option>
<option value="2" class="ans-class">Answer2</option>
<option value="3" class="ans-class">Answer3</option>
<option value="4" class="ans-class">Answer4</option>
</select>
<label>Question 2: This is another question</label>
<select class="form-control select-class">
<option value="1" class="ans-class">Another Answer</option>
<option value="2" class="ans-class">Just some text</option>
<option value="3" class="ans-class" data-id="answer">Test</option>
<option value="4" class="ans-class">Test2</option>
</select>
</div>
<button type="button" class="btn btn-primary" onclick="checkAnswers()">Check</button>
</form>
Fiddle here
You can't have two elements with the same id. Use a custom data attribute or a class instead
After fixing that, this code should to the trick. I tried to use vanilla JavaScript since you didn't indicate using jQuery.
// Lazy: Bind the event to the form.
document.getElementById('ansForm').addEventListener('change', function(event) {
var selectElement = event.target;
// Only respond if the clicked element is one of the selects.
if (selectElement.classList.contains('select-class')) {
// Get the option that is currently selected.
var selectedOption = selectElement[selectElement.selectedIndex];
// Check if this option contains the class 'answer'.
var isAnswerSelected = selectedOption.classList.contains('answer');
console.log(isAnswerSelected);
// Remove the indicators. You could easily use classList.toggle, but the second
// argument is not supported in IE.
// selectElement.classList.toggle('right', isAnswerSelected);
// selectElement.classList.toggle('wrong', !isAnswerSelected);
// So, second best. Just remove both and re-add the class we want.
selectElement.classList.remove('right');
selectElement.classList.remove('wrong');
selectElement.classList.add(isAnswerSelected?'right':'wrong');
} else {
// Ignore clicks on any other element.
}
});
.right {
color: green;
}
.wrong {
color: red;
}
<form id="ansForm" class="testClass1">
<div id="QuestionForm" name="QuestionForm">
<label>Question 1: This is a question </label>
<select class="form-control select-class">
<option value="1" class="ans-class answer">Answer1</option>
<option value="2" class="ans-class">Answer2</option>
<option value="3" class="ans-class">Answer3</option>
<option value="4" class="ans-class">Answer4</option>
</select>
<label>Question 2: This is another question </label>
<select class="form-control select-class">
<option value="1" class="ans-class">Another Answer</option>
<option value="2" class="ans-class">Just some text</option>
<option value="3" class="ans-class answer">Test</option>
<option value="4" class="ans-class">Test2</option>
</select>
</div>
<button type="button" class="btn btn-primary"
onclick="checkAnswers()">Check</button>
</form>
Try this for jQuery approach,
$(function(){
// This will bind 'click' event handler to element with id 'checkBtn'
$('#checkBtn').on('click', function(){
// This gets all selects element which has class containing 'select-class'.
var $selects = $('select.select-class');
// Iterate all the selects element.
$selects.each(function(k, v){
// Get the option for this current select element which has an id of 'answer'.
var $selectAnswerOpt = $(this).children('option#answer');
// Get the value attribute of the option element.
var answer = $selectAnswerOpt.attr('value');
// Get the selected value for the select element.
var selectedValue = $(this).val();
// Checking if the selected value for the select element is the option that has an id of 'answer'
if (selectedValue == answer)
{
// If the selected value has the id of 'answer'
$(this).css('background-color', 'green');
}
else
{
// Else
$(this).css('background-color', 'yellow');
}
});
});
});
And the FIDDLE

Pass multiple checkbox values to dropdown lists in jQuery

I have a checkbox with 5 options. Only two of these can be selected. What I am trying to do is pass the value checked to a dropdown list. Since two checkboxes can be selected, I would like their values to be passed to two dropdown lists. Here's what I have so far.
HTML
<input class="theme" type="checkbox" name="theme" value="adventure" id="adventure"/><label for="adventure">Adventure</label>
<input class="theme" type="checkbox" name="theme" value="attraction" id="attraction"/><label for="attraction">Attraction</label>
<input class="theme" type="checkbox" name="theme" value="culture" id="culture"/><label for="culture">Culture</label>
<input class="theme" type="checkbox" name="theme" value="leisure" id="leisure"/><label for="leisure">Leisure</label>
<input class="theme" type="checkbox" name="theme" value="nature" id="nature"/><label for="nature">Nature</label>
<select id="list2">
<option value="adventure">Adventure</option>
<option value="attraction">Attractions</option>
<option value="culture">Culture</option>
<option value="leisure">Leisure</option>
<option value="nature">Nature</option>
</select>
<select id="list1">
<option value="adventure">Adventure</option>
<option value="attraction">Attractions</option>
<option value="culture">Culture</option>
<option value="leisure">Leisure</option>
<option value="nature">Nature</option>
</select>
jQuery
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
if($(this).attr("value")=="adventure"){
$("#list1").val("adventure");
}
if($(this).attr("value")=="attraction"){
$("#list2").val("attraction");
}
if($(this).attr("value")=="culture"){
$(".cultureInterests").toggle();
}
if($(this).attr("value")=="leisure"){
$(".leisureInterests").toggle();
}
if($(this).attr("value")=="nature"){
$(".natureInterests").toggle();
}
});
As you can see, this method is faulty as the order of selecting a checkbox is beyond my control and I won't be able to tell where to pass the value. Any help is highly appreciated.
EXAMPLE
Here's a JSFiddle of what I am trying to achieve. Notice how the dropdown lists value change when you click on Adventure or Attractions.
http://jsfiddle.net/ajitks/3hdbgw79/
Thank you so much!
Try something like this:
$('input[type="checkbox"]').click(function() {
if ($(this).is(':checked')) {
if ($('input[type="checkbox"]:checked').length == 1) {
$('select#list1').val($(this).val());
} else {
$('select#list2').val($(this).val());
}
}else{
$('select#list1').val($('select#list2').val())
$('select#list2').val('')
}
});
if you don't want if else condition we can use Conditional (Ternary) Operator.
ANSWER
Check out this FIDDLE. It works!
$('.next').click(function() {
var i=1;
$('input[type="checkbox"]:checked').each(function(){
$('select#list'+i).val($(this).val());
i++;
});

Disable select box and enable textbox using one checkbox with JavaScript

I'm am fairly new to JavaScript; I have been googling all day for this but i only found how to enable and disable one textbox using one checkbox.
Here is my code
JavaScript
function enable_text(status){
status=!status;
document.sr2.other_text.disabled = status;
}
HTML
<form name=sr2 method=post>
<input type="checkbox" name=others onclick="enable_text(this.checked)">
Others
<input type=text name=other_text>
</form>
Note: the code I posted is only for a textbox that when uncheck in checkbox it will be enabled.
My question is how do you disable select tag and enable a textbox after unchecking a checkbox?
Add an id to your text box then just put the below onclick of your checkbox instead of the function call.
<form name=sr2 method=post>
<input type="checkbox" name=others onclick= "document.getElementById('id_of_txtbox').disabled=this.checked;">Others
<input type=text name=other_text>
Here's the HTML
<input type="text" id="txt" disabled="disabled"/>
<select name="sel" id="sel">
<option value="test1">Test 1</option>
</select>
<input type="checkbox" name="vehicle" value="Car" checked="checked" onclick="enableText(this.checked)">Uncheck to Disable Select and Enable Text
And the JavaScript is
function enableText(checked){
if(!checked){
document.getElementById('sel').disabled = true;
document.getElementById('txt').disabled = false;
}
else{
document.getElementById('sel').disabled = false;
document.getElementById('txt').disabled = true;
}
}
Select is disabled and text is enabled on uncheking the checkbox and vice versa. Hopefully that helps.
Based on your question, are you trying to present a dropdown but then allow them to enter other values not in the dropdown?
If so, here is another way to approach it:
HTML:
<select name="RenewalTerm" id="RenewalTerm">
<option value="12">12 Month</option>
<option value="24">24 Month</option>
<option value="36">36 Month</option>
<option value="Other">Other</option>
</select>
<span id="RenewalTermOtherFields">
<label labelfor="RenewalTermManual" >Enter Renewal Term: </label>
<input type="text" name="RenewalTermManual" id="RenewalTermManual" />
</span>
JavaScript/jQuery:
$(document).ready(function() {
$('#RenewalTermOtherFields').hide();
$('#RenewalTermManual').val($('#RenewalTerm').val());
$('#RenewalTerm').change(function() {
var selectedItem = $("select option:selected").val();
if (selectedItem !== 'Other') {
$('#RenewalTermOtherFields').hide();
$('#RenewalTermManual').val($('#RenewalTerm').val());
}
else
{
$('#RenewalTermManual').val('');
$('#RenewalTermOtherFields').show();
}
});
});
See It In Action!: http://eat-sleep-code.com/#/javascript/dropdown-with-other-field
This will allow you to select "other" from the list, and when you do it will automatically display a textbox for free-form entry.

How to disable/enable form elements using a checkbox with Javascript?

I'm at a loss - after wracking my brain for hours on this one, it's time to throw the question up here.
I'm trying to have a checkbox execute some javascript code that, when checked, enables some form elements, and when unchecked, disables those elements again.
Here's the javascript that I have:
function houseclean()
{
if (document.orderform.cleaning.checked == true)
{
document.orderform.rooms.disabled = false;
document.orderform.datetime.disabled = false;
document.orderform.howoften.disabled = false;
}
else
{
document.orderform.rooms.disabled = true;
document.orderform.datetime.disabled = true;
document.orderform.howoften.disabled = true;
}
}
And here is my HTML code:
<form id="orderform" style="margin-left: 6cm">
<input type="checkbox" name="cleaning" value="yes" onclick="houseclean()"/> Home cleaning <br />
Service: <select name="rooms" id="rooms" disabled >
<option value="1bedroom">One Bedroom Apt</option>
<option value="2bedroom">Two Bedroom Apt</option>
<option value="3bedroom">Three Bedroom Townhome or SF Home</option>
<option value="4bedroom">Four Bedroom Home</option>
<option value="5bedroom">Five Bedroom Home</option>
<option value="6bedroom">Six Bedroom Home</option>
</select> <br />
Date / Time: <input type="text" name="datetime" disabled /><br />
How often would you like a cleaning?: <select name="howoften" disabled>
<option value="once">One Time Only</option>
<option value="2bedroom">Every Week</option>
<option value="3bedroom">Every Other Week</option>
<option value="4bedroom">Once a Month</option>
</select> <br />
</form>
This code will do the trick. You should be explicit about your element IDs and use getElementById whenever possible.
The HTML:
<form id="orderform" style="margin-left: 6cm;">
<input type="checkbox" id="cleaning" name="cleaning" value="yes" onclick="javascript:houseclean();"/> Home cleaning <br />
Service: <select name="rooms" id="rooms" disabled >
<option value="1bedroom">One Bedroom Apt</option>
<option value="2bedroom">Two Bedroom Apt</option>
<option value="3bedroom">Three Bedroom Townhome or SF Home</option>
<option value="4bedroom">Four Bedroom Home</option>
<option value="5bedroom">Five Bedroom Home</option>
<option value="6bedroom">Six Bedroom Home</option>
</select> <br />
Date / Time: <input type="text" id="datetime" name="datetime" disabled /><br />
How often would you like a cleaning?: <select id="howoften" name="howoften" disabled>
<option value="once">One Time Only</option>
<option value="2bedroom">Every Week</option>
<option value="3bedroom">Every Other Week</option>
<option value="4bedroom">Once a Month</option>
</select> <br />
</form>​
And the javascript:
function houseclean()
{
if (document.getElementById('cleaning').checked == true)
{
document.getElementById('rooms').removeAttribute('disabled');
document.getElementById('datetime').removeAttribute('disabled');
document.getElementById('howoften').removeAttribute('disabled');
}
else
{
document.getElementById('rooms').setAttribute('disabled','disabled');
document.getElementById('datetime').setAttribute('disabled','disabled');
document.getElementById('howoften').setAttribute('disabled','disabled');
}
}
JSFiddle example: http://jsfiddle.net/HQQ4n/10/
I got your code to work. I added the id attribute to the form elements and used document.getElementById to be on the safe side.
JFiddle example: http://jsfiddle.net/vxRjw/1/
Not super robust, but a dynamic jquery solution...
$("#mycheckbox").click(function() {
enableFormElements("#myform", $(this).attr('checked'));
});
function enableFormElements(form, enable) {
var fields = ["checkbox","textarea","select"];
var selector = form+" input";
$.each(fields, function(i,e) { selector += ","+form+" "+e; });
$(selector).each(function(idx) {
if (enable) {
$(this).removeAttr("disabled");
$(this).removeAttr("readonly");
} else {
$(this).attr("disabled","disabled");
$(this).attr("readonly","readonly");
}
if ($(this).is("select") || $(this).is("textarea")) {
var id = $(this).attr("id");
var txt_equiv = id+"_text";
var val = $(this).find("option[value='"+$(this).val()+"']").text();
// dynamically add the span to this element...so you can switch back and forth...
if ($(this).parent().find("span").length == 0) {
$(this).parent().append("<span class='record_display_text' id='"+txt_equiv+"'>"+val+"</span>");
}
}
if ($("#"+txt_equiv).length != 0) {
if (enable) {
$("#"+id).show();
$("#"+txt_equiv).hide();
} else {
$("#"+txt_equiv).show();
$("#"+id).hide();
}
}
});
}
The function basically looks for all input, selects, textareas found inside the element provided and disables or enables each one. If using JQuery 1.9, you may want to change those to prop settings, but I've found that not all browsers are consistently working with that yet. (bleh). In the cases of textareas or selects, it actually creates a related span with an id that matches the input except with "_text" after it. If you have other IDs on your page that might conflict, you might want to edit that...but putting that in place allows the code later to hide/show either the text or the actual select/textarea depending on whether you want everything enabled or disabled. Again, not tested in all circumstances, but feel free to copy and edit for your purposes...
Oh, and make sure that all selects or textareas are an only child to their parent...wrap in a span if you have to because it dynamically adds the related span within the same parent...so if the select or textarea isn't wrapped in a parent (like a span, a div, or a td or something), then it might throw the generated text span somewhere random. :P
And then you can add some CSS to make form elements look more like your normal page or standard span elements...
input[readonly],
select[readonly],
textarea[readonly] {
cursor: default;
}
input[disabled] {
background-color:#F0F0F0;
border:none;
-moz-box-shadow: none;
-webkit-box-shadow:none;
box-shadow:none;
padding: 0;
}
You will probably want to change the background-color to match your page color...and the "cursor:default" one is if bootstrap twitter is adding the annoying "restricted" cursor or whatever it is over disabled elements...but anyways, this is a solution I came up with this evening and it's working for me. :)

javascript checkbox enable/disable

Ok this is very anoying, and it is probably very simple. I want to start my web page with disabled checkboxes, and after particlar line in listbox is selected to enable those boxes. So I put this in onload method
onload = function () {
for (i = 0; i < document.frmMain.checkgroup.length; i++){
document.frmMain.checkgroup[i].disabled = true ;
}
}
it start my page with disabled boxes, now i want do enable them
function enableCheckboxes(){
if (document.frmMain.Vrste[document.frmMain.Vrste.selectedIndex].value == "Sendvici i Rostilj"){
for(i=0;i<document.frmMain.checkgroup.length;i++){
document.frmMain.checkgroup[i].enabled = true;
}
}
}
it goes in to the for loop, but it never enable those checkboxes. I cannot figure it why.
and this is html part, where i call enablecheckbox function:
<select name="Vrste" onChange="PopulatePodvrste(); enableCheckboxes();" size="8">
<option value="Pica">Pica</option>
<option value="Barbarina domaca trpeza">Barbarina domaca trpeza</option>
<option value="Slana Palacinka">Slana Palacinka</option>
<option value="Slatka Palacinka">Slatka Palacinka</option>
<option value="Sendvici i Rostilj">Rostilj i sendvici</option>
<option value="Dobro jutro sa Barbarom">Dobro jutro sa Barbarom</option>
<option value="Chicken Meni">Chicken Meni</option>
<option value="Posebna Ponuda">Posebna Ponuda</option>
<option value="Salate">Salate</option>
</select>
And finally actual checkboxes:
<input type="checkbox" name="checkgroup" >Susam</input><br>
<input type="checkbox" name="checkgroup" >Cili</input><br>
<input type="checkbox" name="checkgroup" >Tartar</input><br>
<input type="checkbox" name="checkgroup" >Urnebes</input><br>
<input type="checkbox" name="checkgroup" >Krastavac</input>
Try instead:
document.frmMain.checkgroup[i].disabled = false ;
if would add the jquery library to your page then I would add:
$(document).ready(function() {
$("input[name='checkgroup']").attr("disabled", "disabled");
})
function enableCheckboxes() {
$("input[name='checkgroup']").removeAttr("disabled");
}
If you don't want to use jquery then just change your enable line to be:
document.frmMain.checkgroup[i].disabled = false ;

Categories