How to disable/enable a button with a checkbox if checked [duplicate] - javascript

This question already has answers here:
Enable/Disable submit button if checkbox is checked/unchecked?
(3 answers)
Closed 8 years ago.
Please i need a script that can work with the HTML code bellow to disable/enable the button when a checkbox is checked or unchecked,
<input type="submit" name="sendNewSms" class="inputButton" id="sendNewSms" value=" Send " />
please pals i don't mean the button to be disabled when checked, but rather the other way round.

You can use onchangeevent of the checkbox to enable/disable button based on checked value
<input type="submit" name="sendNewSms" class="inputButton" id="sendNewSms" value=" Send " />
<input type="checkbox" onchange="document.getElementById('sendNewSms').disabled = !this.checked;" />

You will have to use javascript, or the JQuery framework to do that. her is an example using Jquery
$('#toggle').click(function () {
//check if checkbox is checked
if ($(this).is(':checked')) {
$('#sendNewSms').removeAttr('disabled'); //enable input
} else {
$('#sendNewSms').attr('disabled', true); //disable input
}
});
DEMO: http://jsfiddle.net/T6hvz/

HTML
<input type="checkbox" id="checkme"/><input type="submit" name="sendNewSms" class="inputButton" id="sendNewSms" value=" Send " />
JS
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('sendNewSms');
checker.onchange = function() {
sendbtn.disabled = !!this.checked;
};
DEMO

brbcoding have been able to help me with the appropriate coding i needed, here is it
HTML
<input type="checkbox" id="checkme"/>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
Javascript
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('sendNewSms');
// when unchecked or checked, run the function
checker.onchange = function(){
if(this.checked){
sendbtn.disabled = false;
} else {
sendbtn.disabled = true;
}
}

Here is a clean way to disable and enable submit button:
<input type="submit" name="sendNewSms" class="inputButton" id="sendNewSms" value=" Send " />
<input type="checkbox" id="disableBtn" />
var submit = document.getElementById('sendNewSms'),
checkbox = document.getElementById('disableBtn'),
disableSubmit = function(e) {
submit.disabled = this.checked
};
checkbox.addEventListener('change', disableSubmit);
Here is a fiddle of it in action: http://jsfiddle.net/sYNj7/

