alert not generated even when none of the applicants have selected checkbox - javascript

In a form can create more than 1 applicant, each applicant has a checkbox field. While submission of form it has to check atleast for 1 applicant checbox field has to be selected.code snippet below not working.Could some one help with the script.
function FF_OnBeforeSave() {
for(var i = 1; i < repeat; i++){
var primaryElement = Primary(i);
console.log("primaryElement.. "+primaryElement);
var prim = $(primaryElement).val ();
console.log("prim.. "+prim);
if(prim !== false ){
}
else {
alert('Please select atleast 1 primary');
$('#btnsubmit').removeAttr('disabled');
return false;
}
}
$('#btnsubmit').removeAttr('disabled');
return true;
}

I believe you are using the wrong method of interface with the check box.
http://api.jquery.com/prop/
Try using
$(primaryElement).prop("checked");

Related

Javascript on checkbox validation?

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

Return false if no value is selected (other than heading) from select box

I have a HTML form having select box. On selection of first drop down, next drop down should be auto filled using AJAX.
On Download Records (id="getCsv") button click event a CSV file is generated. Problem is, I want to make all the fields mandatory. Here is the jquery code
var teacher_name = $("#sel_teacher option:selected").text();
var unittest_name = $("#sel_test1 option:selected").text();
var class_name = $("#sel_class1 option:selected").text();
var class_id = $('#sel_class1').val();
var division_name = $("#sel_div1 option:selected").text();
var division_id = $('#sel_div1').val();
var subject_name = $("#sel_sub1 option:selected").text();
if (teacher_name == "") {
alert('Please Select Teacher Name.');
return false;
} else if(class_name == "") {
alert('Please Select Class Name.');
return false;
} else if(division_name == "") {
alert('Please Select Division Name.');
return false;
} else if(subject_name == "") {
alert('Please Select Subject Name.');
return false;
} else if(unittest_name == "") {
alert('Please Select Unit Test Name.');
return false;
} else {
var myObject = new Object();
myObject.class_name = class_name;
myObject.class_id = class_id;
myObject.division_name = division_name;
myObject.division_id = division_id;
myObject.subject_name = subject_name;
myObject.test_name = unittest_name;
var formData = JSON.stringify(myObject);
$('#getCsv').attr('href','csv_generator.php?data=' + formData);
}
The problem is that when I click Download Records, even though the first select box is empty directly alert box for second select box pops up. I tried to solve this problem using the below, but no luck.
if ($("#sel_teacher").attr("selectedIndex") == 0) {
alert("You haven't selected anything!");
return false;
}
Can anybody please help me with this? Any help is appreciated.
selectedIndex is a property, use prop:
$("#sel_teacher").prop("selectedIndex")
Also, you can simplify your code by retrieving the selected value using just $("#sel_teacher").val() and compare to empty string (assuming the value of that option is empty).
var teacher_name = $("#sel_teacher").val();
// get other <select /> values here...
if (teacher_name == '') {
alert("You haven't selected anything!");
return false;
}
// test other values here...
It might be because of the default value that you have given for the first text-box.Just change the value to "" onclick or on blur on that text-box.
Or you can simply handle this matter via HTML5 attribute required and adding onchange() Event Listener .
<select name="sel_teacher" onchange="get_value();" id="sel_teacher" required>
<option>--Select Teacher Name--</option>
</select>
<script>
function get_value() {
var teacher_name = $("#sel_teacher").val();
// get other <select /> values here...
if (teacher_name == '') {
alert("You haven't selected anything!");
return false;
} else {
// write code when teacher_name is selected
}
}
</script>

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!!

How to check drop-down values using JavaScript

