using only javascript to prompt user to choose at least one checkbox - javascript

Hello I have a HTML form which already prompts users to fill empty fields. And this is the script that I am using:
<!-- Script to prompt users to fill in the empty fields -->
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function() {
var elements = document.getElementsByTagName("INPUT");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function(e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("To continue, you must correctly fill in the missing fields.");
}
};
elements[i].oninput = function(e) {
e.target.setCustomValidity("");
};
}
});
</script>
This script works flawlesly and it brings up a nice prompt that looks like this:
It works for all the input text fields, but I need another script that will (a) check if at least one checkbox you can see at the bottom of the form is checked, and (b) will bring up a prompt which is styled the same way as the one above.
I looked at other posts and wrote the below script. I referenced checkboxes by their IDs and somehow used the function function(e) from the above script. Well it won't work for me but I must be close...
<!-- Script which prompts user to check at least one checkbox -->
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function() {
if (
document.getElementById("linux-c-arm-checkbox").checked == false &&
document.getElementById("linux-eda-cad-checkbox").checked == false &&
document.getElementById("linux-blender-checkbox").checked == false &&
document.getElementById("linux-photo-checkbox").checked == false &&
document.getElementById("linux-audio-checkbox").checked == false &&
document.getElementById("linux-latex-checkbox").checked == false &&
document.getElementById("linux-desktop-checkbox").checked == false &&
document.getElementById("linux-office-checkbox").checked == false
){
function(e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("Please choose at least one checkbox.");
}
}
}
});
</script>
Can anyone help me solve this by using javascript without JQuery?

Though there is no way you can put required attribute on a checkbox group and do the validation for atleast one selection, here is a workaround solution. Do the changes accordingly on your HTML.
It takes a hidden textbox as the placeholder of the selected checkbox group. If atleast one is selected the hidden field will also have the value.
function setAccount() {
if (document.querySelectorAll('input[name="gender"]:checked').length > 0)
document.querySelector("#socialPlaceholder").value = document.querySelector('input[name="gender"]:checked').value;
else
document.querySelector("#socialPlaceholder").value = "";
}
function invalidMsg(textbox) {
if (textbox.value == '') {
textbox.setCustomValidity('Please select at least one account');
} else {
textbox.setCustomValidity('');
}
}
<form target="_blank">
<b>Accounts</b>
<input type="text" id="socialPlaceholder" required value="" style="width:0px;height:0px;position: relative;left:-30px;opacity: 0;" oninvalid="invalidMsg(this)"/><br/>
<label>Facebook<input type="checkbox" name="gender" value="facebook" onClick="setAccount()"/></label>
<label>Twitter<input type="checkbox" name="gender" value="twitter" onClick="setAccount()"/></label>
<label>Google Plus<input type="checkbox" name="gender" value="google_plus" onClick="setAccount()"/></label>
<label>Instagram<input type="checkbox" name="gender" value="instagram" onClick="setAccount()"/></label>
</br>
</br>
<input type="submit" value="Submit" />
<br/><br/>
NOTE: Submit without selecting any account to see the validation message
</form>

Your e is null, because you use self executing function inside if and does not pass any event for it.
Try changing e.target to document.getElementById("linux-office-checkbox") or other not-checked element.
In jQuery I would check if any checkbox is selected by doing $('.checkboxClass:checked').length > 0

Related

When using a form that takes to the main website

