onclick for radio button using javascript - javascript

I am trying to write this program for this survey I want a user to answer, after they have completed the survey they would go to click on submit and it would display confirmation of their choices. I can't get this to work for the life of me.
Here's my code:
<!DOCTYPE html>
<title> Satisfaction Survey </title>
<script Language ="Javascript">
function testpage() {
errmsg = " ";
confirmmsg = " ";
errflag = false;
if ( document.form1.rdservice[0].checked == true ) {
confirmmsg = confirmmsg + "<br> Overall is very satsified" ;
}
if ( document.form1.rdservice[1].checked == true ) {
confirmmsg = confirmmsg + "<br> Overall is satisfied" ;
}
if ( document.form1.rdservice[2].checked == true ) {
confirmmsg = confirmmsg + "<br> Overall is neutral" ;
}
if ( document.form1.rdservice[3].checked == true ) {
confirmmsg = confirmmsg + "<br> Overall is unsatsified" ;
}
if ( document.form1.rdservice[4].checked == true ) {
confirmmsg = confirmmsg + "<br> Overall is very unsatsified" ;
}
if ( (doucment.form1.rdservice[0].checked == false) &&
(doucment.form1.rdservice[1].checked == false) &&
(doucment.form1.rdservice[2].checked == false) &&
(doucment.form1.rdservice[3].checked == "false") &&
(doucment.form1.rdservice[4].checked == false)) {
errflag = true;
errmsg = errmsg + "<br> You forgot to select an option";
}
}
</script>
<body>
<form name=form1 method="post">
<fieldset>
<legend> Please take a few moments to complete this satisfaction survey. </legend>
<fieldset>
<legend> Overall, how satisfied were you with the product / service? </legend>
<input type="radio" name="rdservice" value="v"> Very Satisfied
<br>
<input type="radio" name="rdservice" value="s"> Satisfied
<br>
<input type="radio" name="rdservice" value="n"> Neutral
<br>
<input type="radio" name="rdservice" value="un"> Unsatisfied
<br>
<input type="radio" name="rdservice" value="vu"> Very Unsatisfied
</fieldset>
<fieldset>
<input type="submit" name="subm1" value="Submit" onclick="testpge()">
<input type="Reset" name="Res1" value="Reset Form">
</fieldset>
</fieldset>
</body>
</form>
</html>

