Prevent checking a checkbox after onclick - javascript

How can I prevent that a checkbox gets checked (without the use of disable)?
I tried
function nocheck() {
if(somevar.value>3){
alert("Not allowed");
document.getElementById('mybox').checked = false;
}
};
with
<input type="checkbox" name="mybox" id="mybox" value="test" onclick="nocheck();" />
But this way the checkbox still gets checked after the alert message pops up.
EDIT:
Thanks to the comments/answers, I was able to come closer to a solution but not yet solved the problem - what's wrong with this code? http://jsfiddle.net/9kS8E/1/
HTML
<div class="ez-checkbox">
<input type="checkbox" name="mybox" id="mybox" value="test" onclick="nocheck();" class="ez-hide">
</div>
JS
var user = { premium : false };
function nocheck() {
if(!user.premium){
return false;
} else {
return true;
};
};

i think i not understand your question but i think you are searching this,
<input type="checkbox" name="mybox" id="mybox" value="test" onclick="return false;" />
OR
html
<input type="checkbox" name="mybox" id="mybox" value="test" onclick="nocheck()" />
js
function nocheck() {
if(somevar.value>3){
alert("Not allowed");
return false;
}else
return true;
};

(1) save value of check box in a variable [ while "click" value of checkbox will get changed ]
(2) check user type,
if not a premium user, toggle value of check box.
else no need to change value of checkbox
(*) by using toggle : checkbox is already checked or not, we are not allowing a normal user to check it.
Fiddle : http://jsfiddle.net/aslancods/rQG3r/
<input type="checkbox" name="mybox" id="mybox" value="test" onclick="noCheck(event)" />
var user = { premium : true };
function nocheck(elem) {
var newValue = elem.checked;
if(!user.premium) {
alert("not allowed");
elem.checked = !newValue;// toggle value
} else {
alert(" allowed ");
}
};

Your code should also work.
It's getting unchecked after alert.
You can say alert after unchecking like this.
if(somevar.value>3){
document.getElementById('mybox').checked = false;
alert("Not allowed");
}

Related

Disabling a checkbox if a condition is met

I'm pretty new to Javascript and I have an exercise containing a form and some validation checks,
I have a few inputs such as name, price, and a checkbox and I'm trying to disable the checkbox based on the price input (disable it if it's above 200 and re-enable it if it's less than 200), and at the moment it's not working,
I'll really appreciate suggestions.
That's the Javascript code I've written:
document.addEventListener("DOMContentLoaded", function () {
const price = document.querySelector("[name='purchasePrice']");
price.addEventListener("change", checkPrice);
function checkPrice() {
if (price > 200) {
document.querySelector("[name='chkBx']").disabled = true;
} else {
document.querySelector("[name='chkBx']").disabled = false;
}
}
});
and this is the HTML code:
<div class="item-div">
<label>
Purchase Price
<input
class="inputClass"
type="number"
name="purchasePrice"
min="1"
required
/>
</label>
</div>
<div class="item-div">
<label>
Add Charge
<input type="checkbox" name="chkBx" />
</label>
</div>
Just put a parameter name e in checkprice function.And then you will get access to the target value in change event then your function will work fine.
func checkprice (e)
if(e.target.value > 250)
disable true
else
disable false
end of function
Hope it helps.

checkbox onclick wont change checked via jscript

