Conditional Validation using JQuery Validation Plugin - javascript

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!

Related

Difficulties with obtaining values from form

Junior Dev here. I'm trying to implement the following code in order to get all the info typed in the form and to receive an alert message ("everything is ok").
I know there is Jquery valid() function, but I have struggle with implementing it as well.So if it's possible when the textbox doesn't meet the requirements to post the error message(email needs "#", website needs "www.", name 6 letters, password="****".
Can anyone explain me with simple code how can I achieve this ?
<form id=registration_form action="" method="post">
<table>
<tr>
<td>Chose Username: </td>
<td>
<input type="text" class="form_text" id="form_username">
</td>
<td>
<span class="error_form" id="username_error_message"></span>
</td>
</tr>
<tr>
<td>Password: </td>
<td>
<input type="password" class="form_text" id="form_password">
</td>
<td>
<span class="error_form" id="password_error_message"></span>
</td>
</tr>
<tr>
<td>Retype Password: </td>
<td>
<input type="password" class="form_text" id="form_retype_password">
</td>
<td>
<span class="error_form" id="retype_password_error_message"></span>
</td>
</tr>
<tr>
<td>Email: </td>
<td>
<input type="text" class="form_text" id="form_email">
</td>
<td>
<span class="error_form" id="email_error_message"></span>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" class="sbmt_btn" value="Create Account">
</td>
<td></td>
</tr>
</table>
</form>
Here is an example using the jQuery Validation Plugin. Its as simple as calling .validate(); on your form
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation#1.17.0/dist/jquery.validate.min.js"></script>
<script type="text/javascript">
$("#commentForm").validate();
</script>
</head>
It covers email, required input validation and much more. Check out the docs here.
Also, using the submitHandler option for the plugin you can set a callback on submit if all fields are correctly validated. In the example below we use this to call alert() with the message 'Everythings Ok'.
Example
$(document).ready(function() {
$("#commentForm").validate({
//we can use the handler to check if form is correctly validated
submitHandler: function(form) {
alert('Everythings Ok');
}
});
});
input[class="error"], textarea[class="error"] {
border: 1px solid #f00 !important;
}
.error{
margin: 5px;
color: #f00 !important;
}
/* To cover your additional requirement mentioned in the comments */
body {
background: lightblue url(http://images.all-free-download.com/images/graphiclarge/winter_background_311052.jpg) no-repeat fixed center;
}
/* For your additional requirement */
form {
background-color: transparent;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation#1.17.0/dist/jquery.validate.min.js"></script>
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<legend>Please provide your name, email address (won't be published) and a comment</legend>
<p>
<label for="cname">Name (required, at least 2 characters)</label>
<input id="cname" name="name" minlength="2" type="text" required>
</p>
<p>
<label for="cemail">E-Mail (required)</label>
<input id="cemail" type="email" name="email" required>
</p>
<p>
<label for="curl">URL (optional)</label>
<input id="curl" type="url" name="url">
</p>
<p>
<label for="ccomment">Your comment (required)</label>
<textarea id="ccomment" name="comment" required></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit">
</p>
</fieldset>
</form>
Doing this with jQuery would require a lot of different validation techniques most likely including other libraries like Regex. The plugin aggregates all of them into one plugin that can be reused across multiple pages.

Ajax HTML FORM not sending input

i've got a problem I can't figure out.
I have a page (index.php) that open a form, includes another page with PHP (indexsearch.php) and close the form.
This included page is working with a script that display some datas from my website, the data are requested on the page with an AJAX function that is linked to search.php, that is working with a table and checkboxes so we can choose which data to work with.
See this schema :
Everything is working fine but the checkboxes are not send even when they are checked. I did added the name and the value in search.php
<td> <input type="checkbox" name="ajout[]" value="<?php echo $result['id']; ?>"/> </td>
I also did not opened another form.
So I guess the problem may come from the fact the AJAX datas work as an independant form that is not included in my page.
Please see the html code :
<body>
<div class="division">
<table id="text-p">
<tr>
<td>
<form action="" method="get" enctype="multipart/form-data">
<textarea id="text-p1" name="text-p1" maxlength="300" placeholder="Text1"></textarea>
</td>
<td>
<textarea id="text-p2" name="text-p2" maxlength="300" placeholder="Text2"></textarea>
</td>
</tr>
<tr>
<td>
<input type="hidden" name="MAX_FILE_SIZE" value="1000000">
Logo : <input name="logo-p1" type="file" accept="image/*">
</td>
<td>
<input type="hidden" name="MAX_FILE_SIZE" value="1000000">
Logo : <input name="logo-p2" type="file" accept="image/*">
</td>
</tr>
</table>
</div>
<div class="division">
<div width="100%" style="height: 50px;">
<input type="text" name="recherche" id="recherche" style="width: 75%; float:left; display: inline-block;" placeholder="Rechercher...">
<div style="float:right;">
<input type="radio" name="onglet" value="val1" id="act" checked="">Activité
<input type="radio" name="onglet" value="val2" id="sect">Secteur
<input type="radio" name="onglet" value="val3" id="ecr">Ecrans
</div>
</div>
<div width="100%" id="resultats">
<input id="ok" type="button" class="pageselector" name="pageselector" value="1" checked=""><table id="resultat1" width="100%" style="text-align: center;" class="resultatshow">
<tbody><tr>
<td>Cat</td>
<td>Text-1</td>
<td>Text-2</td>
<td>Sélec</td>
</tr>
<tr>
<td>Cat1</td>
<td>NULL</td>
<td>NULL</td>
<td> <input type="checkbox" name="ajout[]" value="1"> </td>
</tr>
<tr>
<td>CAT2</td>
<td>EMPTY</td>
<td>EMPTY</td>
<td> <input type="checkbox" name="ajout[]" value="2"> </td>
</tr>
</table></div>
<input type="submit" value="UPDATE">
</div>
</body>
How can I fix that ?
I am not sure but I guess it can be caused by square brackets in the name attribute of your checkboxes. If you have reason to do it, you have to work with it properly. For example, here is the HTML form field:
<input type='checkbox' name='checkbox[myOption]'>
You have to remember that POST is an array of options. So doing like above you have to access it in the right way on the server side:
$_POST['checkbox']['myOption'];
I don't know if that solves your problem but I hope it helps a little bit

How to achieve check box and text field dependency in following scenario?

I'm using PHP, Smarty, jQuery, etc. for my website. Now the scenario is in one template file there is some code containing loops, checkboxes, textfields, etc. For your reference I'm putting the necessary code snippet from smarty template as below:
{foreach from=$subject_topic_data.topics item=topic_diff_level_data}
<input type="hidden" name="subject_{$subject_topic_data.subject_id}_topics[]" value="{$topic_diff_level_data.topic_id}">
<tr>
<td valign="middle">
<p class="custom-form">
<input type="checkbox" class="custom-check" name="{$sheet_type}_topics_{$subject_topic_data.subject_id}[]" id="{$sheet_type}_{$subject_topic_data.subject_id}_{$topic_diff_level_data.topic_id}" value="{$topic_diff_level_data.topic_id}" {if in_array($topic_diff_level_data.topic_id, $practice_sheet_set_details[$subject_topic_data.subject_id].topics)}checked="checked"{/if}>
<label>{$topic_diff_level_data.topic_name}</label>
<!-- <input type="hidden" name="topic_names[{$topic_diff_level_data.topic_id}]" value="{$topic_diff_level_data.topic_name}"> -->
</p>
</td>
{foreach from=$topic_diff_level_data.difficulty_level item=diff_level key=key_diff_lvl}
<td valign="middle">
{if $site_id=='ENTPRM'}<em>Total {$diff_level.question_count}</em>{/if}
<input type="text" name="{$sheet_type}_{$subject_topic_data.subject_id}_{$topic_diff_level_data.topic_id}_{$key_diff_lvl}" id="{$sheet_type}_{$subject_topic_data.subject_id}_{$topic_diff_level_data.topic_id}_{$key_diff_lvl}" maxlength="3" class="mini" value="{$diff_level.added_no_questions}">
<input type="hidden" name="{$sheet_type}_available_questions_{$subject_topic_data.subject_id}_{$topic_diff_level_data.topic_id}_{$key_diff_lvl}" value="{$diff_level.question_count}">
</td>
{/foreach}
</tr>
{/foreach}
Now from the above code what I want to achieve is when the user checks the check box of subject the concerned topic text fields should get enabled. Initially when the page loads all the tesxtfields of all the topics should be disabled. CAn you help me in achieving this? If you want some additional information I can provide you the same. Thanks in advance.
Client Side:
{foreach from=$subject_topic_data.topics item=topic_diff_level_data}
<input type="hidden"
name="subject_{$subject_topic_data.subject_id}_topics[]"
value="{$topic_diff_level_data.topic_id}">
<tr>
<td valign="middle">
<p class="custom-form">
checkbox: give id of subject_selected
<input type="checkbox" class="custom-check"
name="{$sheet_type}_topics_{$subject_topic_data.subject_id}[]"
id="{$sheet_type}_{$subject_topic_data.subject_id}_{$topic_diff_level_data.topic_id}"
value="{$topic_diff_level_data.topic_id}"
{if in_array($topic_diff_level_data.topic_id,
$practice_sheet_set_details[$subject_topic_data.subject_id].topics)}checked="checked"{/if}>
//disabled
<label>{$topic_diff_level_data.topic_name}</label>
<!-- <input type="hidden"
name="topic_names[{$topic_diff_level_data.topic_id}]"
value="{$topic_diff_level_data.topic_name}">
-->
</p>
</td>
{foreach from=$topic_diff_level_data.difficulty_level item=diff_level key=key_diff_lvl}
<td valign="middle">
{if $site_id=='ENTPRM'}<em>Total {$diff_level.question_count}</em>{/if}
<input type="text"
name="{$sheet_type}_{$subject_topic_data.subject_id}_{$topic_diff_level_data.topic_id}_{$key_diff_lvl}"
id="{$sheet_type}_{$subject_topic_data.subject_id}_{$topic_diff_level_data.topic_id}_{$key_diff_lvl}"
maxlength="3" class="mini" value="{$diff_level.added_no_questions}">
<input type="hidden"
name="{$sheet_type}_available_questions_{$subject_topic_data.subject_id}_{$topic_diff_level_data.topic_id}_{$key_diff_lvl}"
value="{$diff_level.question_count}">
</td>
{/foreach}
</tr>
{/foreach}
Javascript:
<script type=text/javascript>
function subject_selection(/* pass the selection here */){
var check= document.getElementById('subject_selection');
if (check.checked){
/* if checked, ajax? change html values(ie hidden)? that's up to you /
or
document.getElementById('inputSelected').type = "" / change it accordingly */
}
}

Why the text fields are not getting disabled="disabled" in colorbox popup?

I'm using PHP, Smarty , jQuery, Colorbox - a jQuery lightbox plugin, etc. for my website. Now I'm displaying some output in a popup which is generated by using " Colorbox - a jQuery lightbox plugin". Now I want to disable all the text fields present in this popup when the form loads but if I go to the HTML source of page the disabled="disabled" attribute from the <input> tag gets removed and the text boxes are not getting disabled. Can you tell me why this is happening? For your reference I'm putting below the code which will display the data in a Colorbox pop up.
{if $subject_topic_questions}
{foreach from=$subject_topic_questions item=subject_topic_data}
<div class="hidden">
<div id="topics_{$subject_topic_data.subject_id}" class="c-popup">
<h2 class="c-popup-header">Select Topics</h2>
<div class="c-content">
<input type="hidden" name="subject_names[{$subject_topic_data.subject_id}]" id="subject_names" value="{$subject_topic_data.subject_name}">
<h2 class=""> {$subject_topic_data.subject_name}</h2>
<div class="c-tbl-wrap">
<table width="100%" cellspacing="0" cellpadding="0" border="0" class="c-tbl">
<tbody>
<tr>
<td>
<p class="custom-form">
<input class="custom-check" type="checkbox" name="" id="">
<label class="blue">Select All</label>
</p>
</td>
{foreach from=$difficulty_levels item=diff_levels key=dkey}
<input type="hidden" name="diff_levels[{$dkey}]" value="{$diff_levels}">
<td width="22%" align="center"><strong>{$diff_levels}</strong></td>
{/foreach}
</tr>
{foreach from=$subject_topic_data.topics item=topic_diff_level_data}
<input type="hidden" name="subject_{$subject_topic_data.subject_id}_topics[]" value="{$topic_diff_level_data.topic_id}">
<tr>
<td valign="middle">
<p class="custom-form">
<input type="checkbox" class="custom-check" name="{$sheet_type}_topics_{$subject_topic_data.subject_id}[]" id="{$sheet_type}_{$subject_topic_data.subject_id}_{$topic_diff_level_data.topic_id}" value="{$topic_diff_level_data.topic_id}" onChange="enable_topic_ques('{$sheet_type}', '{$subject_topic_data.subject_id}', '{$topic_diff_level_data.topic_id}'); return false;">
<label>{$topic_diff_level_data.topic_name}</label>
<!-- <input type="hidden" name="topic_names[{$topic_diff_level_data.topic_id}]" value="{$topic_diff_level_data.topic_name}"> -->
</p>
</td>
{foreach from=$topic_diff_level_data.difficulty_level item=diff_level key=key_diff_lvl}
<td valign="middle">
{if $site_id=='ENTPRM'}<em>Total {$diff_level.question_count}</em>{/if}
<input type="text" name="{$sheet_type}_{$subject_topic_data.subject_id}_{$topic_diff_level_data.topic_id}_{$key_diff_lvl}" id="{$sheet_type}_{$subject_topic_data.subject_id}_{$topic_diff_level_data.topic_id}_{$key_diff_lvl}" maxlength="3" class="mini" value="{$diff_level.added_no_questions}" disabled="disabled">
<input type="hidden" name="{$sheet_type}_available_questions_{$subject_topic_data.subject_id}_{$topic_diff_level_data.topic_id}_{$key_diff_lvl}" value="{$diff_level.question_count}">
</td>
{/foreach}
</tr>
{/foreach}
</tbody>
</table>
</div>
<p class="center">Done Cancel</p>
</div>
</div>
</div>
{/foreach}
{/if}
The main code you need to consider is as below from the above code:
<input type="text" name="{$sheet_type}_{$subject_topic_data.subject_id}_{$topic_diff_level_data.topic_id}_{$key_diff_lvl}" id="{$sheet_type}_{$subject_topic_data.subject_id}_{$topic_diff_level_data.topic_id}_{$key_diff_lvl}" maxlength="3" class="mini" value="{$diff_level.added_no_questions}" disabled="disabled">
Can you tell me how the disabled="disabled" attribute gets vanishes after page load and if there is any way to apply to it, please tell me. Thanks in advance.
$('.mini').prop("disabled", true);
$('.mini').prop("disabled", false);
try this

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.

Categories