The code is a bit mess, can I suggest to use jquery(https://jquery.com/download/)? It will make your life a lot of easier!
here is the jquery code that you need:
var confirmmsg = "";
var errflag = false;
var errmsg = "";
$.each($('form input[type=radio]'), function() {
if($(this).is(":checked")) {
confirmmsg += "<br> Overall is " + $(this).text();
} else {
errflag = true;
}
});
if (errflag) {
errmsg = "<br> You forgot to select an option";
}
This code takes each input radio element and check if it's checked and then make the confirmmsg and also if one of them it's not checked then the errflag becomes true and also you set up the errmsg
btw, I think you need checkbox instead of radio inputs here

(non jquery approach)
Form inputs that are "button" are simply buttons. You can attach event to those inputs, but they aren't related to submitting form. If you want to make button which will send form you should set "type" attribute to "submit". And then you can verify your form in JavaScript by adding event "onsubmit" to <form> tag, not the button. You can also use "onreset" to catch event if someone press button which cleans form. If you are adding "onsubmit" function, like:
onsumit="return testpage(this);"
you can easy decide inside that function, if form should be send or not. You can do this by returning value. If you return true, form will be send, and if you return false form will not be send. You can also disable sending form by setting "action" attribute of <form> tag to "javascript:void(0);"
In your code i would add "onsubmit" event to <form> tag and i would remove "onclick" from submit button (you are calling function and then posting form) and i also would change function code to:
function testpage(frm)
{
var radioBoxSelected = false;
for(var i=0; i < frm.elements.length;i++)
{
if (frm.elements[i].type == 'radio' && frm.elements[i].checked) {
radioBoxSelected = true;
val = frm.elements[i].value;
// You can move messages to attribute "value" of radio boxes
alert('You have selected: ' + val);
// Below line sets some tag inner content to radiobox "value" attribute
document.getElementById("satisfied_value").innerHTML = val;
// Uncomment if you want send form here
//return true;
}
}
if (!radioBoxSelected) {
alert('Please select option!');
return false;
}
}

Related

How do you validate multiple radio buttons at one time without jQuery?

I am writing a validation function for a html code that was given to me for my class, but am not allowed to change the html code besides adding a head and script. I am at such an early stage that I don't know how to use jQuery yet and would like help with validation for the multiple radio buttons.
I have tried looking for the answer on this and many other sites and just can't seem to find it. I have tried multiple codes, but I suspect that all of them were made with jQuery.
The input for the html
<input type = "radio" name = "radNewsletter" value = "" />Health and Wellness<br />
<input type = "radio" name = "radNewsletter" value = "" />Creative Writing<br />
<input type = "radio" name = "radNewsletter" value = ""/>Gardening
The existing validation
function validateForm() {
var x = document.forms["frmNews"]["txtName"].value;
if (x == "") {
alert ("Name must be filled out.");
return false;
}
var y = document.forms["frmNews"]["txtEmail"].value;
if (y == "") {
alert ("Email must be filled out.");
return false;
}
I was unable to get any other output than the form validating when I pressed the submit button, even when the existing validation should have stopped it.
I found that radNewsletter is a common name in your form. In order to validate forms for radio buttons, you can use below code.
function validateForm() {
var radios = document.getElementsByName("radNewsletter");
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) formValid = true;
i++;
}
if (!formValid) alert("Must check some option!");
console.log(formValid)
return formValid;
}
<input type = "radio" name = "radNewsletter" value = "" />Health and Wellness<br />
<input type = "radio" name = "radNewsletter" value = "" />Creative Writing<br />
<input type = "radio" name = "radNewsletter" value = ""/>Gardening
<br />
<button onclick="validateForm()">Validate
</button>
function validateForm() {
var radios = document.getElementsByName("radNewsletter");
if(!radios.checked)
{
alert("we are testing")
}
if(radios.checked = true){
alert("your checking the boxs")
}
}
Use document.querySelector and pusedo selector checked. This line document.querySelector('input[name="radNewsletter"]:checked') will give the first radio button with the name radNewsletter which is checked. On click of button check if this value is not null. Hopefully you can validate using this
function validate() {
let isChecked = document.querySelector('input[name="radNewsletter"]:checked');
if (isChecked !== null) {
console.log(isChecked.value);
}
}
<input type="radio" name="radNewsletter" value="hw">Health and Wellness<br />
<input type="radio" name="radNewsletter" value="cw">Creative Writing<br />
<input type="radio" name="radNewsletter" value="g">Gardening<br/>
<button type='button' onclick='validate()'>Validate</button>

JavaScript validate, then print and submit

I have a submit function to validate form inputs, then optionally (checkbox) print as part of the submit process.
The problem is that when printed, form submission never completes, without printing form submission works correctly.
<INPUT class=checkboxes id="Place order" onclick="return checkfields()" type=submit value=SUBMIT name="Place order">
The validation always works correctly (AFAIK).
function checkfields() {
var missinginfo="Please fill the following information";
var bres = true, qty=0, elem;
var tqty = document.getElementById('bottles').value;
if (tqty ==0){alert("No wine selected");bres=false;return bres;}
if (tqty %6 !=0){
alert("Orders need to be in 6 bottle packs please add " + (6 -(tqty %6)) + " Bottles to order");
bres=false;
return bres;
} //end if
for (i=1; i<30; i++) {
elem = document.getElementById('f'+i);
if(elem !=null){
if(elem.value== ""){ // ||
//(document.form.website.value.indexOf("http://") == -1) ||
//(document.form.website.value.indexOf(".") == -1)) {
bres = false; missinginfo += "\n " + (document.getElementById('f'+i).name);
} //end if
} //end if
} //end for
if(!bres){alert (missinginfo );}
// end of validation here, print if checkbox checked
if(bres && document.getElementById('cprint').checked==true){window.print();}
document.getElementById('doc').value = "";
return bres;
} //end function
Any suggestions on how to remedy, or am I doing something completely wrong?
Use onsubmit instead of onclick:
<INPUT class="checkboxes" id="Place order"
onsubmit="return checkfields();"
type="submit" value="SUBMIT" name="Place order">