I have 3 checkboxes, i wish to be able to click the box and it tick on/off and via jscript change the value of the input for posting to state weather item is accepted or not on another page. However i have logical script but it wont work, theres no errors but the checkboxes wont click on/off they just click on and thats it.. and the value wont change either i dont understand why.
Could somebody look at this short code and tell me why.
Thank you.
<input type="checkbox" id="paypal" name="paypal1" value=" " onclick='chbxpp();' >
</input>
<label for="paypal" class="checkboxes" >Show PayPal Accepted</label>
<br>
<input type="checkbox" id="facebook" name="facebook" value=" " onclick='chbxfb(this);' >
</input>
<label for="facebook" class="checkboxes" >Show FaceBook Contact Details</label>
<br>
<input type="checkbox" id="twitter" name="twitter" value=" " onclick='chbxtw(this);' >
</input>
<label for="twitter" class="checkboxes" >Show Twitter Contact Details</label>
function chbxpp()
{
if(document.getElementById('paypal').checked === true) {
document.getElementById('paypal').checked = false;
document.getElementById('paypal').value='no';
var vv=document.getElementById('paypal').value;
console.log(vv);
}
if (document.getElementById('paypal').checked === false) {
document.getElementById('paypal').checked = true;
document.getElementById('paypal').value='yes';
var vv=document.getElementById('paypal').value;
console.log(vv);
}
}
function chbxfb(objfb)
{
var that = objfb;
(objfb);
if(document.getElementById(that.id).checked === true) {
document.getElementById(that.id).checked = false;
document.getElementById(that.id).value='no';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
if (document.getElementById(that.id).checked === false) {
document.getElementById(that.id).checked = true;
document.getElementById(that.id).value='yes';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
}
function chbxtw(objtw)
{
var that = objtw;
(objtw);
if(document.getElementById(that.id).checked === true) {
document.getElementById(that.id).checked = false;
document.getElementById(that.id).value='no';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
if (document.getElementById(that.id).checked === false) {
document.getElementById(that.id).checked = true;
document.getElementById(that.id).value='yes';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
}
The objpp was my attempt at another method but just does the same thing...
p.s if i just didnt use jscript and just had the html, would the value not be valid if the checkbox was not clicked or would the value still be sent...
iv just fond this..
How to change the value of a check box onClick using JQuery?
states that the value wont be sent if the box is unchecked... But then how do i know after post what has been clicked.... will i receieve a not isset($_POST['paypal']) or an empty($_POST['paypal'])
I imagine your checkboxes begin with no check inside them or .checked === false, but when you call your function chbxpp(), it looks to see if your .checked property === true and if so it sets it back to false. The click event already changes the checkbox's .checked property for you, no need to do it in your code.
//If the checkbox is checked, set it to not checked...???
//But the problem is, the click event just set the .checked property to true
//so setting it back to false makes it like it never happened.
if(document.getElementById('paypal').checked === true) {
//document.getElementById('paypal').checked = false; //This part is a no-no
document.getElementById('paypal').value='yes';
}else{
document.getElementById('paypal').value='no';
}
Adding to Ryan Wilson's answer, set your cbx's initial value to false. (Also check the format of the cbx - the closing tag.)
<input type="checkbox" id="paypal" name="paypal1" value="false" onchange="chbxpp();" />
function chbxpp() {
// the cbx starts false. when it is clicked for the first time it
// becomes true.
if (document.getElementById('paypal').checked) {
// you don't need this.
//document.getElementById('paypal').checked = true;
document.getElementById('paypal').value = 'yes';
var vv = document.getElementById('paypal').value;
console.log(vv);
} else {
// you also don't need this.
//document.getElementById('paypal').checked = false;
document.getElementById('paypal').value = 'no';
var vv = document.getElementById('paypal').value;
console.log(vv);
}
}

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

How do I properly validate the form using input radios?

I have a problem with validating the form in function validate() method. This line of code:
if(radios[i].value == "yes" && radios[i].checked == true) //DEBUG INFO: skips this step to else.
is being skipped because one or both of the conditions are false, but I'm not sure which one and as well as if the condition is proper to execute. I was thinking that radios[i].value == "yes" will correspond to the value attribute of that input radio button (In other words, the correct answer regarding that question).
When the submit button is clicked, I simply want javascript to tell me whether it's correct or not and to check if the radio button is checked.
Problem: I checked in the radio button, when submit button is clicked the alert for Please make sure you answer every question pops up 3 times and after that displays that I have the correct answer.
Here's the full code:
JavaScript:
// called when "Take Quiz" button is clicked
function takeQuiz()
{
// hide the intro
document.getElementById('intro').style.display = 'none';
// display the quiz
document.getElementById('message').style.overflow = 'auto';
document.getElementById('quiz').style.visibility = 'visible';
document.getElementById('gl_banner').style.display = 'block';
document.getElementById('gl_banner').style.visibility = 'visible';
}
//document.getElementById('submit').onclick = validateQuiz; //calls the function "validateQuiz" when submit button is clicked
// check for validation in the quiz
function validateQuiz()
{
var radios; // access elements by object name (DOM)
var i; // int variable
var right; // boolean variable to determine correct answer
radios = document.getElementById('question1').getElementsByTagName('input');
/*radios = document.getElementById('question2').getElementsByTagName('input');
radios = document.getElementById('question3').getElementsByTagName('input');
radios = document.getElementById('question4').getElementsByTagName('input');
radios = document.getElementById('question5').getElementsByTagName('input');*/
right = true;
// loop to check each radio button for validation
for(i = 0; i < radios.length; i++)
{
if(radios[i].value == "yes" && radios[i].checked == true) //DEBUG INFO: skips this step to else.
{
right = true;
}
else if(radios[i].checked == false)
{
right = false;
alert("Please check to make sure you have answered every question.");
}
}
if(right)
{
alert("You have answered correctly!");
}
else
{
alert("Wrong answer");
}
}
HTML Code:
<div id="message" style="overflow:hidden;"><div id="intro">Why not go ahead and take the quiz to test your knowledge based on what you've learned in Smartphone Photography.
There are only 5 questions surrounding the content of this site.
<br/>
<button id="takeQuiz" type="button" name="name" onclick="takeQuiz()" style="cursor:pointer;">Take Quiz!</button></div>
<div id="gl_banner" style="display:none; visibility:hidden;">Good Luck! :)</div>
<form id="quiz" action="#" method="post" style="visibility:hidden;" autocomplete="off">
<!--QUIZ-->
<h3>1. How many percent of modern camera phones use CMOS?</h3>
<div id="question1">
<input type="radio" name="question-1-answers" id="question-1-answers-A" value="A" />
<label for="question-1-answers-A">A) 20%</label>
<br/>
<input type="radio" name="question-1-answers" id="question-1-answers-B" value="B" />
<label for="question-1-answers-B">B) 80%</label>
<br/>
<input type="radio" name="question-1-answers" id="question-1-answers-C" value="C" />
<label for="question-1-answers-C">C) 50%</label>
<br/>
<input type="radio" name="question-1-answers" id="question-1-answers-D" value="yes" />
<label for="question-1-answers-D">D) 90%</label>
</div>
**Edited for a pure javascript solution.
I got the function to get the select value from this post.
I don't think you need to do a loop here, as you only actually need to check one value- the value of the checked radio.
At the moment your looping through all the radios, so you'll always get three wrong answers.
**Edited again to fix some code errors. I have tested the following, it is working for me.
function getRadioValue(name) {
var group = document.getElementsByName(name);
for (var i=0;i<group.length;i++) {
if (group[i].checked) {
return group[i].value;
}
}
return '';
}
document.getElementById('submit').onclick = validateQuiz; //calls the function "validateQuiz" when submit button is clicked
// check for validation in the quiz
function validateQuiz(){
right = true;
radio = getRadioValue("question-1-answers");
if(!radio.length) {
right = false;
alert("Please check to make sure you have answered every question.");
return;
}
if(radio == 'yes')
{
alert("You have answered correctly!");
}
else {
right = false;
alert("Wrong answer");
}
}

