javascript validation of radio buttons in a form - javascript

hope someone can shed light on the below code which alerts always the error below. The code was devised to validate one radio button is selected otherwise return false to the current page otherwise proceed with the form action. Thanking in you in advance!!
function onDisplayItemsForm(){
var re = false; // used to determine when a button is checked
var radIdSelected = frmDisplayItems;
// traverse the radio buttons
// if one is checked sets re to true, and stops the iteration
for(var i=0; i<radIdSelected.length; i++)
{
if(radIdSelected[i].checked == true)
{
re = true;
break;
}
if (!radIdSelected[i].checked)
{
alert("Please select product");
return false;
}
return true;
}
};
The form is as follows:
<form name="frmDisplayItems" action="showItem.php" onsubmit="return onDisplayItemsForm();" >
<table width="50%" border="1">
<th>Country of Origin</th>
<th>Select</th>
</tr>
<td><input name=\"radId\" type=\"radio\" value=\"$id\" /></td>
</tbody>
</table>
<p><input name="btnSubmit" type="submit" value="Select"/> </p>
</form>
<

It's the value of re that you want to check after the loop has finished:
if (!re)
{
alert("Please select product");
return false;
}
return true;

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

On click button a validation on checkbox if user selects more than one checkbox, it should allow if user selects only one checkbox

On a button click JavaScript Validation should be: If a user select one checkbox it should allow to process further to any script, but when user selects more than one checkbox it should prompt that "you can select only one check box"
I am not getting to What javaScript I should write ?
<tr><td colspan='2'><input type='checkbox' name='check1' value=12> Q.12 Torronto in located in ?</td></tr>
<tr><td colspan='2'><input type='checkbox' name='check1' value=4> Q.4 Columbo is the capital of which country ?</td></tr>
<tr><td colspan='2'><input type='checkbox' name='check1' value=16> Q.16 Most used social suite ?</td></tr>
<tr><td colspan='2'><input type='checkbox' name='check1' value=19> Q.19 Largest State ?</td></tr>
Function call
<td><input type='submit' type='Edit' value='EDIT' formmethod='post' formaction='/~xyz/cgi-bin/Project/CheckEdit.py' onclick='return(CheckedOne())'></td></tr>
The JS which I tried:
function Checked() {
var d = document.myForm.check1;
var arr = 0;
for (var i = 0; i < d.length; i++) {
if (d[i].checked) {
arr++;
alert(arr);
}
}
if (arr == 1) return true;
else {
alert("Please select only one Checkbox");
return false;
}
}
I think you can do better using the approach by sravis using jQuery.
Here are the issues in your original code:
You call the function CheckedOne in the HTML but have a different name in the JS (Checked).
Also, use document.getElementsByName('check1'); to get the
array.
See http://jsbin.com/iTiQOFIX/1/
jQuery length will get you total checked boxes
http://jsfiddle.net/yAz2j/
$(".subtn").live('click', function() {
var total = $('.check1:checked').length;
if(total > 1) {
alert(" Checked : "+total);
// your code
} else {
alert("Checked only one!");
}
return false;
});
Also check this post: https://stackoverflow.com/a/5594976/1570901

Form validation linking fields as required

