This is my form :
<FORM id="form1">
Fields :
<fieldset name="titles">
<br>
<INPUT class = "fit" type="text" name="title">
<br>
<INPUT class = "fit" type="text" name="title">
<br>
<INPUT class = "fit" type="text" name="title">
<br>
<INPUT class = "fit" type="text" name="title">
</fieldset>
</FORM>
How can I check if at least two out of these four fields are filled? Here's what i'I've tried :
$('#form1').validate({ // initialize the plugin
rules: {
title: {
required: "input[name='title']",
minlength: 2
},
messages: {
title: "You must fill at least two titles!"
}
}
});
But it's not working, it always returns a valid form... I'm a newbie to jQuery, any help would be appreciated.
For 1 statement to grab both 'select' and 'input' elements, simply change your single jQuery selector to a multiple selector,
Eg:-
$(this).find('input[type=text], select').each(function(){
if($(this).val() != "") valid+=1;
});
Try this with the button:
$("#submit_button").click(function(){
if($('input[text]').length < 2) {
alert('at least two text inputs are filled');
return false;
}
});
Related
I'd like to use the label text as the validation message. In order to do this, I tried to use $(label[for="nameAttrName"]), snippet here:
$("#myForm").validate({
rules: {
NameQuery: "required"
},
messages: {
NameQuery: "Please fill in " + $(`label[for="NameQuery"]`).text()
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/additional-methods.min.js"></script>
<form id="myForm">
<label for="NameQuery">Name Query </label>
<input name="NameQuery"/>
<input type="submit" value="Submit"/>
</form>
Question is, how can I refer to the attribute name in the for="" bit so I don't have to write for="NameQuery" explicitly? Like this
Question is, how can I refer to the attribute name in the for="" bit so I don't have to write for="NameQuery" explicitly?
Not sure why you would ever need to write this generically since you must list each and every field explicitly within the rules and messages objects anyway.
However, you could generically target the previous label element relative to the field being validated...
"Please fill in " + $(element).prev('label').text();
And it must be returned from within a function() in order to obtain the element argument from the plugin...
....
required: function(params, element) {
return "Please fill in " + $(element).prev('label').text();
}
....
DEMO:
$("#myForm").validate({
rules: {
NameQuery: {
required: true
}
},
messages: {
NameQuery: {
required: function(params, element) {
return "Please fill in " + $(element).prev('label').text();
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/additional-methods.min.js"></script>
<form id="myForm">
<label for="NameQuery">Name Query </label>
<input type="text" name="NameQuery" />
<input type="submit" value="Submit"/>
</form>
As stated in the topic I need to evaluate two fields, one from a drop-down menu item, and one for a text input type field. both in HTML of course. I want to test if the fields are empty, zero, whatever in that context.
I have tried to alter the code, but cannot seem to find the right code.
$(document).ready(function() {
$(function() {
$("#companyDialog").dialog({
autoOpen: false
});
$("#companyButton").on("click", function() {
$("#companyDialog").dialog("open");
});
});
// Validating Form Fields.....
$("#companySubmit").click(function(e) {
var comnpanyname = $("#companyname").val();
var editcompanyscombo = $("#editcompanyscombo").val();
if (companyname === '' || editcompanyscombo === '') {
alert("Please fill all fields marked with an *!");
e.preventDefault();
} else if (editcompanyscombo === '0') {
alert("Select comany to update!");
e.preventDefault();
} else {
alert("Form Submitted Successfully.");
}
});
});
<div class="container">
<div class="main">
<div id="companyDialog" title="Edit company">
<form action="" method="post">
<## CompanyEditCombo ##><br>
<label>New company name:</label>
<input id="companyname" name="companyname" type="text">
<input id="companySubmit" type="submit" value="Submit">
</form>
</div>
<input id="companyButton" type="button" value="Open Company Edit Dialog Form">
</div>
</div>
The fields pop up, but they do not alert if the values are zero or empty.
So far I could see from these snippets, please replace === '' and === '0' by == null
(Double equality comparison operator does not aimed to compare the types. That is why, one should use it because null is type object. s. Developer Mozilla)
I'm using Jquery Validate in my web form. I have an empty input, however the input is populated dynamically with text on the click of a button. Validation doesn't seem to work when I do this.
when the input is empty, on submit validation works (input turns red).
when input is populated dynamically, it stays red, it should turn green
My code is below and here's a fiddle;
In the fiddle, click submit when the input is empty, then toggle the button to No - the input should change to green without having to submit the form again.
HTML
<p>Does this item have an inventory number?</p>
<p>
<form id="myForm" method="post">
<input type="checkbox" class="input-large" value='1' name="btn" id="btn">
<div class="control-group">
<div class="controls">
<div class="input-prepend">
<input type="text" class="input-large" id="type" name="type" placeholder="Inventory Number">
</div>
</div>
</div>
<input type="submit" class="submit" value="Submit">
</form>
Jquery
$(function() {
$('#btn').bootstrapToggle({
on: 'No',
off: 'Yes',
onstyle: 'danger'
});
})
$("#myForm").validate({
rules: {
type: {
required: true,
minlength: 2
}
},
highlight: function(label) {
$(label).closest('.control-group').addClass('error');
},
unhighlight: function(label) {
$(label).closest('.control-group').addClass('success');
},
});
$("#btn").on("change", function() {
if ($(this).prop('checked') == true) {
$("#type").attr("readonly", "true");
$("#type").val("Personal Item");
$("#type").rules("remove", "number minlength maxlength");
}
if ($(this).prop('checked') == false) {
$("#type").removeAttr("readonly");
$("#type").val("");
$("#type").rules("add", {
required: true,
minlength: 5,
maxlength: 6
});
}
});
You use some custom highlight and unhighlight on the control-group.
Just add this to the checked==true condition:
$("#type").closest('.control-group').removeClass("error").addClass("valid");
$("#type").next(".error").remove();
Since the rule is removed, it is not re-validated...
Your Fiddle updated.
I have a form that allow the user to add additional email input fields. I wanted the make those new fields required. The original single email field functions as expected but not the new ones. I have have tried two approaches with no success.
HTML
<form action="/(S(e5sipzkzq4cbahmey3c2f0xs))/Import/PostEmail" id="EmailForm" method="post" > <fieldset>
<legend>EmailViewModel</legend>
<p>
<input type="email" name="EmailAddresses" value=" " class="email" required="required" />
<span class="btn_orange">x</span>
</p>
<p>
<span class="btn_orange"><a class="add_email_button" href="#">Add Another Email</a></span>
</p>
<p>
<span class="btn_orange"><a type="submit" id="SendEmail_Button">Send Email</a></span>
</p>
</fieldset>
</form>
Add new input:
$('.add_email_button').closest('p').click(function() {
var html = '<p><input type="email" required="required" name="EmailAddresses" /><span class="btn_orange">x</span></p>';
$(html).insertBefore($(this));
});
Approach 1:
$('body').on('click', 'span', function() {
$('input').each(function() {
$(this).attr('required', 'required');
});
});
Approach 2:
$('#SendEmail_Button').closest('span').click(function () {
$('input').each(function() {
$(this).attr('required', 'required');
});
$('#EmailForm').submit();
});
approach 3
$('#SendEmail_Button').closest('span').click(function() {
if ($('#EmailForm').valid()) {
$.post('#Url.Action("PostEmail")', $("#EmailForm").serialize());
history.go(-1);}
});
Try this and target the new input field added by the user in place of input (use a class, more specific).
$('body').on('focus', '.inputClass', function() {
$(this).attr('required', 'required');
});
http://jsfiddle.net/qa0ry2fk/3/
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');
});
}
});
});
});