How do I make sure that at least one checkbox is checked?

I am using checkboxes whose values is coming from database. Its name is same but name is fetching like:
<input type="checkbox" id="chkBankServices" name="<%=bs.getServiceID()%>">
<%=bs.getServiceDesc()%>
through this i am getting the values from the database.
Now i have to validate that at least one checkbox should be selected..
If any one can help me i shall be thankful to u.
If i am giving like this the javascript code:
var services = document.getElementsById( 'chkBankServices' );
if(!(services[0].checked) &&
!(services[1].checked) &&
!(services[2].checked) &&
!(services[3].checked) &&
!(services[4].checked) &&
!(services[5].checked) &&
!(services[6].checked) &&
!(services[7].checked) &&
!(services[8].checked))
{
alert( "Please select at least one service to submit." );
return false;
}
It's not giving any alert message.
Is anything wrong in that.
Plz help me...
Thanks in advance
in jQuery :
alert( $("#chkBankServices input[type=checkbox]:checked").length > 0 );
Try this:
var services = document.getElementById( 'chkBankServices' );
var checkboxes = services.getElementsByTagName('input');
var checked = false;
for (var i=0,i0=checkboxes.length;i<i0;i++)
if (checkboxes[i].type.toLowerCase()=="checkbox")
{
if (checkboxes[i].checked) checked = true;
}
and then:
if (!checked)
{
alert('Not checked');
return false;
}
There is no getElementsById method, since there should only be one element with a given id. Perhaps you meant to use getElementsByName? This allows multiple elements to be returned.
As this is really a client side issue, it would help if you could post a sample of the generated HTML, and we can guide you further.
Have you checked the rendered source to make sure your checkboxes are being given the expected names?
I don't know if this will help you with your specific problem, but your code would be easier to read if you avoided the massive if block and used a loop instead:
var checked = false;
for(var i=0;i<services.length;i++){
if(services[i].checked){
checked = true;
}
}
if(!checked){
alert( "Please select at least one service to submit." );
return false;
}
Looking at your code, I'm betting you have that checkbox in a repeater of some sort and are creating multiple checkboxes with the same ID which is invalid html. I would wrap it in a div/span or something with an id like below:
if (!isSomethingChecked()) {
alert( "Please select at least one service to submit." );
return false;
}
function isSomethingChecked() {
var parent = document.getElementById("chkBankServices");
for (var child in parent.childNodes) {
var node = parent.childNodes[child];
if (node && node.tagName === "INPUT" && node.checked) {
return true;
}
}
return false;
}
I assumed the HTML looks like :
<div id="chkBankServices">
<input type="checkbox" id="Checkbox1" />
<input type="checkbox" id="Checkbox2" checked="checked"/>
<input type="checkbox" id="Checkbox3" checked="checked"/>
<input type="checkbox" id="Checkbox4" />
<input type="checkbox" id="Checkbox5" />
<input type="checkbox" id="Checkbox6" />
<input type="checkbox" id="Checkbox7" />
</div>

Categories

Resources