Grey-out (disable) HTML textarea when checkbox is ticked - javascript

I don't really know much Javascript yet, I was hoping somebody could help me understand how to solve my problem:
My HTML form has a checkbox and then a textarea:
<form>
<input type="checkbox" name="detailsgiven" />
<textarea name="details"></textarea>
</form>
I want it so that the textarea gets disabled when the checkbox is ticked so that the user cannot click it and enter text.
I've had a look here and on google, I couldn't find any clear examples of how to do it.
I'm guessing this can be done in Javascript, but I'm feeling a bit out of my depth. Can somebody explain to me how to do this, preferably without using a third party library?

<form>
<input type="checkbox" name="detailsgiven" onchange="toggleDisabled(this.checked)"/>
<textarea name="details" id="tb1"></textarea>
</form>
<script>
function toggleDisabled(_checked) {
document.getElementById('tb1').disabled = _checked ? true : false;
}
</script>

This extremely easy to do with jQuery. Everyone uses jQuery, so should you ;-).
<form>
<input type="checkbox" name="detailsgiven" id="detailsgiven" />
<textarea name="details" id="details"></textarea>
</form>
<script type="text/javascript">
jQuery(document).ready(function($) {
$("#detailsgiven").change(function() {
if($(this).is(":checked")) {
$("#details").attr("disabled", "disabled");
}
else {
$("#details").removeAttr("disabled");
}
});
});
</script>

try this:
if ($('input:checkbox').is(':checked')) {
$('textarea').attr('disabled', 'disabled');
}

<form>
<input type="checkbox" name="detailsgiven" onclick="document.getElementById('t').setAttribute('disabled','disabled');" />
<textarea id="t" name="details"></textarea>
</form>
Notice how onclick event of checkbox is used to execute some javascript code.
if you give your html elements ids, you can access the elements in javascripts through getElementById method of javascript DOM (document object model).
And once you have the element, you can set/get it's attributes, do whole lot of things.

According to my understanding to your requirement. At first, textarea is disabled. When detailsgiven checkbox is checked, textarea is enabled and checkbox is disabled so that he cannot changed. Try like this.
<!DOCTYPE html>
<html>
<head>
<script>
function valueChanged()
{
var element1 = document.getElementById("detailsgiven");
var element2 = document.getElementById("details");
if(element1.checked)
{
element2.disabled=false;
element1.disabled="disabled";
}
}
</script>
</head>
<body>
<form>
<input type="checkbox" name="detailsgiven" id="detailsgiven" onchange="valueChanged()"/>
<textarea name="details" id="details" disabled="true"></textarea>
</form>
</body>
</html>

All you have to do is when you mark the checkbox, just add the attribute disabled="disabled" in the textarea.
Checkout the jsfiddle I have added
http://jsfiddle.net/Q9Lg4/

Related

How to populate input with jquery on-click

