Disabling a checkbox if a condition is met - javascript

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.

Related

Validate a form with multiple elements?

I have a form that has multiple elements/types
inputs for name, email, address, etc.
radio button for shipping speed.
select tags for "state" & "credit card type".
I want to disable the submit button until the:
1.inputs are filled out.
the select tags have an option selected
the radio is checked.
I've selected the elements (see below);
const btn = document.querySelector('#olegnax-osc-place-order-button');
let inputs = document.querySelectorAll('#olegnax-osc-billing-address-list .required-entry, input#authorizenet_cc_number');
let selectTags = document.querySelectorAll('#olegnax-osc-billing-address-list select, #payment_form_authorizenet select');
let radio = document.querySelector('#s_method_owebiashipping1_id_06');
My question is, being the form consists of 3 different types (input, select, radio), can I just create one array with all of these elements and loop though to make sure the value for each is not blank?
For example, say I store all the different elements in an array called "requiredFields" would this work?:
for (var i = 0; i < requiredFeilds.length; i++) {
if (requiredFeilds[i].value === '') {
btn.disabled = true;
}else {
btn.disabled = false;
}
}
There's a lot more to form validation than meets the eye, but that being said you have a major flaw in your logic. Namely, as you loop over all the fields, you could be changing btn.disabled back and forth depending on the value of the form field (or lack of a value).
Instead, begin with the button disabled, and then instead of looping, use Array.prototype.some (see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) to check if any field is missing a value, something such as:
btn.disabled = requiredFields.some(field => field === '');
There's lots else to address with regards to your approach but this corrects your current logic error and is much more concise.
You can loop through everything but the radio buttons easily. For the radio buttons, you want to check if any of the buttons in a radio group are checked, so it is a little more complicated. It might be easier to just designate a radio button as default, with the checked attribute:
document.querySelector("input[type=submit]").disabled = true;
const inputs = Array.prototype.slice.call(document.forms["form1"].querySelectorAll("input[type=text], select"));
document.forms["form1"].addEventListener("input", () => {
let complete = true;
inputs.forEach((field) => {
if(field.value.trim() === "") {
complete = false;
}
});
document.querySelector("input[type=submit]").disabled = !complete;
});
form{
display:flex;
flex-flow:column;
align-items:flex-start;
}
<form name="form1" id="form1">
<input type="text" name="bar" />
<input type="text" name="foo" />
<select name="biz">
<option disabled selected value>---</option>
<option>One</option>
<option>Two</option>
</select>
<select name="baz">
<option disabled selected value>---</option>
<option>One</option>
<option>Two</option>
</select>
<label>
A <input type="radio" name="buzz" value="a" checked />
</label>
<label>
B <input type="radio" name="buzz" value="b" />
</label>
<input type="submit" value="Submit" />
</form>
Yes, just combine your selectors and use a comma, and check tagName:
const requiredFields = document.querySelectorAll( "
#olegnax-osc-place-order-button,
#olegnax-osc-billing-address-list .required-entry,
input#authorizenet_cc_number,
#olegnax-osc-billing-address-list select,
#payment_form_authorizenet select,
#s_method_owebiashipping1_id_06
" );
for( let input of requiredFields ) {
if( input.tagName == "INPUT" ) {
}
else if( input.tagName == "SELECT" ) {
}
else if( input.tagName == "TEXTAREA" ) {
}
}
You should also use the required attribute too:
<input type="text" required />
<select required></select>
<textarea required></textarea>

Ckeckbox check works when clicked on label only

I have a situation where I need to change the value of the checkbox whether it's checked or not for error validation purposes.
The setup is like this
jQuery(document).ready(function($) {
"use strict";
function toggle_checkbox_value(e) {
var $this = $(e.currentTarget);
e.preventDefault();
if (!$this.data('lockedAt') || +new Date() - $this.data('lockedAt') > 300) {
var $input_terms = $('#terms');
if ($input_terms.val() == '0') {
$input_terms.val('1');
$input_terms[0].checked = true;
} else {
$input_terms.val('0');
$input_terms[0].checked = false;
}
}
$this.data('lockedAt', +new Date());
}
$(document).on('click', 'label[for="terms"]', toggle_checkbox_value)
.on('click', '#terms', toggle_checkbox_value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="terms" type="checkbox" name="terms" value="0">
<label for="terms" class="checkbox">I've read and accept the terms & conditions</label>
I've tried with .attr('checked', 'checked') and with .prop('checked', true) but nothing I did seems to work.
When I click on label, the checkbox will be checked (check mark shown), but when I click on the checkbox, the value changes in DOM when I inspect it, but the check mark is not shown.
What seems to be the issue here?
I am not sure what you are trying to do. But this will work
However your server will only retrieve the terms' value if the checkbox is checked so just test if it is set on the server
jQuery(document).ready(function($) {
"use strict";
$("#terms").on('click',function() {
this.value=this.checked?1:0;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="terms" type="checkbox" name="terms" value="0">
<label for="terms" class="checkbox">I've read and accept the terms & conditions</label>

Prevent checking a checkbox after onclick

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

auto-submit form only if specific number of checkboxes had been checked

I am new to jQuery. I am wondering if there is a way to count the number of checkboxes that have been checked and then auto-submit the form once a specific number of checkboxes had been checked. Let's say the user checks 2 checkboxes, nothing happens. The user checks the 3rd checkbox and the form submits.
<input type="checkbox" onclick="this.form.submit();">
You could try this, using no inline javascript...
HTML
<form>
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
</form>
jQuery
$('input[type="checkbox"]').on('click', function (event) {
var flag = $('input:checked').length > 2 ? true : false;
if (flag) $('form').submit();
});
Fiddle
$('input[type="checkbox"]').on('change', function() {
if( $("input[type="checkbox"]:checked").length >=3) {
$('form').submit();
}
});
JQuery function:
function SubmitIfReady() {
if ($('.checkbox-class:checked').length == 5) { // specify the number you want
$('#YourForm').submit();
}
}
HTML (form not shown):
<input type="checkbox" class="checkbox-class" onclick="SubmitIfReady();">
Or without the onclick:
JQuery function:
$(document).ready(function () {
$('.checkbox-class:checked').on('change', function() {
if ($('.checkbox-class:checked').length == 5) { // specify the number you want
$('#YourForm').submit();
}
});
});
HTML (form not shown):
<input type="checkbox" class="checkbox-class">
Like this...
$(".counted-check").click(function(e){
var myForm = $(this).closest('form');
if(myForm.find(".counted-check").filter(":checked").length > 3){
myForm.submit();
}
});
http://jsfiddle.net/HQ5N9/

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

Categories

Resources