See if check box is clicked until it is clicked - javascript

I am seeing how I can make an Are You Human checkbox, but I am having a problem (Code At The End). I am trying to make it see if it is clicked until it is clicked. I tried onclick, but that is not working.
window.onload = function() {
var input = document.getElementById('ruhuman');
function check() {
if (input.checked) {
ruhuman.checked = true;
if (event.originalEvent === undefined) {
ruhuman.human = false;
} else {
ruhuman.human = true;
}
}
alert(ruhuman.human);
alert(ruhuman.checked);
}
input.onchange = check;
check();
}
<input type="checkbox" id="ruhuman" class="ruhuman" onclick="check()" required="required">
<label>R U Human?</label>
Edit: Thanks for your help! Finished product at http://ruhuman.github.io/.
To the people that answered I can put your github for your help!

originalEvent is JQuery, not JavaScript. A workaround is to test screenX and screenY -- if it's a human, these will have some value based on the checkbox position. Also, you can remove the onclick from your html and tie your click event like this:
document.getElementById ("ruhuman").addEventListener("click", function(e){
if (this.checked) {
ruhuman.checked = true;
if (e.screenX && e.screenY) {
ruhuman.human = true;
} else {
ruhuman.human = false;
}
}
console.log(ruhuman.human);
console.log(ruhuman.checked);
});
JS Fiddle Demo

This works: https://jsfiddle.net/rz4pmp5L/3/
var input = document.getElementById('ruhuman');
var ruhuman =
{
checked: false
};
function check()
{
if (input.checked)
{
ruhuman.checked = true;
}
alert(ruhuman.checked);
}
input.onchange = check;
check();
The problem was (at least) that ruhuman was not defined at all.

Related

Disable carriage return in onload javascript

I have a web form that uses a check box function. Users are bypassing the consent checkbox, however, as you can just hit a hard return after entering your creds. Trying to get something that will restrict the carriage return bypassing the check box...
function consentCheckBoxChecked() {
debugger;
var submitBtn = document.getElementById("submitButton");
var checkBox = document.getElementById("consentCheckBox");
if (checkBox.checked === true) {
submitBtn.classList.remove("is-disabled");
} else {
submitBtn.classList.add("is-disabled");
}
}
I think you should try something like this, in addition to applying required classes
<body onload="OnLoadEvent();">
</body>
Javascript:
function OnLoadEvent() {
document.getElementById("submitButton").Enabled = false;
}
function consentCheckBoxChecked()
{
var submitBtn = document.getElementById("submitButton");
var checkBox = document.getElementById("consentCheckBox");
if (checkBox.checked) {
submitBtn.Enabled = true;
} else {
submitBtn.Enabled = false;
}
}

How made my function affect the DOM Jquery?

Hi, I have written a webSite on Shopify and I want to disable my button and add some customs CSS class to my input if the input is not filled on my 4steps form.
I've written a piece of code with what I remember from Jquery it's been a long time since I've used this language.
This is the jQuery funct:
$(document).ready(function () {
$("#submitButton, #btn0, #btn1, #btn2").click(function () {
ValidateForm();
});
function ValidateForm() {
var invalidForm = false;
var index = 0;
var button = document.querySelector("#submitButton, #btn0, #btn1, #btn2");
$("#form__form--stepForm-" + index + "input.form__form--input").each(function () {
if ($(this).val() < 1) {
invalidForm = true;
}
});
if (invalidForm === true) {
button.disabled = true;
$("input.form__form--input").removeClass(".form__form--validation").addClass(".form__form--validationInvalid");
} else if (invalidForm === false) {
button.disabled = false;
$("input.form__form--input").removeClass(".form__form--validation").addClass(".form__form--validationValid");
index++;
}
}
});
I made all my inputs like this one:
<div class="3/3 3/3--thumb 3/3--pocket grid__cell--center">
<input type="text" id="form__form--lastnameInput" name="contact[lastname]"
class="form__form--input form__form--validation" placeholder="Nom *" value required>
<div class="form__form--invalidFeedback">Veuillez saisir votre nom.</div>
</div>
And the button like this:
<button id="btn0" type="button" class="button button--primary form__form--button"
aria-label="SUIVANT" title="SUIVANT">
{% include 'icon-arrow-slider' %}
SUIVANT
</button>
As you can see it's a very basic function for the jquery and a classic HTML input but it doesn't block the button and doesn't make the CSS work either. I'd like to understand why and how to make it work for this site and the following thanks for your time and help, take care of yourself!
Your value checking is always false, consider using length function instead:
if ($(this).val().length < 1) {
invalidForm = true;
}
You may also need to prevent default behavior of your form. Instead of listening to the click, listen the submit event:
$("#form__form--contactWrapper").on('submit',function (e) {
e.preventDefault(); //the form is not sent yet
ValidateForm();
});
Then at the end of your function ValidateForm you can send it when you have all your needed validations done, like this:
$("#form__form--contactWrapper").submit();
I have get rid of all error by doing a big refacto of my code i share you my code
$(document).ready(function () {
$('[to-step]').on('click', function () {
var to_step = $(this).attr("to-step");
var current_step = $(this).closest('[stepform]').attr("stepform");
var form_error = false;
if (!($(this).hasClass("previous-btn"))) {
$('[stepform="' + current_step + '"] .form__form--input').each(function () {
if ($(this).val().length == 0) {
$(this).addClass("input--error");
form_error = true;
} else {
$(this).removeClass("input--error");
}
});
}
if (!form_error) {
if (current_step < 4 || $(this).hasClass("previous-btn")) {
$('[stepform').hide();
$('[stepform="' + to_step + '"]').fadeIn();
}
}
});
$("#submitButton").on("click", function (event) {
event.preventDefault();
if ($("#form__form--radioRgpd:checked").length == 1) {
$("#contact_form").submit();
} else {
$(".form__form--radioRgpdLabel").addClass("label--error");
}
});
});
this piece of code gonna check at what step i am in my 4 'pages' form and add the proper css class if the form is bad filled or not filled.