I recommend using jQuery as it will do all the heavy lifting for you. The code is fairly trivial.
$('input:checkbox').click(function () {
if ($(this).is(':checked')) {
$('#sendNewSms').click(function () {
return false;
});
} else {
$('#sendNewSms').unbind('click');
}
});
The trick is to override the 'click' event and effectively disable it. You can also follow it up with some CSS magic to make it look "disabled". Here is the code in JavaScript in case you need it. It's not perfect but it gets the point across.
var clickEvent = function () {
return false;
};
document.getElementById('#checkbox').onclick(function () {
if (document.getElementById('#checkbox').checked) {
document
.getElementById('#sendNewSms')
.onclick(clickEvent);
} else {
document
.getElementById('#sendNewSms')
.removeEventListener('click', clickEvent, 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

jQuery - radio button on click and not on change

I'm trying to find a solution to an issue I have between click and change.
I need to capture the click event and not change.
I'll explain the situation:
I have a radio button list with 3 items.
Each click I need to clean a div. However, If i'm posting back and return to the client with an error(submit, server validation check failed), the change event is fired once again (obviously), and the div is cleaned.
Is there a way to distinguish between click and the checked state?
I hope I have made myself clear.
Edit:
Added some code:
$("input[name*='SelectedOwner']").on('change',
function () {
var radioId = $(this).val();
if (radioId === "2" || radioId === "3") {
$("#div1").hide();
$("#divclean :input").removeAttr("disabled");
} else {
$("#div1").show();
$("#divclean :input").attr("disabled", true);
}
});
$("input[name*='SelectedOwner']").on('click', function () {
//Clean the output at each change
$("#divclean :input").val("");
});
Thanks.
$('input[name="choose"]').click(function(e) {
if ($(this).data('clicked')) {
$('#theDiv').text('You have REclicked "'+ $(this).val() + '" value');
}
else {
$('input[name="choose"]').data('clicked', false);
$(this).data('clicked', true);
$('#theDiv').text('First time you click "'+ $(this).val() + '" value');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="theDiv"></div>
A
<input type="radio" name="choose" value="a" />
B
<input type="radio" name="choose" value="b" />
C
<input type="radio" name="choose" value="c" />
You should to bind the change event to every radio button:
$("#r1, #r2, #r3").change(function () { }
With jQuery is also possible:
if ($("#r1").is(":checked")) {}
More informations:
JQuery $(#radioButton).change(...) not firing during de-selection
I hope this helps...
Good Luck!

Input value isn't being read correctly, comes up as undefined, JavaScript

I'm creating a website where the input of a form is being read by JavaScript, but when I execute the alert it says that the value of the input is undefined. Why is that?
Here is my form:
<form action="" method="post" id="reportform">
<input type="radio" name="report" value="customer"><p>Customers</p>
<input type="radio" name="report" value="item"><p>Items Sold</p>
<input type="radio" name="report" value="department"><p>Sales Departments</p>
<input type="radio" name="report" value="person"><p>Sales People</p>
<input type="button" name="reportsubmit" value="Submit" onClick="readText(this.form)">
</form>
Here is my JavaScript:
<script>
function readText (form) {
var radio = form.report.value;
alert("You entered: " + radio);
}
</script>
You could read the value from the checked checkbox like this:
function readText(form) {
var checked = form.querySelector('input:checked');
var value = checked ? checked.value : null;
// do something with `value`
}
element.querySelector() works in IE8+.
:checked is a CSS3 thing, I think, so maybe IE9+.
http://jsfiddle.net/rudiedirkx/mzCV8/1/
You have to check the checked property to test which one of your radio button is checked:
function readText (form) {
var radios = form.report;
for(var i = 0; i < radios.length; i++){
if(radios[i].checked){
rate_value = radios[i].value;
alert("You entered: " + rate_value)
}
}
}
Or if you use jQuery you could simply use:
$('#reportform input[name="report"]:checked').val();
your code works fine for me :
http://jsfiddle.net/mzCV8/
ensure that the js code is in front of your form
function readText (form) {
var radio = form.report.value;
alert("You entered: " + radio);
}

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");
}

Prevent text entry in textbox unless checkbox is checked

I'm trying to prevent text from being entered in a textbox unless a checkbox that corresponds with the textbox is checked.
// Validate "Other" textbox
var isOther = document.getElementById("isOther");
isOther.addEventListener("input", function (evt) {
// Checkbox must be checked before data can be entered into textbox
if (isOther.checked) {
document.getElementById("other").disabled = false;
} else {
document.getElementById("other").disabled = true;
}
});
Do not use disabled. Instead use readonly. During document load, uncheck and disable the inputs:
<input type="checkbox" id="isOther" />
<input type="text" id="other" readonly />
And use this script.
// Validate "Other" textbox
var isOther = document.getElementById("isOther");
var other = document.getElementById("other");
isOther.addEventListener("click", function () {
other.readOnly = !isOther.checked;
});
other.addEventListener("focus", function (evt) {
// Checkbox must be checked before data can be entered into textbox
other.readOnly = !isOther.checked;
});
Longer version.
// Validate "Other" textbox
var isOther = document.getElementById("isOther");
var other = document.getElementById("other");
isOther.addEventListener("click", function () {
if (isOther.checked) {
other.readOnly = false;
} else {
other.readOnly = true;
}
});
other.addEventListener("focus", function (evt) {
// Checkbox must be checked before data can be entered into textbox
if (isOther.checked) {
this.readOnly = false;
} else {
this.readOnly = true;
}
});
Fiddle: http://jsfiddle.net/praveenscience/zQQZ9/1/
Fiddle: http://jsfiddle.net/praveenscience/zQQZ9/
My solution uses jQuery library. Here's a fiddle: http://jsfiddle.net/8LZNa/
Basically I'm disabling the input on page load:
<input name="isOther" type="checkbox" id="isOther" /><br />
<input type="text" id="other" disabled/>
... and when isOther changes it will make sure it is checked, and change the state to enabled. Or change back to disabled.
$('input[name=isOther]').change(function(){
if($(this).is(':checked')) {
$("#other").removeAttr('disabled');
}
else{
$("#other").attr('disabled','disabled');
}
});
You can do this:
document.getElementById( 'isOther' ).onChange = function(){
document.getElementById("other").disabled = !this.checked;
};
Without the use of jQuery or disabled property:
HTML
<input type="checkbox" id="x" value="Enable textbox" onclick="test(this);" />
<input type="text" id="y" readonly />
JAVASCRIPT
function test(checkbox) {
if(checkbox.checked) {
document.getElementById('y').readOnly = false;
}
else {
document.getElementById('y').readOnly = true;
}
}

Categories

Resources