Javascript on checkbox validation? - javascript

I have looked up to many online topics on this question but somehow they did not work for me as the system could not detect whether I have ticked the checkbox or not. I want to ensure the system does not proceed to next page if there were no checkbox checked but it still continues to next page regardless of the javascripts I applied.
I'm not sure if im doing it correctly or may have labelled the code wrongly.
the HTML will generate a list of users dynamically based on users available in database using Thymeleaf
Html
<form th:action="#{/user-profile/delete}" th:object="${deleteUsersForm}" method="POST" onsubmit="return validate();" id="deleteUsersForm">
<tr th:each="user: ${users}">
<td><input type="checkbox" id="checkboxTab" name="deleteUserList" th:value="${user.userId}"></td>
<td th:text="${user.name}"></td>
</tr>
</form>
<button class="btn btn-success btn-icon-split" id="delButton" data-toggle="modal"
data-target="#deleteUserConfirmPopup" onclick="checkButton()">Delete User!</button>
Javascripts that I have tried
function validate(){
var valid = false;
if(document.getElementById('checkboxTab').checked){
valid = true;
}
if (valid){
alert('Please proceed');
} else {
alert('Please tick at least one checkbox!');
return false;
}
}
2nd Javascript attempt
function validate(){
var checkboxTab = document.getElementById('checkboxTab');
for (var i = 0; i < checkboxTab.length; i++) {
if(checkboxTab[i].checked == false){
alert('Nothing is checked');
return false
} else {
return true;
}
}
}
3rd Javascript attempt: Pop-up displays "Please check at least 1 checkbox!" then proceed to continue to next page.
function checkButton(){
var checkboxTab = document.getElementById( 'checkboxTab' );
var isChecked = false;
for (var i = 0; i < checkboxTab.length; i++) {
if ( checkboxTab[i].checked ) {
isChecked = true;
}
}
if ( isChecked ) {
alert( 'Proceeding next page' );
return true;
} else {
alert( 'Please check at least 1 checkbox!' );
return false;
}
}
I even tried jQuery able to show pop-up but it can't seem to detect the checkbox is ticked or not therefore it displayed "not checked" despite ticked the checkbox
$('#delButton').click(function () {
if (!$('#checkboxTab').is(':checked')) {
alert('not checked');
return false;
} else {
return true;
}
});

Related

How to validate JavaScript created element in asp.net core mvc