I am doing a form window before you get in the main website so I tried to make it so that if you don't fill any of the spaces it will open a window alert asking to fill those spaces. Plus I'd like that you would only get to the main website if you fill all the spaces but yet the button on the form window always takes to the main website without requiring filling of the camps.
On the button I wrote this:
<a href="index1.html">
<input type="button" value="Terminar" onclick = location.href='index1.html' >
</a>
and on the js window I wrote the window alert command to each one of the categories:
if(frm.name.value=="" || frm.name.value==null || frm.name.length < 3) {
alert("Please write your first name ")
frm.name.focus();
return false;
It seems you are trying to validate the an input field based on a few criteria.
Your question is not clear. Is this what you are trying to do?
function validateInput() {
if (frm.value == "" || frm.value == null || frm.value.length < 3) {
alert("Please write your first name ")
frm.focus();
} else
location.href = 'index1.html'
}
<input type="text" id="frm" placeholder="Please write your first name" />
<input type="button" value="Terminar" onClick="validateInput()">
You want something like this. In your code the input is wrapped in an a tag. so it will always trigger the event. Adding a button the trigger the event will help.
button = document.getElementById('enter');
input = document.getElementById('fill');
button.onclick = function() {
if (input.value == null || input.value == "" || input.value == " ") {
alert('Please write your first name');
} else {
window.location.href = 'index1.html';
}
};
<input id="fill">
<button id="enter">Enter</button>

Disable form submit button input=text and input=checkbox with jquery

I have a form with three inputs ([type=text], multiple input[type=checkbox] and a disabled submit button).
I want the submit button to be enabled if a user has filled in all three text-inputs and has selected at least one of the checkboxes.
I found this fiddle which works great on all three text-inputs, but I'd like to add the additional condition that at least one checkbox must be selected:
$(document).ready(function() {
var $submit = $("input[type=submit]"),
$inputs = $('input[type=text], input[type=password]');
function checkEmpty() {
// filter over the empty inputs
return $inputs.filter(function() {
return !$.trim(this.value);
}).length === 0;
}
$inputs.on('blur', function() {
$submit.prop("disabled", !checkEmpty());
}).blur(); // trigger an initial blur
});
fiddle
Add class="checkbox" in the checkboxes then modify checkEmpty() to this:
function checkEmpty() {
var text= $inputs.filter(function() {
return !$.trim(this.value);
}).length === 0;
var checkbox = false;
if ($(".checkbox:checked").length > 0) {
checkbox = true;
}
if(text == true && checkbox == true){
return true;
}else{
return false;
}
}
Then add the event on click for the checkboxes which is:
$(".checkbox").on("click", function(){
$submit.prop("disabled", !checkEmpty());
});
Hey just add input[type=checkbox] only in jquery part, here is your desired output, try below code:
Index.html
<form method="POST" action="">
User Name: <input name="Username" type="text" size="14" maxlength="14" /><br />
hobbies:<input type="checkbox" name="cricket">Cricket<input type="checkbox" name="football">football<input type="checkbox" name="hockey">hockey<br>
<input type="submit" value="Login" name="Submit" id="loggy">
</form>
<script src="https://code.jquery.com/jquery-1.12.4.js" integrity="sha256-Qw82+bXyGq6MydymqBxNPYTaUXXq7c8v3CwiYwLLNXU=" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
var $submit = $("input[type=submit]"),
$inputs = $('input[type=text], input[type=checkbox]');
function checkEmpty() {
return $inputs.filter(function() {
return !$.trim(this.value);
}).length === 0;
}
$inputs.on('blur', function() {
$submit.prop("disabled", !checkEmpty());
}).blur();
});
</script>
Ok i have a serious problem now.
I'm using wordpress and added:
<?php wp_head(); ?>
<?php wp_footer(); ?>
To my header.php and footer.php, cause i need them so a plugin is getting loaded.
Since i added them the working solution from Stephan Sutter isn't working anymore. The submit button is still disabled if i fill in all required forms. If i remove them it works again, but i need them for the plugin.
I think it is because the plugin adds input text to the page. Is there any way i can use the code frm Stephan for a defined form ID=#addmovie-form?

Get value from textbox based on checkbox on change event