toggle checkbox with javascript

I want to uncheck a checkbox using javascript. I have one button which just unchecks the box and works fine:
function clear() {
document.getElementById("check").checked = "";
}
I have another button that I want to check the box if not checked and uncheck if it is. Below doesn't uncheck the box. I can can switch the if statement and does works the opposite way. What's the problem?
function switchIt() {
if (document.getElementById("check").checked !== "checked") {
document.getElementById("check").checked = "checked";
} else {
document.getElementById("check").checked = "";
}
Thanks!
switch is a reserved word, use another one
function switchIt() {
var box = document.getElementById("check");
if (box.checked) {
box.checked = false;
} else {
box.checked = true;
}
}
setInterval(switchIt, 1000);
<input type="checkbox" id="check" />
Treat "checked" as a boolean, not as a string.
You can just invert it, as in
element = document.getElementById("check")
element.checked = !element.checked
A more featured example:
var $toggle = document.getElementById('toggle');
var $checkbox = document.getElementById('checkbox');
var toggle_checkbox = function() {
$checkbox.checked = !checkbox.checked;
}
$toggle.addEventListener('click',toggle_checkbox);
<label>
Checkbox:
<input id="checkbox" type="checkbox" checked />
</label>
<button id="toggle">Toggle</button>
You need a boolean to do that.
Take a look at this pen:
https://codepen.io/anon/pen/jJyXgO
let checkbox = document.querySelectorAll('#check')[0]
setInterval(function() {
checkbox.checked = !checkbox.checked
}, 1000)
I've never seen it done with a string "checked" before. Try with a boolean like:
function change() {
if (document.getElementById("check").checked !== true) {
document.getElementById("check").checked = true;
} else {
document.getElementById("check").checked = false;
}
}
or easier
function change() {
document.getElementById("check").checked = !document.getElementById("check").checked
}
Don't forget, switch is reserved, so use a different name, as I did with change()

Stop form submission if radio button is checked

I have a form on FormAssembly, and I would like to stop someone submitting the form if they select the 'No' Radio Button for the question 'Are you an employer?'. I have put what I have so far in a jsfiddle.
JS:
$(document).ready(function() {
$('input#tfa_1904').click(function() {
if ($('#tfa_1904').is(':checked') {
submitButton.disabled = true;
}
else {
submitButton.disabled = false;
}
});
});
submitButton code:
document.addEventListener("DOMContentLoaded", function() {
var warning = document.getElementById("javascript-warning");
if (warning != null) {
warning.parentNode.removeChild(warning);
}
var oldRecaptchaCheck = parseInt('0');
if (oldRecaptchaCheck !== -1) {
var explanation = document.getElementById('disabled-explanation');
var submitButton = document.getElementById('submit_button');
if (submitButton != null) {
submitButton.disabled = true;
if (explanation != null) {
explanation.style.display = 'block';
}
}
}
});
In your case you don't need to check whether the radio button is checked as only one will be checked at a time. So, just capturing the click will suffice.
$(document).ready(function() {
$('input#tfa_1904').click(function() {
$('#submit_button').prop('disabled', true);
});
$('input#tfa_1903').click(function() {
$('#submit_button').prop('disabled', false);
});
});
Updated fiddle:
https://jsfiddle.net/h5r8gud1/8/

to add a class when all checkboxes are checked

I'm trying to add a "disabled" class to my button when all the checkboxes are checked and when none of them are checked.
Was able to figure out when none of them are check:
var SummaryCheckBox = function() {
$(':checkbox').click(function () {
$('.btn-primary').toggleClass('disabled', !$(':checkbox:checked').length);
});
}
But having a hard time checking when all the checkboxes are checked. Suggestions?
$(":checkbox").change(function(){
var a = $(":checkbox");
if(a.length == a.filter(":checked").length){
alert('all checked');
}
if(!a.length == a.filter(":checked").length){
alert('all unchecked');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
<input type="checkbox" name="vehicle" value="Car" checked> I have a car<br>
This will remove class disabled if all checkboxes are checked or add it if only one checkbox not checked:
var SummaryCheckBox = function() {
$(':checkbox').click(function () {
$('.btn-primary').toggleClass('disabled', !($(':checkbox:checked').length === $(':checkbox').length));
});
}
var SummaryCheckBox = function() {
$(':checkbox').click(function () {
if($(':checkbox:checked').length == $(':checkbox').length || !$(':checkbox:checked').length){
$('.btn-primary').toggleClass('disabled');
}
});
}
Also you might wanna add some class to checkboxes
Add an additional condition to compare lengths,
$(':checkbox:checked').length === $(':checkbox').length
// ^Checked length ^Total Length
var SummaryCheckBox = function() {
$(':checkbox').click(function () {
$('.btn-primary').toggleClass('disabled', $(':checkbox:checked').length === $(':checkbox').length || !$(':checkbox:checked').length);
});
}
Also, binding a click handler inside a function is not so good idea. Any specific reason for this? Move the .click(..) outside the function.
Fiddle
Fiddle2 with click handler outside the function
function allChecked() {
return $('input[type=checkbox]').not(':checked').length == 0;
}
You can check if it returns true or false, toggle the class you want.
jsfiddle DEMO
$('[type="checkbox"]').on('change', function(){
var l = $('[type="checkbox"]:checked').length;
if(l === 4 || l === 0){
$('[type="submit"]').attr('disabled', '');
} else {
$('[type="submit"]').removeAttr('disabled');
}
});
Digit 4 (number of checkboxes) is hardcoded for simplicity.
Fiddle
Try this code:
$(':checkbox').click(function () {
$('.btn-primary').toggleClass('disabled', !$(':checkbox:checked').length === $(":checkbox").length);
});
You need to check whether checked check boxes are same as total number of check boxes, Then you can add disabled class to the button.
Demo
my two cents will be example code that features a larger code base but tries to be more generic and self-documenting too ...
(function (global, $) {
var
Array = global.Array,
array_from = (
((typeof Array.from == "function") && Array.from)
|| (function (array_prototype_slice) {
return function (list) {
return array_prototype_slice.call(list);
};
}(Array.prototype.slice))
),
isCheckboxControl = function (elm) {
return !!(elm && (elm.type == "checkbox"));
},
isControlChecked = function (elm) {
return !!(elm && elm.checked);
},
validateSubmitState = function (evt) {
var
elmForm = evt.currentTarget.form,
$btnPrimary = $(elmForm).find(".btn-primary"),
checkboxList = array_from(elmForm.elements)
.filter(isCheckboxControl),
isEveryCheckboxChecked = checkboxList
.every(isControlChecked),
isSomeCheckboxChecked = checkboxList
.some(isControlChecked)
;
if (isEveryCheckboxChecked || !isSomeCheckboxChecked) {
$btnPrimary.attr("disabled", "");
} else {
$btnPrimary.removeAttr("disabled");
}
},
initializeSubmitBehavior = function () {
var
$btnPrimary = $(".btn-primary")
;
$btnPrimary // register validation.
.closest("form")
.on("click", ":checkbox", validateSubmitState)
;
// force initial validation.
$btnPrimary.toArray().forEach(function (elmButton) {
var
elmCheckbox = $(elmButton.form).find(":checkbox")[0]
;
if (elmCheckbox) { // initial validation by fake event.
validateSubmitState({currentTarget:elmCheckbox});
}
// just trying not to break this examples form.
elmButton.form.action = global.location.href;
});
}
;
initializeSubmitBehavior();
}(window, jQuery));

Categories