I have a form which contain elements (checkboxes) that will be produced using JavaScript and I want to check if at least one of them is checked. Also, I have a few inputs that I want to check if at least one of them has value. The initial problem was The code I wrote displayed the error message but immediately submits the form. I can't use server side validation here because these items are created through JS. and I'm not sure if I can use server side validation to check if at least one input field has value.
For this problem I tried using e.preventDefault(); , it stops the form from submitting if there is no value or checkbox not checked but if there was a value it will still not submit the form
This the code I tried
$(function () {
$("#SubmitForm-btn").click(function () {
$("#fupForm").submit(function (e) {
e.preventDefault();
var valid = true;
//here I'm checking if any of the input field has value.
$('#dataTable tbody tr td input[type=text]').each(function () {
var text_value = $(this).val();
if (!hasValue(text_value)) {
valid = false;
$("#tableEmpty").html("Please Choose a Service");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
})
//here I'm checking if any of the checkbox is checked.
$('.check').each(function () {
if (!$(this).is(':checked')) {
valid = false;
$("#Person_errorMSG").html("Please choose a person");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
});
//here I'm checking if any of the checkbox is checked.
$('.Fromcheck').each(function () {
if (!$(this).is(':checked')) {
valid = false;
$("#From_errorMSG").html("Please choose a City");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
});
//here I'm checking if any of the checkbox is checked.
$('.Tocheck').each(function () {
if (!$(this).is(':checked')) {
valid = false;
$("#To_errorMSG").html("Please choose a To city");
return false;
}
else {
$("#fupForm").unbind('submit');
valid = true;
return true;
}
});
});
});
});
You should prevent the button click event, instead of the form submit action.
Please refer the following sample code:
In the View page, we have a mainform.
<form id="mainform" asp-action="AddAttribute">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="AttributeId" class="control-label"></label>
<input asp-for="AttributeId" class="form-control" />
<span asp-validation-for="AttributeId" class="text-danger"></span>
</div>
...
<div class="form-group">
Is Submit <input type="checkbox" class="isSubmit" />
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" id="SubmitForm-btn" />
</div>
</form>
At the end of the above page, add the following script:
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script>
$(function () {
$("#SubmitForm-btn").click(function () {
event.preventDefault(); //prevent the default submit action.
//check if the checkbox is checked or not.
var ischecked = $(".isSubmit").last().is(":checked");
if (ischecked) {
//alert("Checked");
//if the cleckbox checked, submit the form.
$("#mainform").submit();
}
else {
//alert("Unchecked");
//show notification message. and the form will not submit.
}
});
});
</script>
}
The result as below:

JavaScript submits form despite return false statement

I have a python flask webapp and JavaScript front-end. In my front end I am doing all form validations, before submitting it. One such validation is to check the value of a name input field against a list of names(array) I am passing to the template already on GET request. The code below works fine unless it's the last element in the array !!! Then it alerts properly, yet still submits the form. In other words - when rendering the page I am passing the list with all names existing in the database. Then if the same name is provided in the input field, I expect alert and stop execution. In my case, it works fine for all but the last element in the passed array. Then it alerts, yet still submits the form.
My HTML:
function submitServiceForm() {
if ($('#ingested_product_name').val() == '') {
alert("you must specify a product name");
return false;
} else if ($('#ingested_product_features').val() == '') {
alert("you must specify at least one feature");
return false;
} else if ($('#selected_quality_1').val() == null && !$('#no_qualities').is(':checked')) {
alert("you must select at least one Quality");
return false;
} else if ($('#selected_aspect_1').val() == null && !$('#no_qualities').is(':checked')) {
alert("you must select at least one Aspect");
return false;
} else if ($('#ingesting_service').val() == '') {
alert("you must select an ingesting service");
return false;
} else {
let no_qa_check = document.getElementById('no_qualities');
if (no_qa_check.checked) {
let allIngestInPlatform = {
{
allIngestInPlatform | safe
}
};
for (let i = 0; i < allIngestInPlatform.length; i++) {
if ($('#ingested_product_name').val() == allIngestInPlatform[i]['ingested']) {
alert("an Ingested Product with the same name already exists on that platform");
return false;
} else {
document.getElementById('ingested_product_form').submit();
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-row">
<table class="table">
<tr>
<td>
<button type="button" onclick="return submitServiceForm();" class="btn btn-primary">Add Ingested Product</button>
</td>
</tr>
</table>
</div>
Returning false in a submit button click doesn't do anything. A submit button click has a default action of submitting the form. You would need to specifically return false in the onsubmit event instead:
<form .. onsubmit="return submitServiceForm();">
Nowadays people also often prefer to avoid inline Javascript, so with jQuery, that might look more like this:
// Use a more specific selector than this
$('form').on('submit', function(){
return submitServiceForm();
});
Alternatively if you'd like to keep it in onclick, you can use event.preventDefault() instead.
// use a more specific selector than .btn-primary
$('.btn-primary').click(function(e){
if(!submitServiceForm()){
e.preventDefault();
}
});
Change this line on your code
From
for (let i = 0; i < allIngestInPlatform.length; i++)
To
for (let i = 0; i <= allIngestInPlatform.length; i++)

Validating a checkbox after already validating other sections of a form [duplicate]

I have a form with multiple checkboxes and I want to use JavaScript to make sure at least one is checked. This is what I have right now but no matter what is chosen an alert pops up.
JS (wrong)
function valthis(){
if (document.FC.c1.checked) {
alert ("thank you for checking a checkbox")
} else {
alert ("please check a checkbox")
}
}
HTML
<p>Please select at least one Checkbox</p>
<br>
<br>
<form name = "FC">
<input type = "checkbox" name = "c1" value = "c1"/> C1
<br>
<input type = "checkbox" name = "c1" value = "c2"/> C2
<br>
<input type = "checkbox" name = "c1" value = "c3"/> C3
<br>
<input type = "checkbox" name = "c1" value = "c4"/> C4
<br>
</form>
<br>
<br>
<input type = "button" value = "Edit and Report" onClick = "valthisform();">
So what I ended up doing in JS was this:
function valthisform(){
var chkd = document.FC.c1.checked || document.FC.c2.checked||document.FC.c3.checked|| document.FC.c4.checked
if (chkd == true){
} else {
alert ("please check a checkbox")
}
}
I decided to drop the "Thank you" part to fit in with the rest of the assignment. Thank you so much, every ones advice really helped out.
You should avoid having two checkboxes with the same name if you plan to reference them like document.FC.c1. If you have multiple checkboxes named c1 how will the browser know which you are referring to?
Here's a non-jQuery solution to check if any checkboxes on the page are checked.
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
var checkedOne = Array.prototype.slice.call(checkboxes).some(x => x.checked);
You need the Array.prototype.slice.call part to convert the NodeList returned by document.querySelectorAll into an array that you can call some on.
This should work:
function valthisform()
{
var checkboxs=document.getElementsByName("c1");
var okay=false;
for(var i=0,l=checkboxs.length;i<l;i++)
{
if(checkboxs[i].checked)
{
okay=true;
break;
}
}
if(okay)alert("Thank you for checking a checkbox");
else alert("Please check a checkbox");
}
If you have a question about the code, just comment.
I use l=checkboxs.length to improve the performance. See http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/
I would opt for a more functional approach. Since ES6 we have been given such nice tools to solve our problems, so why not use them.
Let's begin with giving the checkboxes a class so we can round them up very nicely.
I prefer to use a class instead of input[type="checkbox"] because now the solution is more generic and can be used also when you have more groups of checkboxes in your document.
HTML
<input type="checkbox" class="checkbox" value=ck1 /> ck1<br />
<input type="checkbox" class="checkbox" value=ck2 /> ck2<br />
JavaScript
function atLeastOneCheckboxIsChecked(){
const checkboxes = Array.from(document.querySelectorAll(".checkbox"));
return checkboxes.reduce((acc, curr) => acc || curr.checked, false);
}
When called, the function will return false if no checkbox has been checked and true if one or both is.
It works as follows, the reducer function has two arguments, the accumulator (acc) and the current value (curr). For every iteration over the array, the reducer will return true if either the accumulator or the current value is true.
the return value of the previous iteration is the accumulator of the current iteration, therefore, if it ever is true, it will stay true until the end.
Check this.
You can't access form inputs via their name. Use document.getElements methods instead.
Vanilla JS:
var checkboxes = document.getElementsByClassName('activityCheckbox'); // puts all your checkboxes in a variable
function activitiesReset() {
var checkboxesChecked = function () { // if a checkbox is checked, function ends and returns true. If all checkboxes have been iterated through (which means they are all unchecked), returns false.
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
return true;
}
}
return false;
}
error[2].style.display = 'none'; // an array item specific to my project - it's a red label which says 'Please check a checkbox!'. Here its display is set to none, so the initial non-error label is visible instead.
if (submitCounter > 0 && checkboxesChecked() === false) { // if a form submit has been attempted, and if all checkboxes are unchecked
error[2].style.display = 'block'; // red error label is now visible.
}
}
for (var i=0; i<checkboxes.length; i++) { // whenever a checkbox is checked or unchecked, activitiesReset runs.
checkboxes[i].addEventListener('change', activitiesReset);
}
Explanation:
Once a form submit has been attempted, this will update your checkbox section's label to notify the user to check a checkbox if he/she hasn't yet. If no checkboxes are checked, a hidden 'error' label is revealed prompting the user to 'Please check a checkbox!'. If the user checks at least one checkbox, the red label is instantaneously hidden again, revealing the original label. If the user again un-checks all checkboxes, the red label returns in real-time. This is made possible by JavaScript's onchange event (written as .addEventListener('change', function(){});
You can check that atleast one checkbox is checked or not using this simple code. You can also drop your message.
Reference Link
<label class="control-label col-sm-4">Check Box 2</label>
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck1 /> ck1<br />
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck2 /> ck2<br />
<script>
function checkFormData() {
if (!$('input[name=checkbox2]:checked').length > 0) {
document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
return false;
}
alert("Success");
return true;
}
</script>
< script type = "text/javascript" src = "js/jquery-1.6.4.min.js" > < / script >
< script type = "text/javascript" >
function checkSelectedAtleastOne(clsName) {
if (selectedValue == "select")
return false;
var i = 0;
$("." + clsName).each(function () {
if ($(this).is(':checked')) {
i = 1;
}
});
if (i == 0) {
alert("Please select atleast one users");
return false;
} else if (i == 1) {
return true;
}
return true;
}
$(document).ready(function () {
$('#chkSearchAll').click(function () {
var checked = $(this).is(':checked');
$('.clsChkSearch').each(function () {
var checkBox = $(this);
if (checked) {
checkBox.prop('checked', true);
} else {
checkBox.prop('checked', false);
}
});
});
//for select and deselect 'select all' check box when clicking individual check boxes
$(".clsChkSearch").click(function () {
var i = 0;
$(".clsChkSearch").each(function () {
if ($(this).is(':checked')) {}
else {
i = 1; //unchecked
}
});
if (i == 0) {
$("#chkSearchAll").attr("checked", true)
} else if (i == 1) {
$("#chkSearchAll").attr("checked", false)
}
});
});
< / script >
Prevent user from deselecting last checked checkbox.
jQuery (original answer).
$('input[type="checkbox"][name="chkBx"]').on('change',function(){
var getArrVal = $('input[type="checkbox"][name="chkBx"]:checked').map(function(){
return this.value;
}).toArray();
if(getArrVal.length){
//execute the code
$('#msg').html(getArrVal.toString());
} else {
$(this).prop("checked",true);
$('#msg').html("At least one value must be checked!");
return false;
}
});
UPDATED ANSWER 2019-05-31
Plain JS
let i,
el = document.querySelectorAll('input[type="checkbox"][name="chkBx"]'),
msg = document.getElementById('msg'),
onChange = function(ev){
ev.preventDefault();
let _this = this,
arrVal = Array.prototype.slice.call(
document.querySelectorAll('input[type="checkbox"][name="chkBx"]:checked'))
.map(function(cur){return cur.value});
if(arrVal.length){
msg.innerHTML = JSON.stringify(arrVal);
} else {
_this.checked=true;
msg.innerHTML = "At least one value must be checked!";
}
};
for(i=el.length;i--;){el[i].addEventListener('change',onChange,false);}
<label><input type="checkbox" name="chkBx" value="value1" checked> Value1</label>
<label><input type="checkbox" name="chkBx" value="value2"> Value2</label>
<label><input type="checkbox" name="chkBx" value="value3"> Value3</label>
<div id="msg"></div>
$('input:checkbox[type=checkbox]').on('change',function(){
if($('input:checkbox[type=checkbox]').is(":checked") == true){
$('.removedisable').removeClass('disabled');
}else{
$('.removedisable').addClass('disabled');
});
if(($("#checkboxid1").is(":checked")) || ($("#checkboxid2").is(":checked"))
|| ($("#checkboxid3").is(":checked"))) {
//Your Code here
}
You can use this code to verify that checkbox is checked at least one.
Thanks!!

Two inputs with the same name

I'm working on a webapp that has several forms. The problem comes when two inputs have the same name. I want to alert user if no one is selected. That works perfectly on Chrome, but Firefox can't say me if both of them aren't treated.
JScript:
function validateForm(assignmentForm)
{
doc = document.getElementById(assignmentForm);
var messages = [];
valid = true;
if (doc.ambit.value=="")
{
messages.push("One of two ambits must be selected");
valid = false;
}
if (doc.name.value=="")
{
messages.push("Write a name");
valid = false;
}
if(!valid){
alert(messages.join('\n'));
return false;
}
return true;
}
HTML:
<input name="name" type="text"></input>
<input name="ambit" type="radio" value="center" ></input>
<input name="ambit" type="radio" value="titulation"></input>
<input type="submit" value="submit"/>
When I submit this form without selecting any of two radius, Chrome alerts me with "One of two ambits must be selected". But Firefox doesn't notify me of anything.
My first though was to give an ID to both inputs and treat them separately, but is it possible to fix this with another option?
For firefox doc.ambit.value is coming as array
So put this check,
ischecked_method = false;
for ( var i = 0; i < doc.ambit.length; i++) {
if(doc.ambit[i].checked) {
ischecked_method = true;
break;
}
}
if (!ischecked_method)
{
messages.push("One of two ambits must be selected");
valid = false;
}
Instead of assuming form is valid first and checking if it's not, try assuming it's not valid and checking to see if it is.
Then you can loop through each radio button and set valid to true if you find one which is checked. Like this:
var valid = false;
var ambitValues = doc.getElementsByName('ambit')
for (var i = 0; i < ambitValues.length; i++) {
if (ambitValues[i].checked) {
valid = true;
}
};

Validating a single radio button is not working in available javascript validation script

I have randomly generated radio button series like
<input type="radio" name="creatorusers" value="1">
<input type="radio" name="creatorusers" value="1">
<input type="radio" name="creatorusers" value="1">
<input type="radio" name="creatorusers" value="1">
.....so on
But I get only ONE radio button and execute the javascript validation given for it to chk whether the radio button is selected or not, then it doesnt work
Ples help me out in resolving this.
mycreator = -1;
for (i=frm.creatorusers.length-1; i > -1; i--) {
if (frm.creatorusers[i].checked) {
mycreator = i; i = -1;
}
}
if (mycreator == -1) {
alert("You must select a Creator User!");
return false;
}
Always (!) use the var keyword. Otherwise your variables will be in the global scope (yes, even those in function bodies), which can make for some bugs that are hard to track down.
As #Felix pointed out, creatorusers will only be an array if there is more than one element with that name in the form. You can create a single-element array when necessary to work around that.
Here is an abstracted function that can validate an arbitrary checkbox list.
function ensureChecked(checkboxes, error) {
if (checkboxes) {
var cbx = (checkboxes.length > 0) ? checkboxes : [checkboxes];
for (var i=0; i<cbx.length; i++) {
if (cbx[i].checked) {
return true;
}
}
alert(error);
}
return false;
}
call as
ensureChecked(frm.creatorusers, "You must select a Creator User!");
Ah now I got. If you only have one radio button, then frm.creatorusers is not an array. Just skip it:
var mycreator = -1;
var checked = false;
if(typeof frm.creatorusers.length === 'number') {
for (var i=frm.creatorusers.length; i--; ) {
if (frm.creatorusers[i].checked) {
mycreator = i;
checked = true;
break;
}
}
}
else if(frm.creatorusers.checked){
mycreator = //? what here?
checked = true;
}
if(!checked) {
alert("You must select a Creator User!");
return false;
}
If mycreator was just for checking whether a button was selected or not, you can completely remove it from the code above.
Some further notes to your code:
Always declare variables with var, otherwise they will be global.
Use break to end a loop.
Maybe it is just because of copy and paste, but having a lot of radio buttons with the same value does not make much sense.
You can do something like this:
function validate(frm){
var isChecked = false;
for (var i=0; i<frm.elements.length; i++)
{
if (frm.elements[i].type === 'radio'){
if (frm.elements[i].checked === true){
isChecked = true;
break;
}
}
}
if (isChecked === true){
return true;
}
else{
alert('You should select an option first !');
}
}
Now you should call above function on onsubmit event of the form:
<form onsubmit="return validate(this);">
Now the validate function will make sure that at least one radio button is checked otherwise it won't submit.
this should do it
function isRadioSelected(btn) {
if(typeof btn.length === 'number') {
for(var i=0;i<btn.length;i++)
if(btn[i].checked) return true
}else{
if(btn.checked) return true
}
return false
}
You could try something like this instead:
<html>
<head>
<script type="text/javascript">
function confirmsubmit() {
var btn = document.formname.buttonname
if (btn.checked == false)
{
window.alert("You did not click the button.");
btn.focus();
return false;
}
return true;
}
</script>
</head>
<body>
<form method="post" action="mailto:youremail#yourdomain.com"
name="formname" onsubmit="return confirmsubmit();">
click here: <input type="radio" name="buttonname"><br />
<p><input type="submit" value="Submit" name="submit"></p>
</form>
</body>
</html>

Categories

Resources