I have two textboxes and one checkbox in a form.
I need to create a function javascript function for copy the first txtbox value to second textbox on checkbox change event.
I use the following code but its shows null on first time checkbox true.
function ShiptoBill()
{
var billing = document.getElementById("txtbilling").value;
var shipping = document.getElementById("txtshipping").value;
var check = // here i got checkbox checked or not
if(check == true)
{
// here I need to add the txtbilling value to txtshipping
}
}
Given that form controls can be accessed as named properties of the form, you can get a reference to the form from the checkbox, then conditionally set the value of txtshipping to the value of txtbilling depending on whether it's checked or not, e.g.:
<form>
<input name="txtbilling" value="foo"><br>
<input name="txtshipping" readonly><br>
<input name="sameas" type="checkbox" onclick="
this.form.txtshipping.value = this.checked? this.form.txtbilling.value : '';
"><br>
<input type="reset">
</form>
Of course you might want to set the listener dynamically, the above just provides a hint. You could also conditionally copy the contents over if the user changes them and the checkbox is checked, so a change event listener on txtbilling may be required too.
Try like following.
function ShiptoBill() {
var billing = document.getElementById("txtbilling");
var shipping = document.getElementById("txtshipping");
var check = document.getElementById("checkboxId").checked;
if (check == true) {
shipping.value = billing.value;
} else {
shipping.value = '';
}
}
<input type="text" id="txtbilling" />
<input type="text" id="txtshipping" />
<input type="checkbox" onchange="ShiptoBill()" id="checkboxId" />
function ShiptoBill()
{
var billing = document.getElementById("txtbilling");
var shipping = document.getElementById("txtshipping");
var check = document.getElementById("checkboxId").checked; // replace 'checkboxId' with your checkbox 'id'
if (check == true)
{
shipping.value = billing.value;
}
}
To get the event when it changes, do
$('#checkbox1').on('change',function() {
if($(this).checked) {
$('#input2').val($('#input1').val());
}
});
This checks for the checkbox to have a change, then checks if it is checked. If it is, it places the value of Input Box 1 into the value of Input Box 2.
EDIT: Here's a pure JS solution, and a JSBin too.
function ShiptoBill()
{
var billing = document.getElementById("txtbilling").value;
var shipping = document.getElementById("txtshipping").value;
var check = document.getElementById("thischeck").checked;
console.log(check);
if(check == true)
{
console.log('checked');
document.getElementById("txtshipping").value = billing;
} else {
console.log('not checked');
}
}
with
<input id="thischeck" type="checkbox" onclick="ShiptoBill()">

Do not search if the search field is empty (Wordpress)

I have this basic Wordpress search form, I don't want users to be able to search if they leave the search field blank, preferably with javascript, how is this done?
Many ways lead to Rome... But here is one solution.
So, say your search form input field has and id called query and you want to disable the submit button until the user has entered at least 1 character.
$('#query').keyup(function () {
if ($(this).val() == '') {
$('#submit').prop('disabled', true);
} else {
$('#submit').prop('disabled', false);
}
}).keyup();
See this fiddle: https://jsfiddle.net/fxqsc86s/
(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#search').attr('disabled', 'disabled');
} else {
$('#search').removeAttr('disabled');
}
});
})();
and remember to disable the button by default:
<input type="submit" id="search" value="Search" disabled="disabled" />
Answer taken from previous stack overflow question: Disabling submit button until all fields have values
You can also do it like this.
It will check either your TextBox is empty
if ($('#TextBoxId').val() === '') {
// Your coding will go here.
}

Check if all inputs are empty

I have multiple inputs on my page, when any them are filled, an "info div" appears on the side;
Now if all the inputs are manually cleared (on keyup), I need to hide that "info div".
How can I check (on keyup) that all of the inputs are empty at the same time?
Cheers
Loop through all the inputs, and if you get to a non-empty one you know they're not all empty. If you complete your loop without finding one, then they are all empty.
function isEveryInputEmpty() {
var allEmpty = true;
$(':input').each(function() {
if ($(this).val() !== '') {
allEmpty = false;
return false; // we've found a non-empty one, so stop iterating
}
});
return allEmpty;
}
You might want to 'trim' the input value before comparing (if you want to treat an input with just whitespace in it as empty). You also might want to be more specific about which inputs you're checking.
Simple solution (ES6) Without jQuery
html
<div class="container">
<input id="input1" />
<input id="input2" />
<input id="input3" />
</div>
JS
document.getElementById('btnCheckEmpty').addEventListener('click', () => {
if (isEveryInputEmpty())
alert('empty');
else
alert('not empty');
});
const isEveryInputEmpty = () => {
var inputs = document.querySelectorAll('.container input');
for (const input of inputs)
if (input.value !== '') return false;
return true;
}
Online Demo

Categories