Javascript Validating in a loop

I have two radio buttons on the top (YES/NO) If yes the javascript function showhideform shows another text box(certificate). This form is in a loop as you see with all my outputs.If yes is chosen and loop is 1 everything works fine onsubmit. If Yes and I submit when loop is 2 it only validates certificate textbox 2 and forgets about certificate textbox 1. I need it to validate both if yes is chosen twice.
Radio Buttons:
<input
type="radio"
value="No"
name="abc_<cfoutput>#BAdd#</cfoutput>"
id="noabc_<cfoutput>#BAdd#</cfoutput>"
onchange="showhideForm_<cfoutput>#BAdd#</cfoutput>(this.value);"/>
<label for="noabc_<cfoutput>#BAdd#</cfoutput>">No</label>
<input
type="radio"
value="Yes"
name="abc_<cfoutput>#BAdd#</cfoutput>"
id="abc_<cfoutput>#BAdd#</cfoutput>"
required="yes"
onchange="showhideForm_<cfoutput>#BAdd#</cfoutput>(this.value);"/>
<label for="abc_<cfoutput>#BAdd#</cfoutput>">Yes</label>
Show / Hide Radio Buttons:
function showhideForm_<cfoutput>#BAdd#</cfoutput>(abc_<cfoutput>#BAdd#</cfoutput>) {
if (abc_<cfoutput>#BAdd#</cfoutput> == "Yes") {
document.getElementById("div1_<cfoutput>#BAdd#</cfoutput>").style.display = 'block';
document.getElementById("div2_<cfoutput>#BAdd#</cfoutput>").style.display = 'none';
}
else if (abc_<cfoutput>#BAdd#</cfoutput> == "No") {
document.getElementById("div2_<cfoutput>#BAdd#</cfoutput>").style.display = 'block';
document.getElementById("div1_<cfoutput>#BAdd#</cfoutput>").style.display = 'none';
}
}
Validating through loop:
function doSubmit(n) {
var QnoText = ['abc_<cfoutput>#BAdd#</cfoutput>']; // add IDs here for questions with optional text input
var ids = '';
flag = true;
for (i=0; i<QnoText.length; i++) {
CkStatus = document.getElementById(QnoText[i]).checked;
ids = QnoText[i]+'Certificate_<cfoutput>#BAdd#</cfoutput>' + n;
if (CkStatus && document.getElementById(ids).value == '') {
alert('Please enter certificate number ' + n + '.');
document.getElementById(ids).focus();
flag = false;
}
}
return flag;
}
Certificate textbox:
<input
type="text"
name="abc_<cfoutput>#BAdd#</cfoutput>Certificate_<cfoutput>#BAdd#</cfoutput>"
validateat="onSubmit"
validate="maxlength"
id="abc_<cfoutput>#BAdd#</cfoutput>Certificate_<cfoutput>#BAdd#</cfoutput>"
size="54"
maxlength="120"
value="">
submit button:
//return doSubmit(1);
It looks like the n is just a numbering/index to the id of the input textbox it is validating.
Looking at your code, CKStatus seems to me is a checkbox. If it is checked, it will validate the certificate input text box according to the parameter n.
After days of working on it I have finally figured it out!! I just wanted to say thanks to everyone that has helped and this is the code for anyone who was interested!
<script type="text/javascript">
function doSubmit() {
var count =<cfoutput>#BAdd#</cfoutput>;
flag = true;
for (i=1; i<=count; i++){
var ids = 'abc_'+i +'Certificate_'+i;
var Radio = 'abc_'+i
CkStatus = document.getElementById(Radio).checked;
if (CkStatus && document.getElementById(ids).value == '') {
alert('Please enter certificate number ' +i);
document.getElementById(ids).focus();
flag = false;
}
}
return flag;
}
</script>