I want to populate an input field on click with jquery, currently am able to populate a normal html field but not an input field, the reason i want to achieve this is to enable submissions because currently the data populated on html field is not being submitted, I beleive that populating this data in an input field will enable possible submissions.
I am currently using the following code to achieve this:
function populatethefield() {
document.getElementById("populatethisfield").innerHTML = "data to be populated to the field";
}
The field html
< p id="populatethisfield"><p>
This works, but i want to populate an input field, rather than a paragraph field.
When trying to change the value of an input field, you have to access the value property because inputs do not have an innerHTML, but a value instead. See code below for a demonstration:
<input type="text" id="target" placeholder="test" />
<script>
document.getElementById('target').value = "Value Updated.";
</script>
Hope this is what you are looking for
$('.populate').click(function(e){
var data = 'Some Content'
$("#populatethisfield").html('<input value="'+data+'">')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<p id="populatethisfield"></p>
<button class="populate">Populate Input</button>
If you want a pure jquery solution use the val() method for input fields.
$('.populate').on('click', function() {
$('#target').val("data to be populated to the field");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<input type="text" id="target" placeholder="test" />
<button class="populate">Populate Input</button>
You can try this.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<script>
function changeValue(value){
document.getElementById("input").value= "Hello World";
}
</script>
<body>
<input type="button" onclick="changeValue(2)" value="Button">
<input type="text" id="input" value="">
</body>
</html>

Need to disable a checkbox in JSP where checkbox name is same as hidden field

I have a checkbox and a hidden input type having same name. I need to enable/disable checkbox base on some condition. How can i do that ? If I am trying to disable it by using checkbox name it is failing because it is not able to identify whether I want to diasable hidden field or checkbox.
Please suggest any solution for this.
try this.
<!DOCTYPE html>
<html>
<head>
<script>
function getElements() {
var x=document.getElementsByName("x");
if(x.length == 2) {
alert("Number of 'X' is " + x.length);
document.getElementsByName("x")[1].disabled=true ;
}
}
</script>
</head>
<body>
<input name="x" type="hidden" value="1">
<input name="x" type="text" value="1">
<input type="button" onclick="getElements()" value="How many elements named 'x'?">
</body>
</html>
If you insist to use name instead of of an unique id
By assuming your tag order with same name in your html is looked something like below:
<input type="checkbox" name="a">
<input type = "hidden" name="a">
You can do something like this:
document.getElementsByName('a')[0].disabled = true;

Show a javascript variable on html textbox

All I have to do is to show a number in a textbox and a button which add 10 every time I press it, here's my code (it doesn't work).
<head>
<script type="text/javascript">
var n=parseInt(ocument.forms["formNum"]["numero"].value);
document.getElementById("numero").value=n;
function sumar() {
n=document.forms["formNum"]["numero"].value+10;
document.forms["formNum"]["numero"].value=n;
}
function inicializar() {
n=document.forms["formNum"]["numero"].value=0;
}
</script>
</head>
<body>
<form name="formNum">
<p>
<input type="text" size="10" name="numero" id="numero" />
</p>
<p>
<input type="button" name="sumar" value="Sumar" onclick="sumar()" />
<input type="button" name="inicializar" value="Iniciar a 0" onclick="inicializar()" />
</p>
</form>
</body>
<body>
<script type="text/javascript">
function sumar(){
document.getElementById("numero").value = parseInt(document.getElementById("numero").value)+10;
}
function inicializar(){
document.getElementById("numero").value=0;
}
</script>
<form name="formNum">
<p>
<input type="text" size="10" name="numero" id="numero" value="0" />
</p>
<p>
<input type="button" value="Sumar" onclick="sumar()" />
<input type="button" value="Iniciar a 0" onclick="inicializar()" />
</p>
</form>
</body>
Five suggestions.
It is always better to give unique ids to your html elements.
Never name your HTML elements and javascript functions the same.
If you want to access the html element from javascript, if you know the id, use getElementById.
Use Firebug or Developer tools from the browser, to debug.
If you want to access your elements with the hierarchy, use elements in the form like this document.forms["formNum"].elements["numero"].value. Check this example
Demo: http://jsfiddle.net/DPJCR/
This code should work:
<input type="text" id="mytext">
<script type="text/javascript">
var elem = document.getElementById("mytext");
elem.value = "My default value";
</script>
See: Set the value of an input field
Maybe you are getting an exception from the parseInt that prevents the value from changing.
If it is an option to use jQuery, try this:
function sumar(){
$("#numero").attr("value", parseInt($("#numero").attr("value"), 10)+10);
}
Try this this will help you
var count=10;
$('#btnSumar').click(function(){
if($('#numero').val()=='')
{
$('#numero').val(count);
}else
$('#numero').val(eval($('#numero').val())+count);
});
$('#btnInc').click(function(){
$('#numero').val('');});
Fiddle here

checkbox enable onload to display other elements

Ok, The question here is to allow a form to grab information from a mysql settings, like enabled or disabled. then a checkbox is going to determine if the the 3 following text fields (box123) are going to be enabled or disabled depending on that request.
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="test.js"></script>
</head>
<body>
<form>
<input type="checkbox" name="detailsgiven" id="checker" checked=checked>Enabled?
<br>
<input type='text' name="details" id="tb1" value='box1'>
<br>
<input type='text' name="details" id="tb2" value='box2'>
<br>
<input type='text' name="details" id="tb3" value='box3'>
<br>
</form>
</body>
</html
>
test.js Jquery code which allows the check to be enabled or disabled depending on the activation varible
toggleInputs($('#checker'));
$('#checker').click(function () {
toggleInputs($(this));
});
function toggleInputs(element) {
if (element.prop('checked')) {
$('#tb1').prop('disabled', false);
$('#tb2').prop('disabled', false);
$('#tb3').prop('disabled', false);
} else {
$('#tb1').prop('disabled', true);
$('#tb2').prop('disabled', true);
$('#tb3').prop('disabled', true);
}
}
While you've already accepted an answer, I feel that answer over-complicated the solution somewhat, and left in unnecessary redundancy. That said, I'd suggest the following approach:
function toggleInputs(element) {
/* using a multiple selector
checking whether the check-box is checked or not using ':is()`,
which returns a Boolean */
$('#tb1, #tb2, #tb3').prop('disabled', element.is(':checked'));
}
$('#checker').change(function(){
// event-handling (reacting to the change event)
toggleInputs($(this));
/* the next change() (without arguments) triggers the change event,
and, therefore, the event-handling */
}).change();
JS Fiddle demo.
Amended the above function (using the ! operator) to have the fields editable while the input is checked, and disabled while the input is unchecked:
function toggleInputs(element) {
$('#tb1, #tb2, #tb3').prop('disabled', !element.is(':checked'));
}
$('#checker').change(function(){
toggleInputs($(this));
}).change();
JS Fiddle demo.
References:
:checked selector.
change().
is().
prop().
Here you go... Actually using jquery as your question asked:
HTML
<form>
<input type="checkbox" name="detailsgiven" id="checker" checked=checked>Enabled?
<br>
<input type='text' name="details" id="tb1" value='box1'>
<br>
<input type='text' name="details" id="tb2" value='box2'>
<br>
<input type='text' name="details" id="tb3" value='box3'>
<br>
</form>
JavaScript
$(document).ready(function() {
toggleInputs($('#checker'));
$('#checker').click(function () {
toggleInputs($(this));
});
});
function toggleInputs(element) {
if (element.prop('checked')) {
$('#tb1').prop('disabled', false);
$('#tb2').prop('disabled', false);
$('#tb3').prop('disabled', false);
} else {
$('#tb1').prop('disabled', true);
$('#tb2').prop('disabled', true);
$('#tb3').prop('disabled', true);
}
}
http://jsfiddle.net/Q9Lg4/40/
When the initial call is made the elements in the body are not yet loaded. You can wrap the first call to toggleInputs in a JQuery ready event function or place the script tag that includes test.js after the form.

Enabling inactive fields by clicking on field

Is it possible to have a group of inactive fields where if one of the fields is clicked some of the fields become mandatory and some segments of code are run? Say for example you have three fields which are shown:
<input type="text" id="gov1" name="gov1">
<input type="text" id="parentb" name="parentb">
<input type="checkbox" name="child" id="child">
All three of these fields are initially inactive; but say you click on one of the fields it now makes the rest active and mandatory, and some segment of code is run on the field "parentb" and it is attributed at readonly.
window.onload = function(event)
{
var $input2 = document.getElementById('dec');
var $input1 = document.getElementById('parentb');
$input1.addEventListener('keyup', function()
{
$input2.value = $input1.value;
});
}
I have done a bit of searching around but i can't seem to find anything of use for this specific situation and i'm quite new to JavaScript so any sort of help would be great. Is this at all possible using JavaScript? Or is something similar to this possible?
This method you are looking is called 'chained-select' method.
jQuery framework is used for example below:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
<form action="" method="get">
<label>
<input name="Government" type="checkbox" value="">Government</label>
<br>
<label>
<input name="Parent" type="checkbox" id="parent_child_group" value="">Parent</label>
<br>
<label>Name of Child
<input type="text" name="parent_child" value="" class="parent_child_group"></label>
<br>
<label>Other
<input type="text" name="parent_other" value="" class="parent_child_group"></label>
</form>
<script type="text/javascript">
$(document).ready(function () {
$(function() {
enable_cb();
$("#parent_child_group").click(enable_cb);
});
function enable_cb() {
if (this.checked) {
$("input.parent_child_group").removeAttr("disabled");
} else {
$("input.parent_child_group").attr("disabled", true);
}
}
});
</script>
</body>
</html>
Working example on JSFiddle: http://jsfiddle.net/farondomenic/fg7p8/1/

Categories