I have drop-down and Textbox inside a Gridview so I want to check the followings on a button click:
(1) Check if NOTHING is selected from the drop down first (the drop-down options are either YES, NO or NA) . If nothing is selected, I want to show message that reads like this “Please make selection from the drop-down”
(2) If the selection from the drop-down is NO and the Textbox is blank or empty then I want to show message that says: “Please provide comments”
The first code checks if the text-box is blank and it works and the 2nd code checks if no selection is made from the drop down and that one works fine too so how can i combine between those 2 codes? I want to execute both codes on button click, right now it is only calling the first code. please help. Thanks.
here is my code that checks if the textbox is blank:
<script type ="text/javascript">
function Validate() {
var flag = false;
var gridView = document.getElementById('<%= GridView1.ClientID %>');
for (var i = 1; i < gridView.rows.length; i++) {
var selects = gridView.rows[i].getElementsByTagName('select');
var areas = gridView.rows[i].getElementsByTagName('textarea');
if (selects != null && areas != null) {
if (areas[0].type == "textarea") {
var txtval = areas[0].value;
var selectval = selects[0].value;
if (selectval == "No" && (txtval == "" || txtval == null)) {
flag = false;
break;
}
else {
flag = true;
document.getElementById('<%=btnSubmit.ClientID%>').style.visibility = 'visible';
}
}
}
}
if (!flag) {
alert('Please note that comments are required if you select "No" from the dropdown box. Thanks');
document.getElementById('<%=btnSubmit.ClientID%>').style.visibility = 'hidden';
}
return flag;
}
</script>
and here is the code that checks the drop-down
<script type="text/javascript">
function validate_DD() {
var flag = true;
var dropdowns = new Array(); //Create array to hold all the dropdown lists.
var gridview = document.getElementById('<%=GridView1.ClientID%>'); //GridView1 is the id of ur gridview.
dropdowns = gridview.getElementsByTagName('Select'); //Get all dropdown lists contained in GridView1.
for (var i = 0; i < dropdowns.length; i++) {
if (dropdowns.item(i).value == 'Select') //If dropdown has no selected value
{
flag = false;
break; //break the loop as there is no need to check further.
}
}
if (!flag) {
alert('Please select either Yes, No or NA in each dropdown and click the Save button again. Thanks');
document.getElementById('<%=btnSubmit.ClientID%>').style.visibility = 'hidden';
}
return flag;
}
</script>
Try this:
<select id="ddlCars">
<option value="1">Honda</option>
<option value="2" selected="selected">Toyota</option>
<option value="3">BMW</option>
</select>
Accessing dropdown:
To get the value:
var el = document.getElementById("ddlCars");
var val = el.options[el.selectedIndex].value; // val will be 2
To get the text:
var el = document.getElementById("ddlCars");
var car = el.options[el.selectedIndex].text; //car will be Toyota

Simple JavaScript check not working?

I have this validate form function:
function ValidateForm() {
var chks = document.register.elements['sendto[]'];
var hasChecked = false;
for (var i=0;i<chks.length;i++){
if (chks[i].checked){
hasChecked = true;
break;
}
}
if (!hasChecked){
alert("Please select at least one friend.");
chks[0].focus();
return false;
}
}
html for this is:
<input type="checkbox" name="sendto[]" value="2" >
I know this is not full code. Full code is huge. But basically if i have only one checkbox in the code the above code gives a message undefined on ValidateForm(). Which is called when form is submitted and and above checkbox is checked.
But if i have two checkboxes in the code like this:
<input type="checkbox" name="sendto[]" value="2" >
<input type="checkbox" name="sendto[]" value="4" >
On submit when ValidateForm() function is called this works correctly. Am i doing something wrong that it is not working for 1 checkbox even if it is checked?
The statement
var chks = document.register.elements['sendto[]'];
gets the element (element*s*, if there are more then one) with namesendto[]
If there is only one element with name sendto[] then you have the reference of that element in chks.
If there are more than one element with name sendto[], then chks holds the reference to the array of those elements.
When you do this:
for (var i=0;i<chks.length;i++){
You try to loop based on chks.length. If chks is an array (see above: when there are multiple elements by name sendto[]), then chks.length will hold the number of elements in the array.
If there is only one sendto[] element, then chks will hold that element and since the element (<input type="checkbox" name="sendto[]" value="2" >) does not have a property called length, the browser says length is indefined
So you have o differentiate between two scenarios, when there is only one sendto[] checkbox and when there are more than one.:
var chks = document.register.elements['sendto[]'];
var hasChecked = false;
//Check whether there is one checkbox or whether there are more
if(chks.length)
{
for (var i=0;i<chks.length;i++)
{
if (chks[i].checked)
{
hasChecked = true;
break;
}
}
}
else
{
if(chks.checked)
{
haschecked = true;
}
}
PS:
code gives a message undefined on ValidateForm() does not convey much. Even for you it is not clear what this means right (That's why you have asked this question). Try to give more details. Any modern browser will give more details on the undefined, the what is undefined which line etc. Even pre-historic browsers will tell you the line number where the undefined error was thrown. With those details you can try to find the line and try to see what is happening. You most likely will find out. If you don't, post it to the community here with all these details.
<script language="javascript">
function validate() {
var chks = document.getElementsByName('sendto[]');
var hasChecked = false;
for (var i = 0; i < chks.length; i++) {
if (chks[i].checked) {
hasChecked = true;
break;
}
}
if (hasChecked == false) {
alert("Please select at least one friend.");
return false;
}
return true;
}
</script>
Here is how I would do it.
if(!validate()){
alert("Please select at least one.");
return false;
}
function validate(){
var els=document.getElementsByName('sendto[]');
for(var i=0;i<els.length;i++){
if(els[i].checked){
return true;
}
}
return false;
}
You could use validate as an anonymous function.

Categories

Resources