Form using javascript make field required?

I have a form that uses a javascript file items.js to add new items. So each time form.php is used and the 'add items' buttons is clicked then the new row of fields show to add details.
So for example some of the code is the following to add field item name.
newCell = newRow.insertCell(3);
newCell.innerHTML = '<input class="item_text_area item_name" type="text" name="0_item_' + new_item + '" id="0_item_' + new_items + '" size="20" maxlength="250" />';
How can I edit this .js file to make the Item name field required?
Any help would be appreciated.
Per Jeevan: As you cannot be sure how many items the user submits, I would choose for an approach where all new items have unique class, say dynamicAddedItems.
As Jeevan already said, you can add the following to the form tag to prevent it from submitting if it returns false.
<form onsubmit="return validate();"></form>
With javascript:
function validate(){
var elems = document.getElementsByClassName( 'dynamicAddedItems' );
var allgood = true;
//Loop through all elements with this class
for( var i = 0; i < elems.length; i++ ) {
if( !elems[i].value || !elems[i].value.length ) {
elems[i].className += " error";
allgood = false;
} else {
elems[i].className = "item_text_area item_name dynamicAddedItems";
}
}
//If any element did not meet the requirements, prevent it from being submitted and display an alert
if( !allgood ) {
alert( "Please fill in all the required fields." );
return false;
}
//Otherwise submit the form
return true;
}
This script will add the error class if a field is empty and prevent the form from being submitted. It's up to you how you want to display a field with such a class.
You can use jquery for this. Add a class, in this case 'requiredAttr' to the required fields and then validate on form submit.
<form onsubmit="return validate();">
First Name*: <input class="requiredAttr" type="text" /><br/>
Last Name: <input type="text" /><br/>
<input type="submit" />
</form>
function validate(){
$(".requiredAttr").each(function(){
if($(this).val().length < 1){
alert("please fill in all the required fields.");
$(this).focus();
return false;
}
else{
return true;
}
});
return false;
}
Here is a working fiddle. It also brings the focus on the first un-filled field after the validation alert:
http://jsfiddle.net/YG6mk/2/

validation of input text field in html using javascript

