How can I instruct jQuery Validation plug-in to turn off validation based on class attributes and just work based on json rules?
This is conflicting with my jQuery templating system.
First, in your JQuery ready function set the class to 'ignore' or 'require' for each element:
$("#name").attr("class", "required");
$("#email").attr("class", "ignore");
Second, set validate function to ignore the 'ignore' class:
$("#form1").validate({ignore: ".ignore"});
This will require the name but ignore the email.
Looking at the source of jquery.validate.js, there is a variable called classRuleSettings, which stores the validation types based on class names. Set it to a 0 length array and you shold be good.
Try this():
<form>
<input type="text" class="required"/>
<input type="Submit"/>
</form>
<script type="text/javascript">
$.validator.classRuleSettings = []; //I am not sure about any side effects because of this
$("form").validate();
</script>
You can use ignore option
$("form").validate({ignore:".ignore"});
<input type="text" id="fName" class="required ignore"/> <!--fname won't be "required"-->
Related
I have a search input tag that is being added by a jQuery plug-in:
<input type="search" />
Note that this does not have an ID, CLASS, or NAME. I need the search input tag to look like this:
<input type="search" name="myname" />
A simple solution is for me to update the jQuery plug-in. However, I do not want to do this as it will cause challenges when I upgrade this plug-in in the future.
This JavaScript works properly and adds the name attribute:
$(document).ready(function() {
document.getElementsByTagName("input")[0].setAttribute("name", "myname");
});
The problem is that the "[0]" in this function relies on the search input being the first input field in the form. I do not think this solution is sustainable.
There are other inputs in the form. This is the only one with the type attribute equal to "search." Is there a way to identify it by this attribute? Or, is there another solution you propose?
Thank you for your time!
You can use the document.querySelector:
document.querySelector("input[type='search']")
Below is an example (you can inspect the output to see name attribute):
document.querySelector("input[type=search]").setAttribute("name", "myname");
<input type="search" value="foo" />
<input type="bar" value="bar" />
You can target a selection by anything. So, the selector input[type="search"]' will work.
If you want to apply this to all input's of type search, this is good enough, and you get all of them in here:
$('input[type="search"]')
This works without jQuery too:
document.querySelectorAll('input[type="search"]')
A more targeted approach would be
document.querySelectorAll('div.filter input[type="search"]')
I guess this is pretty basic yet I don't know how to solve this puzzle. What I have is two inputs generated by a plugin in Wordpress. What I want to do is to change the placeholders in the fields.
The problem is that the fields ID (which I use to call the inputs via Javascript) is the same, resulting in that only the first inputs placeholder changes.
The auto-generated HTML:
<input type="password" placeholder="Lösenord" name="swpm-19" id="swpm-19" value="" class="swpm-text swpm-large required ">
<input type="password" placeholder="Retype password Here" name="swpm-19_re" id="swpm-19" value="" class="swpm-text swpm-large required ">
The Javascript:
<script type="text/javascript">
jQuery(document).ready(function($){
$('#swpm-19').attr("placeholder","Lösenord");
});
</script>
I have no idea how to call the second input since the ID's are the same. What I did notice is that the names of the inputs is different. The second inputs name is "swmp-19_re". Would it be possible to fetch the input in the Javascript via the name instead of the ID?
You cannot have duplicate id, this is invalid document.
You can use the attribute value selector to select the elements by using name attribute value.
$('input[name="swpm-19"], input[name="swpm-19_re"]').attr('placeholder', 'Lösenord');
You can also use starts with as
$('input[name^="swpm-19"]').attr('placeholder', 'Lösenord');
For more information on the type of CSS (attribute) selectors that jQuery supports check this page.
I have 2 questions:
How to check input better? I have idea:
First, make field near input.
<input type='text' name='firstname'><label id='firstnameError'></label>
Second, call js-function on input onBlur with id of input and id of this label.
<input type='text' name='firstname' id='firstname' onBlur='checkEmpty("firstname", "firstnameError");'><label id='firstnameError'></label>
And js-script:
function checkEmpty(fieldId, errorFieldId)
{
var data = document.getElementById(fieldId).value;
if (data == "")
{
document.getElementById(errorFieldId).innerHTML="Error, input something!...";
}
}
And I will just use this function on all inputs, right?
Is it correct?
How to check all inputs in form correctly?
Sure I can set type=button and onSubmit call some function, which will check all elements in this form. ~ Same function like in first question, but with 5-7 if-blocks for each input. And yes for 10 forms, I will have to write 10 functions, etc. How better do it? Seems to me, I can only send form Id/name and get childs of element. Am I correct?
Maybe another way? I use jquery on my site anyway (some ajax). Maybe it is easier to do what I want on jquery? The problem is I am not too good in js, to use jquery easily. What do you think?
If you just want to verify if some data is provided or not, you can use required attribute.
<input type="text" name="username" required>
if you are using XHTML it should be as shown below..
<input type="text" name="username" required="required">
The required attribute is supported in Internet Explorer 10, Firefox, Opera, and Chrome and is not supported in Internet Explorer 9 and earlier versions, or in Safari.
In case if you want to use JavaScript. You can create a javascript function which will be called on submit of the form.
<form name="search" onsubmit="return validate()" >
Name: <input type="text" name="name"/>
Age: <input type="gender" name="sex"/>
<input type="submit" name="Submit" value="Submit"/>
</form>
function validate(){
// all the code for verification
return false; // if any of the step verification step fails. Otherwise return true.
}
Source: http://www.w3schools.com/tags/att_input_required.asp
To improve on your design, it's better to use non-inline JavaScript. Try using a design like this:
var fname = document.getElementById("firstname");
var other = document.getElementById("otherid");
fname.onblur = other.onblur = function() {
checkEmpty(this.id,this.id+"Error");
}
This will give all your desired elements the same onclick function and eliminate those pesky onblur attributes.
Edit: make sure your variables are declared before you chain assignments like this, or you will yield unwanted global variables.
I have a website form where I have fields that I want to be required (with JQuery Plugin) only when the check-box is checked.
So far I wrote JavaScript that works if the the check-box is not checked, or checked. But when a user checks the check-box and then unchecks it the code does not work (field is still mandatory when unchecked).
Also one other bug is for some reason this same code only works for updating only one items required boolean. For example if I have the same code but make it so two elements requirements are updated the script does not work at all.
Here is the relevant source code:
<script>
function swap(){
if(document.getElementById('must').checked){
document.getElementById("element1").setAttribute("required", "true");
}else{
document.getElementById("element1").setAttribute("required", "false");
}
}
</script>
<form>
<input type="checkbox" onclick="swap();" id="must" name="must" value="1" style="width:10;">
<input id="element1" type="text" name="element1" placeholder="Enter Value" >
<input type="submit" id="submit" name="submit" value="Send" >
</form>
Any assistance would be greatly appreciated.
Best way I know to check if checkbox is checked, it to use jQuery is() method (documentation). It handles x-browser differences for you. Also best way to add attribute to HTML element is to use attr() method.
if($("#must").is(":checked")) {
$("#element1").attr('required', 'required');
} else {
$("#element1").removeAttr();
}
You can check in DOM inspector that attribute is added.
Required attribute documentation is here.
Try this, in xhtml we specify required="required" and there no required="false", a better way is to remove attribute required on else
<script type="text/javascript">
function swap(){
if(document.getElementById('must').checked){
document.getElementById("element1").setAttribute("required", "required");
}else{
document.getElementById("element1").removeAttribute("required");
}
}
</script>
The required attribute is a boolean attribute, it presence means that the field is required and its absence means the field isn't required. It has only 3 valid forms 1. required alone by itself 2. required="" equal to an empty string 3. required="required"
I know what the jQuery Validation plugin is. I know the jQuery Unobtrusive Validation library was made by Microsoft and is included in the ASP.NET MVC framework. But I cannot find a single online source that explains what it is. What is the difference between the standard jQuery Validation library and the "unobtrusive" version?
Brad Wilson has a couple great articles on unobtrusive validation and unobtrusive ajax.
It is also shown very nicely in this Pluralsight video in the section on " AJAX and JavaScript".
Basically, it is simply Javascript validation that doesn't pollute your source code with its own validation code. This is done by making use of data- attributes in HTML.
With the unobtrusive way:
You don't have to call the validate() method.
You specify requirements using data attributes (data-val, data-val-required, etc.)
Jquery Validate Example:
<input type="text" name="email" class="required">
<script>
$(function () {
$("form").validate();
});
</script>
Jquery Validate Unobtrusive Example:
<input type="text" name="email" data-val="true"
data-val-required="This field is required.">
<div class="validation-summary-valid" data-valmsg-summary="true">
<ul><li style="display:none"></li></ul>
</div>
For clarification, here is a more detailed example demonstrating Form Validation using jQuery Validation Unobtrusive.
Both use the following JavaScript with jQuery:
$("#commentForm").validate({
submitHandler: function(form) {
// some other code
// maybe disabling submit button
// then:
alert("This is a valid form!");
// form.submit();
}
});
The main differences between the two plugins are the attributes used for each approach.
jQuery Validation
Simply use the following attributes:
Set required if required
Set type for proper formatting (email, etc.)
Set other attributes such as size (min length, etc.)
Here's the form...
<form id="commentForm">
<label for="form-name">Name (required, at least 2 characters)</label>
<input id="form-name" type="text" name="form-name" class="form-control" minlength="2" required>
<input type="submit" value="Submit">
</form>
jQuery Validation Unobtrusive
The following data attributes are needed:
data-msg-required="This is required."
data-rule-required="true/false"
Here's the form...
<form id="commentForm">
<label for="form-x-name">Name (required, at least 2 characters)</label>
<input id="form-x-name" type="text" name="name" minlength="2" class="form-control" data-msg-required="Name is required." data-rule-required="true">
<input type="submit" value="Submit">
</form>
Based on either of these examples, if the form fields that are required have been filled, and they meet the additional attribute criteria, then a message will pop up notifying that all form fields are validated. Otherwise, there will be text near the offending form fields that indicates the error.
References:
- jQuery Validation: https://jqueryvalidation.org/documentation/
jQuery Validation Unobtrusive Native is a collection of ASP.Net MVC HTML helper extensions.
These make use of jQuery Validation's native support for validation driven by HTML 5 data attributes.
Microsoft shipped jquery.validate.unobtrusive.js back with MVC 3.
It provided a way to apply data model validations to the client side using a combination of jQuery Validation and HTML 5 data attributes
(that's the "unobtrusive" part).