js function not working in aspx (form validation) - javascript

i'm trying to write a form in aspx page includes veification in the submit button.Even if i run debugger clicking the submit doesn't perfom the Js code (or maybe there is a problem in syntax that i dont' know what is it). Can anyone help me find the mistake (either synax of script or something in the html)? thanks alot:)
the code of default.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>טופס הרשמה</title>
<link rel="Stylesheet" type="text/javascript" href="style.css" />
<script>
var FinalMsg = "";
function VerifyForm() {
VerUser();
VerPasses();
VerGen();
alert(FinalMsg);
}
function VerUser(){
var vus = document.getElementById("username").value;
if(vus.length=0)
{
FinalMsg+="type username";
}
}
function VerPasses(){
var vpasfir = document.getElementById("pass1").value;
var vpassec = document.getElementById("pass2").value;
if(vpasfir.length=0)
{
FinalMsg+="type password";
}
if(vpassec.length=0)
{
FinalMsg+="type the secondary pass";
}
if (vpasfir.value != vpassec.value)
{
FinalMsg+="passs aren't match";
}
}
function VerGen() {
var vgen1 = document.getElementById("male").value;
var vgen2 = document.getElementById("female").value;
var vgen3 = document.getElementById("other").value;
if ((vgen1.checked==false)&&(vgen2.checked==false)&&(vgen3.checked==false&&)){
FinalMsg += "haven;t chosen gender";
}
}
</script>
</head>
<body dir="rtl">
<center> <img src="Title.gif" width="500px"/></center>
<form id="FormAboutYou" runat="server" method="post" onsubmit="validateForm()">
<table border="0">
<tr>
<td class="field">שם משתמש</td>
<td><input type="text" name="username" id="username"/></td>
</tr>
<tr>
<td class="field">סיסמה</td>
<td><input type="password" name="pass1" id="pass1"/></td>
</tr>
<tr>
<td class="field">סיסמה בשנית</td>
<td><input type="password" name="pass2" id="pass2"/></td>
</tr>
<tr>
<td class="field">כתובת דוא"ל</td>
<td><input type="email" name="email" id="email"/></td>
</tr>
<tr>
<td class="field">מזונות מועדפים</td>
<td Class="ChooseFrom">
<input type="checkbox" name="food" value="Choclate" id="choc" /> שוקולד <br />
<input type="checkbox" name="food" value="Fries" id="fries"/> צ'יפס <br />
<input type="checkbox" name="food" value="Tomatoes and other vegetables" id="veg"/> ירקות ופירות <br />
<input type="checkbox" name="food" value="Pasta" id="pasta"/> פסטה <br />
<input type="checkbox" name="food" value="Cheese" id="che"/>גבינה <br />
</td>
</tr>
<tr>
<td class="field">מגדר</td>
<td class="ChooseFrom">
<input type="radio" name="gender" value="Male" id="male"/> זכר <br />
<input type="radio" name="gender" value="Female" id="femle"/> נקבה <br />
<input type="radio" name="gender" value="Unde" id="other"/> עדיין לא החלטתי/יש לי בעיה עם שדות בינארים <br />
</td>
</tr>
<tr>
<td class="field">living in</td>
<td>
<select>
<option value="TelAviv" id="ny">new york</option>
<option value="PetaTikwa" id="rome">rome</option>
<option value="QiryatOno" id="Paris">Paris</option>
<option value="RamgatGan" id="lv">Las Vegas</option>
<option value="Haifa" id="ln">London</option>
<option value="Qraiot" id="bt">Bairut</option>
<option value="Bash" id="bej">Beijing</option>
<option value="Eilat" id="tk">Tokyo</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="submit" name="submit" value="הזן נתוניך על פני המים" onsubmit="VerifyForm();"/>
</td>
</tr>
</table>
</form>
<hr />
<br /><br /><br /><br />
<br /><br /><br /><br />
</body>
</html>
thanks again :)

An idea could be to take onsubmit() out of the form tag.
then for your button change the onSubmit to onclick='return verifyForm();
In your verifyForm() method you need to return either true or false; if false, the form won't submit.
So, something like this at the end of your verifyForm()
if (FinalMsg == ""){
return true;
}else{
return false;
}

Related

submit input text into table as <td>

