I have a series of forms that correspond to likert questions:
<form class="indicator-form" request="post">
<fieldset>
<label class="top-label">
Enter the number of <strong>category 1</strong> staff that answered each level of importance on a 5-point likert-field scale for the question:<br/>
<em>Question 1?</em>
</label>
<table>
<tr class="likert">
<td>
<label for="cat1_a">Very Unimportant</label>
<input id="cat1_a" name="cat1_a" class="likert-field" type="text" />
</td>
<td>
<label for="cat1_b">Unimportant</label>
<input id="cat1_b" name="cat1_b" class="likert-field" type="text" />
</td>
<td>
<label for="cat1_c">Neutral</label>
<input id="cat1_c" name="cat1_c" class="likert-field" type="text" />
</td>
<td>
<label for="cat1_d">Important</label>
<input id="cat1_d" name="cat1_d" class="likert-field" type="text" />
</td>
<td>
<label for="cat1_e">Very Important</label>
<input id="cat1_e" name="cat1_e" class="likert-field" type="text" />
</td>
</tr>
</table>
</fieldset>
<fieldset>
<label class="top-label">
Enter the number of <strong>category 2</strong> staff that answered each level of importance on a 5-point likert-field scale for the question:<br/>
<em>Question 2?</em>
</label>
<table>
<tr class="likert">
<td>
<label for="cat2_a">Very Unimportant</label>
<input id="cat2_a" name="cat2_a" class="likert-field" type="text" />
</td>
<td>
<label for="cat2_b">Unimportant</label>
<input id="cat2_b" name="cat2_b" class="likert-field" type="text" />
</td>
<td>
<label for="cat2_c">Neutral</label>
<input id="cat2_c" name="cat2_c" class="likert-field" type="text" />
</td>
<td>
<label for="cat2_d">Important</label>
<input id="cat2_d" name="cat2_d" class="likert-field" type="text" />
</td>
<td>
<label for="cat2_e">Very Important</label>
<input id="cat2_e" name="cat2_e" class="likert-field" type="text" />
</td>
</tr>
</table>
</fieldset>
<input type="submit" value="Submit Data"/>
</form>
I want to validate each table row so that:
If there is no data in the row, no validation is applied (i.e. a user
can submit an empty row)
If there is any data in the row, all fields must be filled out.
My JS:
// Likert Row Validation
jQuery.validator.addMethod('likert', function(value, element) {
var $inputs = $(element).closest('tr.likert').find('.likert-field:filled');
if (0 < $inputs.length && $inputs.length < 5 && !($(element).val())){
return false;
} else {
return true;
}
}, 'Partially completed rows are not allowed');
// Likert Fields
jQuery.validator.addClassRules('likert-field', {
likert: true
});
var validator = $('.indicator-form').validate({
errorPlacement: function(error, element){
errorPos = element;
errorClass = 'alert-arrow-center';
error.insertAfter(errorPos).addClass(errorClass);
}
});
On the face of it, this validation works - but if you start playing around with it, it becomes clear that the rule is only applied to the fields that are blank when the submit button is clicked.
How can I make it so that the validation rule applies to all fields unless there is no data at all?
JSfiddle here: http://jsfiddle.net/6RtcJ/1/
It's behaving strangely because validation is only triggered for one field at a time (unless you click the submit). If you blank out data in one field, then only the one field is re-evaluated. This is why you have messages lingering around on other fields.
It's not ideal, but you can force the whole form to re-validate on every keyup and blur event using the valid() method like this...
$('input').on('blur keyup', function() {
$('.indicator-form').valid();
});
Your demo: http://jsfiddle.net/6RtcJ/20/
Same idea, but only triggered by blur event...
http://jsfiddle.net/6RtcJ/21/
Quote OP:
"... it becomes clear that the rule is only applied to the fields that are blank when the submit button is clicked."
If you're expecting validation messages to appear on a field even after the same field passes validation, then that's not how this plugin works.
There are ways to group messages together using the groups option, which may help you a bit. You can also use the errorPlacement callback to position the one message for the whole row.
The way the groups option works is that it will group all error messages for several fields into one message... so only after all fields in the group pass validation, the single message will go away.
I've set the onkeyup option to false in this example since all fields now share the same message.
groups option demo: http://jsfiddle.net/6RtcJ/22/
ok , i got your meaning.
there are some solution here.
1.remove the rules on this form when all input not insert any word.
2.add the rules ,if one of the input had data.
you should do a check before validation?
Try this:
$(document).ready(function(){
$('.indicator-form').validate({
onfocusout:false,
submitHandler: function (form) {
alert('Form Submited');
return false;
}
});
// Likert Fields
/*
$('.likert-field').each(function(){
$(this).rules('add',{
required: true,
messages: {
required: "Partially completed rows are not allowed",
},
});
});
*/
$("input[type='submit']").click(function(){
$("tr.likert").each(function(){
var $inputs = $(this).find('.likert-field:filled');
if (0 < $inputs.length && $inputs.length < 5) {
$(this).children('td').children('.likert-field').each(function() {
$(this).rules('add',{
required: true,
});
});
} else {
$(this).children('td').children('.likert-field').each(function() {
$(this).rules('remove');
});
}
});
});
});
Related
I have an HTML form and using Javascript to validate the form. However, when I use setCustomValidity(), it doesn't seem to work properly. I have to click on the submit button twice to mark the field as invalid, and then when the correct input is entered, the field is not marked as valid again, i.e. the error message keeps repeating.
Here's my HTML:
<form id="data_form" onsubmit="event.preventDefault(); return validateForm();">
<table>
<tr>
<td colspan="2" class="right_align">
<label for="supplier_ref"> Supplier Reference Number: </label>
</td>
<td colspan="2">
<input id="supplier_ref" name="supplier_ref" type="number" required>
</td>
</tr>
<!-- more rows -->
<button id="generate" name="generate" type="submit" onclick=""> Generate Barcode </button>
</table>
</form>
Javascript:
function validateForm() {
var form = document.forms["data_form"];
var emptymsg = "Field must be filled out.";
var supplier_ref = form.elements["supplier_ref"];
var supplier_ref_value = supplier_ref.value.toString();
if (supplier_ref_value == "") {
supplier_ref.setCustomValidity(emptymsg);
return false;
}
if (supplier_ref_value.length != 9){
supplier_ref.setCustomValidity("Number has to be 9 digits long.");
return false;
} else {
supplier_ref.setCustomValidity("");
}
return true;
}
When the length of the Supplier Reference is less than 9 digits, the error message appears, but when I enter the correct length, I still get the same error.
I would appreciate any help.
Thanks in advance
Nvm it only works with addEventListener
I've tried, I've researched, and I still can't figure out how to validate this form using jQuery. I've even tried to check out the jQuery API and I had no luck with it. This shouldn't be as hard as it seems. There are a few id's that i'm not using yet because I want to get what I have so far working before I continue. The best I could find for validating emails is just straight up JavaScript. Here's my code.
$(document).ready(function(){
$("#sendForm").click(function(){
var validForm=true; //set valid flag to true, assume form is valid
//validate customer name field. Field is required
if($("#custName").val()) {
$("#custNameError").html(""); //field value is good, remove any error messages
} else {
$("#custNameError").html("Please enter your name.");
validForm = false;
}
//validate customer phone number. Field is required, must be numeric, must be 10 characters
var inPhone = $("#custPhone").val(); //get the input value of the Phone field
$("#custPhoneError").html(""); //set error message back to empty, assume field is valid
if(!inPhone) {
$("#custPhoneError").html("Please enter your phone number.");
validForm = false;
} else {
//if( !$.isNumeric(inPhone) || Math.round(inPhone) != inPhone ) //if the value is NOT numerice OR not an integer. Rounding technique
if( !$.isNumeric(inPhone) || (inPhone % 1 != 0) ) //if the value is NOT numerice OR not an integer. Modulus technique
{
$("#custPhoneError").html("Phone number must be a number.");
validForm = false;
} else {
if(inPhone.length != 10) {
$("#custPhoneError").html("Phone number must have 10 numbers");
validForm = false;
}
}
}
//ALL VALIDATIONS ARE COMPLETE. If all of the fields are valid we can submit the form. Otherwise display the errors
if(validForm) {
//all values are valid, form is good, submit the form
alert("Valid form will be submitted");
//$("#applicationForm").submit(); //SUBMIT the form to the server
} else {
//form has at least one invalid field
//display form and associated error messages
alert("Invalid form. Display form and error messages");
}
}); //end sendform.click
}); //end .ready
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
label {
width:150px;
display:inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2></h2>
<h3>Form Validation Project - Complaint Form</h3>
<form id="form1" name="form1" method="post" action="">
<p>Please enter the following information in order to process your concerns.</p>
<p>
<label for="custName">Name:</label>
<input type="text" name="custName" id="custName" />
<span id="custNameError" class="errorMsg"></span>
</p>
<p>
<label for="custPhone">Phone Number: </label>
<input type="text" name="custPhone" id="custPhone" />
<span id="custPhoneError" class="errorMsg"></span>
</p>
<p>
<label for = "email">Email:</label>
<input type = "text" name = "emailAdd" id = "emailAdd" />
<span id = "emailError" class = "emailError"></span>
</p>
<p>Please Select Product Group:</p>
<p>
<label>
<input type="radio" name="custProducts" value="books" id="custProducts_0" />
Books
</label>
<br />
<label>
<input type="radio" name="custProducts" value="movies" id="custProducts_1" />
Movies
</label>
<br />
<label>
<input type="radio" name="custProducts" value="electronics" id="custProducts_2" />
Consumer Electronics
</label>
<br />
<label>
<input type="radio" name="custProducts" value="computer" id="custProducts_3" />
Computer
</label>
<br />
</p>
<p>Description of problem: (Limit 200 characters)</p>
<p>
<label for="custComplaint"></label>
<textarea name="custComplaint" id="custComplaint" cols="45" rows="5"></textarea>
</p>
<p>
<input type="submit" name="button" id="button" value="File Complaint" />
<input type="reset" name="button2" id="button2" value="Reset" />
</p>
</form>
<p> </p>
$("#button").click(function(e){
e.preventDefault(); // you need to stop the initial event to have a chance to validate
var validForm=true;
// etc...
You can use jquery.validate.js to validate your forms , it will overcome all your manual efforts to create the validation rules also it is providing the various predefined rules like required,email, minlength and maxlength, etc. So, it will be easier for you to achieve what you need very easily.
https://jqueryvalidation.org/
I have a simple jquery form validation and submission package - see if that's of any help - it's easy to install and you can customise quite a few things: https://github.com/sebastiansulinski/ssd-form
Just to get you started, your submit control in the html has id "button", so you should use $('#button').click, not $('#sendForm').click.
Also, if you want to stay on the page (like to do validations, show errors, etc), you have to prevent the form from submitting automatically when the button is clicked. There are lots of ways to do this, but the easiest way is to just change your button type from submit to button. Ie, replace this:
<input type="submit" name="button" id="button" value="File Complaint" />
with this:
<input type="button" name="button" id="button" value="File Complaint" />
------
That should get you started, at least your code will run, you can use console.log to debug, etc. Good luck.
UPDATE
I should add that if you take my advice, the form will never submit on it's own - that is good if some validation fails and you want to stay on the page and give some error feedback to the user.
When you do want the form to submit, you have to make it happen yourself. Again, there are lots of ways to do this, but the simplest one is probably:
$('#form1').submit();
<tr>
<td>.....</td>
<td>
<div class="...">
<div class="..." id="..." style="display:block;">
<ul id="..." class="..." style="position:relative;">
<%
for(int i = 0;i < len;i++)
{
//get a json object
if(jsonobj != null)
{
//Get style...id..and some other values....
%>
<li class="..." style="display:block;" id="...">
<div style="<%=style%>">
<input type="checkbox" id="<%=Id%>" class="..." value="true" <%if(enabled){%> checked="checked" <%}%> onClick="..."/>
<input id="inp_<%=Id%>" type="text" class="..." style="border:none;padding-left:5px;" value="<%=text%>" title="<%=title%>">
</div>
</li>
<% }
}
%>
</ul>
</div>
</div>
</td>
</tr>
I have a table row like the above code. As you can see, there are two inputs, a checkbox and a text field. While submiting the form I want to validate the text field and show an error message with a small error icon at the right side. But since the input is in a table row I'm unable to to this.
I have a function which shows a tool tip. I just have to pass the id of the element and the message to that function. I want to validate the input field, show a small error image and call the tool tip function so that the tool tip is shown on the error image.
I want the error image to appear next to the required input field i.e., if the 3rd input field is vaidated to false, then the error should be displayed next to the 3rd containing the input field.
How do I do it?
It's a simple task for jQuery. See the example below:
$(document).ready(function(){
$("#btnSave").click(function(){
$(".txtvalidatorMessage").remove() // remove all messages
var inputs = $(".txtvalidator");
function ShowMessage(message, input){
var messageContainer = $("<div class='txtvalidatorMessage'>"+message+"</div>");
messageContainer.insertAfter(input)// show the message beside the input
}
inputs.each(function(){
var validationType = $(this).attr("validationType");
var require = eval($(this).attr("require"));
switch(validationType)
{
case "NotEmpty":
if ($(this).val() == "" && require == true)
ShowMessage("cant be empty",$(this))
break;
case "Number":
var isnum = /^\d+$/.test($(this).val());
if (!isnum && require == true)
ShowMessage("only number",$(this))
break;
}
});
});
});
.txtvalidatorMessage{
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input type='text' value="" placeholder='Cant be empty' class='txtvalidator' validationType='NotEmpty' require='true' />
</td>
</tr>
<tr>
<td>
<input type='text' value="" placeholder='only Number' class='txtvalidator' validationType='Number' require='true' />
</td>
<tr>
<td>
<input type='button' value="Validate" id='btnSave' />
</td>
</tr>
</table>
I have a list of items that need to be selected and take an action based on user's request.
User selects the items and click on one of the btns to do something on the items.
My code is as following but I am not sure how to complete it. I believe, need to put them in a form to be submitted or pass the but not sure how to have a form with two submit btns, (if I need to have ).
<body>
<p><b>Shopping cart</b></p>
<table>
<tbody>
<c:forEach items="${mycart.items}" var="item">
<tr>
<td>
<input type="checkbox" name="Items"
value="${item.ID}"/>
</td>
<td>
Name : ${item.name}
</td>
</tr>
</c:forEach>
</tbody>
</table>
checkout
Delete
you can easily have two <input type="submit" name="something" /> in one <form>
if you want to differentiate the actions, just use different name for each submit button
EDIT:
<form ...>
...
...
<input id="b1" type="submit" name="edit" value="Edit"/>
<input id="b2" type="submit" name="delete" value="Delete"/>
</form>
If the form above is submitted by clicking #b1, then your request will contain a parameter named "edit". If the submit is triggered by #b2, then it will contain "delete".
I think following script might let you obtain what items are checked.
With jQuery, you need implement your checkout() like this
function checkout() {
$('input[name="Items"]:checkbox').each(function() {
if ($(this).attr("checked")) {
alert($(this).val() + 'is checked');
} else {
alert($(this).val() + 'is not checked');
}
}
);
}
I have a form I cobbled together with bits of code copied online so my HTML and Javascript knowledge is VERY basic. The form has a button that will add another set of the same form fields when clicked. I added some code to make it so that if the "Quantity and Description" field is not filled out, the form won't submit but now it just keeps popping up the alert for when the field's not filled out even if it is. Here's is my script:
<script type='text/javascript' src='http://code.jquery.com/jquery-1.5.2.js'>
</script><script type='text/javascript'>
//<![CDATA[
$(function(){
$('#add').click(function() {
var p = $(this).closest('p');
$(p).before('<p> Quantity & Description:<br><textarea name="Quantity and Description" rows="10"
cols="60"><\/textarea><br>Fabric Source: <input type="text" name="Fabric Source"><br>Style# & Name: <input
type="text" name="Style# & Name"><br>Fabric Width: <input type="text" name="Fabric Width"><br>Repeat Information:
<input type="text" name="Repeat Info" size="60"><input type="hidden" name="COM Required" /> </p><br>');
return false;
});
});
function checkform()
{
var x=document.forms["comform"]["Quantity and Description"].value
if (x==null || x=="")
{
alert("Quantity & Description must be filled out, DO NOT just put an SO#!!");
return false;
}
}
//]]>
</script>
And here's my HTML:
<form action="MAILTO:ayeh#janusetcie.com" method="post" enctype="text/plain" id="comform" onSubmit="return
checkform()">
<div>Please complete this worksheet in full to avoid any delays.<br />
<br />Date: <input type="text" name="Date" /> Sales Rep: <input type="text" name="Sales Rep" /> Sales Quote/Order#: <input type="text" name="SQ/SO#" /><br />
<br />Quantity & Description: <font color="red"><i>Use "(#) Cushion Name" format.</i></font><br />
<textarea name="Quantity and Description" rows="10" cols="60">
</textarea>
<br />Fabric Source: <input type="text" name="Fabric Source" /><br />Style# & Name: <input type="text" name="Style# & Name" /><br />Fabric Width: <input type="text" name="Fabric Width" /><br />Repeat Information: <input type="text" name="Repeat Info" size="60" /><br /><font color="red"><i>Example: 13.75" Horizontal Repeat</i></font><br />
<br /><input type="hidden" name="COM Required" />
<p><button type="button" id="add">Add COM</button></p>
</div>
<input type="submit" value="Send" /></form>
How can I get it to submit but still check every occurence of the "Quantity and Description" field?
First, I would not use spaces in your input names, as then you have to deal with weird escaping issues. Use something like "QuantityAndDescription" instead.
Also, it looks like you're trying to have multiple fields with the same name. The best way to do that is to add brackets to the name, meaning the values will be grouped together as an array:
<textarea name="QuantityAndDescription[]"></textarea>
This also means the code has to get all the textareas, not just the first. We can use jQuery to grab the elements we want, to loop over them, and to check the values. Try this:
function checkform()
{
var success = true;
// Find the textareas inside id of "comform", store in jQuery object
var $textareas = $("form#comform textarea[name='QuantityAndDescription[]']");
// Loop through textareas and look for empty values
$textareas.each(function(n, element)
{
// Make a new jQuery object for the textarea we're looking at
var $textarea = $(element);
// Check value (an empty string will evaluate to false)
if( ! $textarea.val() )
{
success = false;
return false; // break out of the loop, one empty field is all we need
}
});
if(!success)
{
alert("Quantity & Description must be filled out, DO NOT just put an SO#!!");
return false;
}
// Explicitly return true, to make sure the form still submits
return true;
}
Also, a sidenote of pure aesthetics: You no longer need to use the CDATA comment hack. That's a holdover from the old XHTML days to prevent strict XML parsers from breaking. Unless you're using an XHTML Strict Doctype (and you shouldn't), you definitely don't need it.