I am looking to do some client size validation. Below you will find an example of my template.
When this form is submitted it is okay for a line to be empty. However I want to be sure if even one item in a line is selected/has an entry that all lines will have an entry. For example. There should always be either Nothing OR require a Date, start Time, stop time, and class. (the class is populated by a button in another location) The validation will be used to warn the individual if they are missing anything and if they submit we will disregard the record as incomplete.
I have looked at jquery Validation as we are already using it on other forms in our project but, I have been unable to find a way to link row items together.
<form>
<table id="payableEventTable" class="table table-condensed table-striped">
<thead>
<tr>
<th>Date</th>
<th>Class/Scenario</th>
<th>Start</th>
<th>Stop</th>
<th>Break</th>
</tr>
</thead>
<tbody id="payableEventTableBody">
<c:forEach begin="0" end="5" varStatus="i">
<tr>
<td><input type="date" class="input-small" name="claimForm.payableEvents[${i.index}].eventDate" /></td>
<td>
<select class="classSelect" name="claimForm.payableEvents[${i.index}].event">
<option></option>
</select>
</td>
<td><input type="text" class="input-small" name="claimForm.payableEvents[${i.index}].eventStartTime" /></td>
<td><input type="text" class="input-small" name="claimForm.payableEvents[${i.index}].eventStopTime" /></td>
<td>
<select>
<option value="0" selected>No Break taken</option>
<option value="15">15 Minutes</option>
<option value="30">30 Minutes</option>
<option value="45">45 Minutes</option>
</select>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</form>
Technology we are willing to use. HTML, CSS, javaScript, jQuery, (lightweight plugins for jquery). We also have to make sure the solution works back to IE8.
Edit:
I built a JSFiddle. To help with visualization.
Edit:
I have come up with an answer. However, if anyone is able to improve on my answer, streamline it/make it look nicer I would still be willing to give out the Bounty to that person.
Here is my suggestion: To make your code more legible, you can combine the three functions validateRow(), isRowEmpty(), isRowComplete() into one simpler validateRow() function. Also it is a lot faster, because you only need to go through all elements and check their values once instead of twice.
I also created a simple to use validateForm() function to tidy things up.
The validateForm() function can now be used in an event handler:
// Event Handler
$('#validate').bind('click', function(e){
e.preventDefault();
if(validateForm()) {
alert("next");
//$('#claimWizard').wizard('next');
}
});
// Form Validation
var validateForm = function(){
var valid = true;
$('#payableEventTableBody tr').each(function() {
if (validateRow($(this))) {
$(this).removeClass("error");
}
else {
valid = false;
$(this).addClass('error');
}
});
return valid;
}
var validateRow = function(row){
var state = null,
valid = true;
row.find('input, select').each(function() {
var value = $(this).val(),
isEmpty = (value != 0 && value !== '');
//if its the first element just save the state
if(state === null) {
state = isEmpty;
}
// if this field has not the same state as the rest
else if(state !== isEmpty) {
valid = false;
}
})
return valid;
}
And here's your fiddle with my code implemented: http://jsfiddle.net/KNDLF/
So, what I came up with:
Three methods: isRowValid(), isRowEmpty(), isRowComplete()
The rows need to be either empty or complete.
//The following code is part of my logic on continuing
var valid = true;
$('#payableEventTableBody tr').each(function() {
$(this).removeClass('error');
if (!isRowValid($(this))) {
valid = false;
$(this).addClass('error');
return;
}
});
if (valid) {
$('#claimWizard').wizard('next');
}
//The following is my validation methods
<script type="text/javascript">
function isRowValid($tr) {
return (isRowEmpty($tr) || isRowComplete($tr));
}
function isRowEmpty($tr) {
var isEmpty = true;
$tr.find('input, select').each(function() {
var value = $(this).val();
if (value != 0 && value !== '') {
isEmpty = false;
}
});
return isEmpty;
}
function isRowComplete($tr) {
var isComplete = true;
$tr.find('input, select').each(function(){
var value = $(this).val();
if(value === ''){
isComplete = false;
}
});
return isComplete;
}
</script>
This should be good to start with
http://jsfiddle.net/rJaPR/
$('#validate').bind('click', function(e){
e.preventDefault();
$('#payableEventTable tr').each(function(){
var tr = $(this);
var newRowValue=0;
$(tr).find('input, select').each(function(){
var value = $(this).val();
switch(newRowValue){
case 0:
// first input/select
newRowValue = ((value!=0 && value!='') ? 1 : -1);
break;
case 1:
// there are some values in this row
if (value==0 || value=='')
tr.css('backgroundColor', 'red');
break;
case -1:
// this row should be empty
if (value!=0 && value!='')
tr.css('backgroundColor', 'red');
break;
}
})
})
})

Javascript Drop Down

I'm working on a form that has multiple drop downs which get checked whether the user has selected something or not. Most fields are mandatory so upon clicking submit, red text replaces the black, showing which have to be filled in. It isn't validating for some reason or doing what it is i'm trying to accomplish. Other fields that have a id such as 'literature' work fine but this doesn't. Could it be because it's numeric?
Javascript:
var lit = document.getElementById("012");
var hasLeadLiterature = false;
for (j = 0;) {
if (lit[j].selected === true) {
hasLeadLiterature = true;
break;
}
}
if (!hasLeadLiterature){
changeCSS("lbl_literature", "errored");
ErrorText=ErrorText+"11";
}
------
if (submitcount != 0){
alert("This form has already been submitted. Thank you!");
return;
}
/** Submit form check */
if (ErrorText == ""){
submitcount++; form.submit();
} else{
return;
}
------
HTML:
<TR>
<TD width="30%" valign="middle" ALIGN="left"><LABEL id="lbl_literature" for="lbl_literature" class="normal">How would you prefer to receive<br /> literature?: <SPAN class="required">*</SPAN></LABEL></TD><TD width="70%" valign="top" ALIGN="LEFT">
<TABLE>
<TR>
<td class="text_input"> <!-- 012 -->
<select id="012" name="012" title="Literature Preference">
<option value="None">--None--</option>
<option value="Print">Print</option>
<option value="Digital">Digital</option>
</select>
</td>
</TR>
</TABLE>
</TD>
</TR>
Any help would be much appreciated!!
Thanks in advance!
I believe there is a problem with your for loop, it is not looping anything, have you checked it does loop?
I suggest you read up about how to use a for loop, correct code will be more like:
for (var i=0; i<lit.length; i++)
Because this loop is not valid hasLeadLiterature never changes which by the nature of your code bypasses everything.
It looks like your validation is checking the opposite condition. Take a look:
for (j = 0;) {
if (lit[j].selected === true) {
hasLeadLiterature = true;
break;
}
}
If you get rid of the unnecessary loop structure, you're doing this:
if (lit[0].selected === true) {
hasLeadLiterature = true;
}
In this case, lit[0] is the first, empty option element in the select element. So your condition is saying that if the empty option is selected, the form validates. Shouldn't you reverse that condition? Something like this:
if (lit[0].selected === false) {
hasLeadLiterature = 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