<script type='text/javascript'>
function required()
{
var empt = document.forms["form1"]["Name"].value;
if (empt == "")
{
alert("Please input a Value");
return false;
}
}
</script>
<form name="form1" method="" action="">
<input type="text" name="name" value="Name"/><br />
<input type="text" name="address line1" value="Address Line 1"/><br />
I have more than one input text field, each having their default value. Before I submit the form I have to verify whether all fields are filled. So far i got the javascript to check for null since different text boxes have different default value. How can I write a javascript to verify that user has entered data? I mean, the script must identify that input data is other than default and null.
If you are not using jQuery then I would simply write a validation method that you can be fired when the form is submitted. The method can validate the text fields to make sure that they are not empty or the default value. The method will return a bool value and if it is false you can fire off your alert and assign classes to highlight the fields that did not pass validation.
HTML:
<form name="form1" method="" action="" onsubmit="return validateForm(this)">
<input type="text" name="name" value="Name"/><br />
<input type="text" name="addressLine01" value="Address Line 1"/><br />
<input type="submit"/>
</form>
JavaScript:
function validateForm(form) {
var nameField = form.name;
var addressLine01 = form.addressLine01;
if (isNotEmpty(nameField)) {
if(isNotEmpty(addressLine01)) {
return true;
{
{
return false;
}
function isNotEmpty(field) {
var fieldData = field.value;
if (fieldData.length == 0 || fieldData == "" || fieldData == fieldData) {
field.className = "FieldError"; //Classs to highlight error
alert("Please correct the errors in order to continue.");
return false;
} else {
field.className = "FieldOk"; //Resets field back to default
return true; //Submits form
}
}
The validateForm method assigns the elements you want to validate and then in this case calls the isNotEmpty method to validate if the field is empty or has not been changed from the default value. it continuously calls the inNotEmpty method until it returns a value of true or if the conditional fails for that field it will return false.
Give this a shot and let me know if it helps or if you have any questions. of course you can write additional custom methods to validate numbers only, email address, valid URL, etc.
If you use jQuery at all I would look into trying out the jQuery Validation plug-in. I have been using it for my last few projects and it is pretty nice. Check it out if you get a chance. http://docs.jquery.com/Plugins/Validation
<form name="myForm" id="myForm" method="post" onsubmit="return validateForm();">
First Name: <input type="text" id="name" /> <br />
<span id="nameErrMsg" class="error"></span> <br />
<!-- ... all your other stuff ... -->
</form>
<p>
1.word should be atleast 5 letter<br>
2.No space should be encountered<br>
3.No numbers and special characters allowed<br>
4.letters can be repeated upto 3(eg: aa is allowed aaa is not allowed)
</p>
<button id="validateTestButton" value="Validate now" onclick="validateForm();">Validate now</button>
validateForm = function () {
return checkName();
}
function checkName() {
var x = document.myForm;
var input = x.name.value;
var errMsgHolder = document.getElementById('nameErrMsg');
if (input.length < 5) {
errMsgHolder.innerHTML =
'Please enter a name with at least 5 letters';
return false;
} else if (!(/^\S{3,}$/.test(input))) {
errMsgHolder.innerHTML =
'Name cannot contain whitespace';
return false;
}else if(!(/^[a-zA-Z]+$/.test(input)))
{
errMsgHolder.innerHTML=
'Only alphabets allowed'
}
else if(!(/^(?:(\w)(?!\1\1))+$/.test(input)))
{
errMsgHolder.innerHTML=
'per 3 alphabets allowed'
}
else {
errMsgHolder.innerHTML = '';
return undefined;
}
}
.error {
color: #E00000;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Validation</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
var tags = document.getElementsByTagName("input");
var radiotags = document.getElementsByName("gender");
var compareValidator = ['compare'];
var formtag = document.getElementsByTagName("form");
function validation(){
for(var i=0;i<tags.length;i++){
var tagid = tags[i].id;
var tagval = tags[i].value;
var tagtit = tags[i].title;
var tagclass = tags[i].className;
//Validation for Textbox Start
if(tags[i].type == "text"){
if(tagval == "" || tagval == null){
var lbl = $(tags[i]).prev().text();
lbl = lbl.replace(/ : /g,'')
//alert("Please Enter "+lbl);
$(".span"+tagid).remove();
$("#"+tagid).after("<span style='color:red;' class='span"+tagid+"'>Please Enter "+lbl+"</span>");
$("#"+tagid).focus();
//return false;
}
else if(tagval != "" || tagval != null){
$(".span"+tagid).remove();
}
//Validation for compare text in two text boxes Start
//put two tags with same class name and put class name in compareValidator.
for(var j=0;j<compareValidator.length;j++){
if((tagval != "") && (tagclass.indexOf(compareValidator[j]) != -1)){
if(($('.'+compareValidator[j]).first().val()) != ($('.'+compareValidator[j]).last().val())){
$("."+compareValidator[j]+":last").after("<span style='color:red;' class='span"+tagid+"'>Invalid Text</span>");
$("span").prev("span").remove();
$("."+compareValidator[j]+":last").focus();
//return false;
}
}
}
//Validation for compare text in two text boxes End
//Validation for Email Start
if((tagval != "") && (tagclass.indexOf('email') != -1)){
//enter class = email where you want to use email validator
var reg = /^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/
if (reg.test(tagval)){
$(".span"+tagid).remove();
return true;
}
else{
$(".span"+tagid).remove();
$("#"+tagid).after("<span style='color:red;' class='span"+tagid+"'>Email is Invalid</span>");
$("#"+tagid).focus();
return false;
}
}
//Validation for Email End
}
//Validation for Textbox End
//Validation for Radio Start
else if(tags[i].type == "radio"){
//enter class = gender where you want to use gender validator
if((radiotags[0].checked == false) && (radiotags[1].checked == false)){
$(".span"+tagid).remove();
//$("#"+tagid").after("<span style='color:red;' class='span"+tagid+"'>Please Select Your Gender </span>");
$(".gender:last").next().after("<span style='color:red;' class='span"+tagid+"'> Please Select Your Gender</span>");
$("#"+tagid).focus();
i += 1;
}
else{
$(".span"+tagid).remove();
}
}
//Validation for Radio End
else{
}
}
//return false;
}
function Validate(){
if(!validation()){
return false;
}
return true;
}
function onloadevents(){
tags[tags.length -1].onclick = function(){
//return Validate();
}
for(var j=0;j<formtag.length;j++){
formtag[j].onsubmit = function(){
return Validate();
}
}
for(var i=0;i<tags.length;i++){
var tagid = tags[i].id;
var tagval = tags[i].value;
var tagtit = tags[i].title;
var tagclass = tags[i].className;
if((tags[i].type == "text") && (tagclass.indexOf('numeric') != -1)){
//enter class = numeric where you want to use numeric validator
document.getElementById(tagid).onkeypress = function(){
numeric(event);
}
}
}
}
function numeric(event){
var KeyBoardCode = (event.which) ? event.which : event.keyCode;
if (KeyBoardCode > 31 && (KeyBoardCode < 48 || KeyBoardCode > 57)){
event.preventDefault();
$(".spannum").remove();
//$(".numeric").after("<span class='spannum'>Numeric Keys Please</span>");
//$(".numeric").focus();
return false;
}
$(".spannum").remove();
return true;
}
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", onloadevents, false);
}
//window.onload = onloadevents;
</script>
</head>
<body>
<form method="post">
<label for="fname">Test 1 : </label><input type="text" title="Test 1" id="fname" class="form1"><br>
<label for="fname1">Test 2 : </label><input type="text" title="Test 2" id="fname1" class="form1 compare"><br>
<label for="fname2">Test 3 : </label><input type="text" title="Test 3" id="fname2" class="form1 compare"><br>
<label for="gender">Gender : </label>
<input type="radio" title="Male" id="fname3" class="gender" name="gender" value="Male"><label for="gender">Male</label>
<input type="radio" title="Female" id="fname4" class="gender" name="gender" value="Female"><label for="gender">Female</label><br>
<label for="fname5">Mobile : </label><input type="text" title="Mobile" id="fname5" class="numeric"><br>
<label for="fname6">Email : </label><input type="text" title="Email" id="fname6" class="email"><br>
<input type="submit" id="sub" value="Submit">
</form>
</body>
</html>
function hasValue( val ) { // Return true if text input is valid/ not-empty
return val.replace(/\s+/, '').length; // boolean
}
For multiple elements you can pass inside your input elements loop their value into that function argument.
If a user inserted one or more spaces, thanks to the regex s+ the function will return false.
<pre><form name="myform" action="saveNew" method="post" enctype="multipart/form-data">
<input type="text" id="name" name="name" />
<input type="submit"/>
</form></pre>
<script language="JavaScript" type="text/javascript">
var frmvalidator = new Validator("myform");
frmvalidator.EnableFocusOnError(false);
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name","req","Plese Enter Name");
</script>
before using above code you have to add the gen_validatorv31.js js file
For flexibility and other places you might want to validated. You can use the following function.
`function validateOnlyTextField(element) {
var str = element.value;
if(!(/^[a-zA-Z, ]+$/.test(str))){
// console.log('String contain number characters');
str = str.substr(0, str.length -1);
element.value = str;
}
}`
Then on your html section use the following event.
<input type="text" id="names" onkeyup="validateOnlyTextField(this)" />
You can always reuse the function.

Categories

Resources