Ive been looking online for super long and I haven't been able to find an answer to something that seems super common.
Basically what I want to do is submit input text and maybe also if a radio button or something like that is checked to popup as text in a table as here are some photos of the inputs and the table.
I want to be able to press the "+" or "add" button and have all the text from the inputs added into the table and if the radio is checked (checked= true(something like that)) for it all to show up in the table when I press the add button.
Here is my HTML for the example photo:
<div class="bg">
<button id="droplist-btn" class="droplist-btn">Add By Droplist</button>
<form>
<input type="text" id="item-code-input" class="item-code-input" placeholder=""></input>
<button type="submit" id="add-item" class="add-item">+</button>
<input type="text" id="color-input" placeholder="color"></input>
<select type="text" id="sizes-item-code" class="sizes-item-code">
<option value="Small">Small</option>
<option value="Medium">Medium</option>
<option value="Large">Large</option>
<option value="XLarge">XLarge</option>
<option value="One Size">One Size</option>
</select>
</label>
<label class="switch">
<input type="checkbox">
<span class="slider"></span>
</label>
<label for="switch">Any Color</label>
</form>
<table id="items-table">
<!--<caption>Task</caption>-->
<tr>
<th>Item</th>
<th>Size</th>
<th>Options</th>
</tr>
<tr>
</tr>
</table>
<label id="item-code-label">Item Code</label>
<!-- idk what happened here -->
<label class="radio">.
<input type="radio" checked="checked" name="radio">
<span class="check-item"></span>
</label>
<label id="keyword-label">Keyword</label>
<label class="radio">.
<input type="radio" name="radio">
<span class="check-keyword"></span>
</label>
</div>
<script src="jquery.js"></script>
<script src="items.js"></script>
</body>
</html>
I have tried to add both of the answers below to my other script and none of them are working here is the html for my differnt table:
<table id="proxy-list">
<tr>
<!--<th>Name</th> -->
<th colspan="3">Proxies</th>
</tr>
<tr>
<td>Proxy1:</td>
<td>174.32.116.214:87</td>
<td>
<button class="remove-btn"><div class="thex">x</div></button>
</td>
</tr>
</table>
<input type="text" id="proxy-add-name" placeholder="Name"></input>
<input type="text" id="proxy-add-proxy" placeholder="Proxy"></input>
<button id="proxy-add" onclick="addProxy()">Add</button>
Any help is appreciated thank you.
(I Know my html code is very messy im very knew to html and am still learning)
(jQuery is preferred but as I said anything helps)
Just update the start of addRow
function addRow() {
var item_text = 1; // $('#item-code-input').val() ???
var size_text = 2;
var options_text = 3;
$('#main-table').append('<tr>'
+'<td>'+item_text+'</td>'
+'<td>'+size_text+'</td>'
+'<td>'+options_text+'</td>'
+'</tr>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="main-table">
<tr>
<th>Item</th><th>Size</th><th>Options</th>
</tr>
</table>
<button onclick="addRow()">Add Row</button>
This is using your code - BTW I added id="switch" for the checkbox input (to link to for="switch") For options it only takes into account "Any Colour" though. The "+" button makes it add rows. I used "return false" to stop the form from submitting when the + button is clicked.
function addRow() {
var item_text = $('#item-code-input').val();
var size_text = $('#sizes-item-code').val();
var options_text = $('#switch').is(':checked') ? 'Any Color' : '';
$('#items-table').append('<tr>'
+'<td>'+item_text+'</td>'
+'<td>'+size_text+'</td>'
+'<td>'+options_text+'</td>'
+'</tr>');
}
$(function(){
$('#add-item').click(function(){
addRow();
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="bg">
<button id="droplist-btn" class="droplist-btn">Add By Droplist</button>
<form>
<input type="text" id="item-code-input" class="item-code-input" placeholder=""></input>
<button type="submit" id="add-item" class="add-item">+</button>
<input type="text" id="color-input" placeholder="color"></input>
<select type="text" id="sizes-item-code" class="sizes-item-code">
<option value="Small">Small</option>
<option value="Medium">Medium</option>
<option value="Large">Large</option>
<option value="XLarge">XLarge</option>
<option value="One Size">One Size</option>
</select>
</label>
<label class="switch">
<input type="checkbox" id="switch">
<span class="slider"></span>
</label>
<label for="switch">Any Color</label>
</form>
<table id="items-table">
<!--<caption>Task</caption>-->
<tr>
<th>Item</th>
<th>Size</th>
<th>Options</th>
</tr>
<tr>
</tr>
</table>
<label id="item-code-label">Item Code</label>
<!-- idk what happened here -->
<label class="radio">.
<input type="radio" checked="checked" name="radio">
<span class="check-item"></span>
</label>
<label id="keyword-label">Keyword</label>
<label class="radio">.
<input type="radio" name="radio">
<span class="check-keyword"></span>
</label>
</div>
<script src="jquery.js"></script>
<script src="items.js"></script>
</body>
</html>
Try this out. Not efficient but it covers what you want to do
function add() {
let table = document.getElementById("theTable")
let fd = new FormData(myForm)
let output = ""
for(let data of fd.entries()) {
output += "<td>"+data[1]+"</td>"
}
output = "<tr>"+output+"</tr>"
table.innerHTML += output
}
<form id=myForm>
<input name="name" value="John" />
<input name="age" value="32" />
<input name="lang" value="en" />
<input type=button onclick="add()" value="+"/>
</form>
<table width="100%" border=1 id="theTable">
</table>

Writing and Retrieving Cookies in JS

Alright so I have this assignment for my class and I'm not entirely sure what I'm doing wrong. I need to insert an initPage() function to the sbutton that calls saveMailingInfo() and it has to run when the page loads. I also need to write a saveMailingInfo() function that creates an 3 year expiration date and loops through each element of the mailing form. I was certain I did it right but I don't get the alert when I test it. Any ideas?
/* this function attachs the event handler under both event models */
function addEvent(object, evName, fnName, cap) {
if (object.attachEvent)
object.attachEvent("on" + evName, fnName);
else if (object.addEventListener)
object.addEventListener(evName, fnName, cap);
}
function writeCookie(cName, cValue, expDate, cPath, cDomain, cSecure) {
if (cName && cValue != "") {
var cString = cName + "=" + escape(cValue);
if (expDate)
cString += ";expires=" + expDate.toGMTString();
if (cPath) cString += ";path=" + cPath;
if (cDomain) cString += ";domain=" + cDomain;
if (cSecure) cString += ";secure";
document.cookie = cString;
}
function saveMailingInfo() {
var expire = new Date();
expire.setFullYear(expire.getFullYear() + 3);
var allFields = document.mailingForm.elements;
for (var i = 0; i < allFields.length; i++) {
if (allFields[i].type == "text") {
writeCookie(allFields[i].id, allFields[i].value, expire);
}
if (allFields[i].nodename == "SELECT") {
writeCookie(allFields[i].id, allFields[i].selectedIndex, expire);
}
if (allFields[i].type == "radio") || allFields[i].type == "checkbox") {
writeCookie(allFields[i].id, allFields[i].checked, expire);
}
}
}
alert("Cookie has been written!");
}
addEvent(window, "load", initpage, false);
function initPage(){
document.getElementById("sbutton").onclick = saveMailingInfo;
console.log(document.cookie);
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<!-- DW6 -->
<head>
<!--
-->
<title>Cakes by Emily</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="main.css" type="text/css" />
<script type="text/javascript" src="cakeForm.js"></script>
</head>
<body >
<div class="head" id="header">
<p><img src="cake.jpg" alt="cake picture" /><img src="logo.gif" alt="Cakes by Emily" width="400" height="125" /></p>
<div class="links" id="navigation">
Home
Cakes
Pastries
Pies
Mailing List
</div>
</div>
<div class="mainContent">
<p>Enter your info to be added to our email list with reminders about getting that birthday
cake you want! Remember at Cakes by Emily, we aim to make every birthday the best!</p>
<form name="mailingForm" >
<table>
<tr>
<td>
First:
</td>
<td> <input type="text" name="firstName" id="firstName"><BR>
</td>
</tr>
<tr>
<td>
Last:
</td>
<td><input type="text" name="lastName" id="lastName" ><BR>
</td>
</tr>
<tr>
<td>
E-Mail:
</td>
<td><input type="text" name="email" id="email" ><BR>
</td>
</tr>
<tr>
<td>
Birthday (mm/dd/yyyy):
</td>
<td><input type="text" name="birthday" id="birthday" ><BR>
</td>
</tr>
<tr>
<td>
Favorite Cake:
</td>
<td>
<select id="favoriteCake">
<option value="ButterCream">Butter Cream</option>
<option value="Chocolate">Chocolate</option>
<option value="Vanilla">Vanilla</option>
<option value="RedVelvet">Red Velvet</option>
</select><BR>
</td>
</tr>
<tr>
<td>
Frequency of Emails:
</td>
<td><input type="radio" name="frequency" id="frequency1" >Email me monthly<BR>
<input type="radio" name="frequency" id="frequency2" >Email me quarterly<BR>
<input type="radio" name="frequency" id="frequency3" >Email me near my birthday<BR>
</td>
</tr>
</table>
<input type="submit" id="sbutton" name="sbutton" value="Join our mailing List" />
<input type="reset" value="Reset the form" />
</form>
</div>
<div class="footer">
</div>
</body>
</html>

jquery star plugin not working after ajax call

I have one JSP in that JSP i have a for loop. inside the for loop i am printing stars with rating in different cells of table. After making the ajax call, stars are not coming. Just the radio buttons are coming I am using this plugin http://www.fyneworks.com/jquery/star-rating/. Here is my step by step code. I have removed some part to make it simple.
First JSP code :
<div class="book-right" id="ajaxTest">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.rating.js"></script>
<script type="text/javascript" src="js/jquery-latest.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.min.js"></script>
<--table + some intermediate loop code --->
<c:forEach var="leg" items="${option.legs}" varStatus="loopCounter3">
<div>
<input type="radio" name="rating-${loopCounter2.index}" value="1" class="rating-star" />
<input type="radio" name="rating-${loopCounter2.index}" value="2" class="rating-star" />
<input type="radio" name="rating-${loopCounter2.index}" value="3" class="rating-star" />
<input type="radio" name="rating-${loopCounter2.index}" value="4" class="rating-star" />
<input type="radio" name="rating-${loopCounter2.index}" value="5" class="rating-star" />
</div>
<input type="hidden" id="avgRating" name="avgRating" value="${leg.courierProduct.rating}"></input>
<script>
var avgRating = $('#avgRating').val();
$('.rating-star').rating('select', avgRating);
</script>
</c:forEach>
Here is my ajax call :
function loadXMLDoc()
{
var xmlhttp;
var filtervalue=document.getElementById('filter1').value;
var url="FilterRender?filtervalue="+filtervalue;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("ajaxTest").innerHTML=xmlhttp.responseText;
var preference = document.getElementById("pref_id").value;
if(preference== '1')
{
$("#myTable").tablesorter({
sortList : [[2,0]],
headers: {
0: {
sorter: false
},
4: {
sorter: false
} } });
}
else if(preference== '2')
{
$("#myTable").tablesorter({
sortList : [[1,0]],
headers: {
0: {
sorter: false
},
4: {
sorter: false
} } });
}
else
{
$("#myTable").tablesorter({
headers: {
//make the first column un-sortable
0: {
sorter: false
},
//make the fourth column un-sortable
4: {
sorter: false
} } });
}
var avgRating = $('#avgRating').val();
alert('called');
$('.rating-star').rating().rating('select', avgRating );
$('.rating-star').rating('readOnly',true);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
After the Ajax call i am loading this div:
<div class="book-right" id="ajax">
<script type="text/javascript" src="js/jquery-1.11.2.js"></script>
<script type="text/javascript" src = "js/jquery.rating.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.min.js"></script>
<c:choose>
<c:when test="${fn:length(routes) == 1 and fn:length(routes[0].options) == 0}">
<div style="padding:216px;width:800px !important">
<span style="font-size: 20px; font-weight: bolder;margin: 90px;">Sorry! Currently we have no service found for this route.</span>
</div>
</c:when>
<c:otherwise>
<table id="myTable" class="tablesorter" width="769" border="0" cellspacing="0" cellpadding="0" class="sortable">
<thead>
<tr>
<th width="24%" height="67" align="center" bgcolor="#f7f6f6">
<span class="ser service"> Service Provider</span>
</th>
<th width="21%" height="67" align="center" bgcolor="#f7f6f6">
<span class = "ser icon1 icon2" >Delivery Time
</span>
</th>
<th width="16%" height="67" align="center" bgcolor="#f7f6f6">
<span class = "ser icon1 icon3">Cost
</span>
</th>
<th width="15%" height="67" bgcolor="#f7f6f6" align="center">
<span class="ser">Ratings </span>
</th>
<th width="17%" height="67" align="center" bgcolor="#f7f6f6">
</th>
</tr>
</thead>
<tbody>
<c:set var="filtervalue" scope="session" value="${param.filtervalue}"/>
<c:forEach var="route" items="${routes}" varStatus="loopCounter">
<c:forEach var="option" items="${route.options}"
varStatus="loopCounter2">
<tr>
<c:if test="${option.duration<=filtervalue}">
<td><div>
<c:forEach var="leg" items="${option.legs}"
varStatus="loopCounter3">
<span class="item"> <img
src="img/vendor_logos/<c:out value="${leg.courierProduct.logoName}" />"></span>
</c:forEach>
</div></td>
<td><span><c:out value="${option.duration}" /> days</span></td>
<td><span class="cost" style="font-size: 23px;"><img
src="img/rs.png">
<c:out value="${option.totalCost}" />/-</span></td>
<td>
<c:forEach var="leg" items="${option.legs}" varStatus="loopCounter3">
<div>
<input type="radio" name="rating-${loopCounter2.index}" value="1" class="rating-star"/>
<input type="radio" name="rating-${loopCounter2.index}" value="2" class="rating-star"/>
<input type="radio" name="rating-${loopCounter2.index}" value="3" class="rating-star"/>
<input type="radio" name="rating-${loopCounter2.index}" value="4" class="rating-star"/>
<input type="radio" name="rating-${loopCounter2.index}" value="5" class="rating-star"/>
</div>
<input type= "hidden" id="avgRating" name="avgRating" value= "${leg.courierProduct.rating}"></input>
<script>
var avgRating = $('#avgRating').val();
alert('called');
$('.rating-star').rating().rating('select', avgRating );
$('.rating-star').rating('readOnly',true)
</script>
</c:forEach>
</td>
<td>
<div id="${loopCounter2}" class="details" >
<span class="det">Details
<span class="fulv">
<div class="col">
<p>Cost - Rs-<c:out value="${option.cost}" /></p>
<p>Service Tax - Rs - <c:out value="${option.serviceTax}"/></p>
<p>Total - Rs - <c:out value="${option.totalCost}"/></p>
</div><!--ocl-->
</span><!--fulv-->
</span>
<span class="book">Book Now</span>
</div>
<!--details-->
</td>
</c:if>
</tr>
</c:forEach>
<!-- <br> -->
</c:forEach>
</tbody>
</table>
</c:otherwise>
</c:choose>
</div>
I have given the full second JSP code (loaded by AJAX) for reference. I am a beginner.Any help will be greatly appreciated. Please ask if any more code needs to be shown

how to check the default value of a radiobutton tag and display its related contents?

below is the code to check a default value for the radiobutton tag by giving checked="checked", but i am not able to display the related form by default, it can be displayed only when i click on it, how to display anyone of these forms by default ?
HTML:
<form>
<label><input value="1" type="radio" name="formselector" checked="checked" onclick="displayForm(this)">Old Definitions</label>
<label><input value="2" type="radio" name="formselector" onclick="displayForm(this)">New Definition</label>
</form>
<panel method="post" style="visibility:hidden" id="form1" name="form1">
<table style="width:100%;">
<tr>
<th ><span class="dropt">ID Reserve Tracks</th>
<td>
<input id="idtracks" autocomplete="off" name="idtracks" type="text" maxlength="50" >
</td>
</tr>
</table>
</panel>
<panel style="visibility:hidden" id="form2">
<table style="width:100%;">
<th ><span class="dropt">MD Reserve Tracks</th>
<td>
<input id="mdtracks" autocomplete="off" name="mdtracks" type="text" maxlength="50" >
</td>
</table>
</panel>
JavaScript:
function displayForm(c){
if(c.value == "1"){
document.getElementById("form1").style.visibility='visible';
document.getElementById("form2").style.visibility='collapse';
}
else if(c.value =="2"){
document.getElementById("form1").style.visibility='collapse';
document.getElementById("form2").style.visibility='visible';
}
else{
}
}
jsfiddle: http://jsfiddle.net/uLkHk/
Your Html is not well formed, you should improve that.
To make it work as you want, just do not set the option checked in HTML. Then select it in JavaScript, calling the Click method.
See this, I modified a little your HTML, and it works.
<html>
<body>
<form>
<label>
<input value="1" type="radio" id="radioOld" name="formselector" onclick="displayForm(this)" />Old
Definitions</label>
<label>
<input value="2" type="radio" id="radioNew" name="formselector" onclick="displayForm(this)" />New
Definition</label>
</form>
<form method="post" style="visibility: hidden" id="form1" name="form1">
<table style="width: 100%;">
<tr>
<td>
<span class="dropt">ID Reserve Tracks</span>
</td>
<td>
<input id="idtracks" autocomplete="off" name="idtracks" type="text" maxlength="50" />
</td>
</tr>
</table>
</form>
<form style="visibility: hidden" id="form2">
<table style="width: 100%;">
<tr>
<td>
<span class="dropt">MD Reserve Tracks</span>
</td>
<td>
<input id="mdtracks" autocomplete="off" name="mdtracks" type="text" maxlength="50" />
</td>
</tr>
</table>
</form>
<script>
function displayForm(c) {
if (c.value == "1") {
document.getElementById("form1").style.visibility = 'visible';
document.getElementById("form2").style.visibility = 'collapse';
}
else if (c.value == "2") {
document.getElementById("form1").style.visibility = 'collapse';
document.getElementById("form2").style.visibility = 'visible';
}
else {
}
}
</script>
<script>
document.getElementById('radioOld').click();
//document.getElementById('radioOld').checked = true;
//var theDefaultOption = document.getElementById('formselector');
//displayForm(theDefaultOption);
</script>
</body>
</html>
Or you can simply set the default panel's visibility to visible in the HTML as Barmar said.

Conditional Validation using JQuery Validation Plugin

I have a simple html form that I've added validation to using the JQuery Validation plugin. I have it working for single fields that require a value. I now need to extend that so that if a user answers Yes to a question they must enter something in the Details field, otherwise the Details field can be left blank. I'm using radio buttons to display the Yes/No. Here's my complete html form - I'm not sure where to go from here:
<script type="text/javascript" charset="utf-8">
$.metadata.setType("attr", "validate");
$(document).ready(function() {
$("#editRecord").validate();
});
</script>
<style type="text/css">
.block { display: block; }
form.cmxform label.error { display: none; }
</style>
</head>
<body>
<div id="header">
<h1>
Questions</h1>
</div>
<div id="content">
<h1>
Questions Page 1
</h1>
</div>
<div id="content">
<h1>
</h1>
<form class="cmxform" method="post" action="editrecord.php" id="editRecord">
<input type="hidden" name="-action" value="edit">
<h1>
Questions
</h1>
<table width="46%" class="record">
<tr>
<td width="21%" valign="top" class="field_name_left"><p>Question 1</p></td>
<td width="15%" valign="top" class="field_data">
<label for="Yes">
<input type="radio" name="Question1" value="Yes" validate = "required:true" /> Yes
</label>
<label for="No">
<input type="radio" name="Question1" value="No" /> No
</label>
<label for="Question1" class="error">You must answer this question to proceed</label>
</td>
<td width="64%" valign="top" class="field_data"><strong>Details:</strong>
<textarea id = "Details1" class="where" name="Details1" cols="25" rows="2"></textarea></td>
</tr>
<tr>
<td valign="top" class="field_name_left">Question 2</td>
<td valign="top" class="field_data">
<label for="Yes">
<input type="radio" name="Question2" value="Yes" validate = "required:true" /> Yes
</label>
<label for="No">
<input type="radio" name="Question2" value="No" /> No
</label>
<label for="Question2" class="error">You must answer this question to proceed</label>
</td>
<td valign="top" class="field_data"><strong>Details:</strong>
<textarea id = "Details2" class="where" name="Details2" cols="25" rows="2"></textarea> </td>
</tr>
<tr class="submit_btn">
<td colspan="3">
<input type="submit" name="-edit" value="Finish">
<input type="reset" name="reset" value="Reset"> </td>
</tr>
</table>
</form>
</div>
</body>
</html>
On your <textarea> elements, add a dependency expression for required, for example for question 1, do this:
validate="required:'input[name=Question1][value=Yes]:checked'"
This says if $('input[name=Question1][value=Yes]:checked').length > 0 then the field is required, so if Yes is checked, it's required :)
You can see a working demo here
You can do something like this:
$("#editRecord").validate({
rules: {
'Details1': {
required: function() {
return $('input[name=Question1]').val() == 'yes';
}
}
'Details2': {
required: function() {
return $('input[name=Question2]').val() == 'yes';
}
}
}
});
In response to Nick Craver's suggested response above, I found the correct syntax to be:
class="validate[required][name=Question1][value=Yes]:checked"
instead of what he posted.
Thanks for putting me on the right track, though!

Categories