I have simple registration form and the password inputs are:
<label for="pass">Password:</label>
<div class="input-group input-group-md">
<span class="input-group-addon" id="sizing-addon1"><span class="glyphicon glyphicon-cog"></span></span>
<input type="password" class="form-control" placeholder="Password" aria-describedby="sizing-addon1" id="pass">
</div>
<br>
<label for="pass_confirm">Confirm password:</label>
<div class="input-group input-group-md">
<span class="input-group-addon" id="sizing-addon1"><span class="glyphicon glyphicon-envelope"></span></span>
<input type="password" class="form-control" placeholder="Confirm password" aria-describedby="sizing-addon1" id="confirmPass">
</div>
<br>
<p id="passwordMatch"></p>
I want the paragraph with id="passwordMatch" to show up and depending on the result to show the exact text needed. My jquery code is:
$('#confirmPass').on('keyup', function () {
if ($('#confirmPass').val() == $('#pass').val()) {
$('#passwordMatch')[0].style.display = "block";
// use array to convert jquery to object $('#passwordMatch').html('Password match!').css('color', 'green');
} else {
$('#passwordMatch').html('Password do not match!').css('color', 'red');
}
});
But when i type some random passwords in the inputs the console is telling me that the .style attribute is not defined. Before that i was using $('this') but i found out that i get an object and because of that i cant access DOM directly. Nevermind, changed it with if('#confirmPass').val() and i still get the same error.
If you need to access the DOM object directly you should use $('#passwordMatch')[0].style.display = "block";
But as you already use jQuery I suggest you to use $('#passwordMatch').show();
The problem is that you're using .style on a jquery Selector - try this instead of .style:
$('#passwordMatch').css("display", "block");
change the line of code to:
$('#passwordMatch').css({'display':'block'});
$('#passwordMatch') returns a collection, so it doesn't have a style attribute. You should probably pick whether you are going to be using jQuery or pure javascript and stick to it. jQuery -> $('#passwordMatch').css('display','block');
If you really wanted to, you could also do:
$('#confirmPass').on('keyup', function () {
if ($('#confirmPass').val() == $('#pass').val()) {
$('#passwordMatch')[0].style.display = "block";
$('#passwordMatch').html('Password match!').css('color', 'green');
} else {
$('#passwordMatch').html('Password do not match!').css('color', 'red');
}
});
Related
I am doing this for validating multiple input fields with different data intake using a generic function to which I can pass RegExp output and display the validation message or icon.
This is my HTML code
<div class="form-group">
<label for="fname" class="form-lable">First name</label>
<input type="text" id="fname" name="fname" class="form-input" required>
<div for="fname">
<span class="validation-container success"><i class="bi bi-check2"></i></span>
<span class="validation-container error"><i class="bi bi-x"></i></span>
</div>
</div>
<div class="form-group">
<label for="lname" class="form-lable">First name</label>
<input type="text" id="lname" name="lname" class="form-input" required>
<div for="lname">
<span class="validation-container success"><i class="bi bi-check2"></i></span>
<span class="validation-container error"><i class="bi bi-x"></i></span>
</div>
</div>
This is what I am doing
$('#fname').on('keyup', function () {
$('.validation-container').hide();
});
$('#lname').on('keyup', function () {
$('.validation-container').hide();
});
What it does:
It's doing that thing for both of the inputs.
$('#fname').on('keyup', function () {
$(this).parent().find('.validation-container').hide();
let check = fnameRegExp.test($(this).val());
let success = ".validation-container.success";
let wrong = ".validation-container.error";
validateInput(check, success, wrong);
});
What I am doing here is sending regex match, success as well as wrong classes to the function. If the input is not matched with the regex then it will display the div having that wrong class.
function validateInput(check, success, wrong) {
if (check) {
$(success).show();
checkAll();
} else {
$(wrong).show();
}
}
And I am calling that function on keyup for each input. what it does is, it shows validation signs (✅, ❎) for every input.
change this
<div for="fname" id="fnameValidators">
<span class="validation-container success"><i class="bi bi-check2"></i></span>
<span class="validation-container error"><i class="bi bi-x"></i></span>
</div>
$('#fname').on('keyup', function () {
$('#fnameValidators').hide();
});
Similarly make changes for last name.
TL;DR
Use
$(this).parent().find('.validation-container').hide();
To hide only the element with that class within the same container.
Longer version
$('.validation-container') searches in the whole DOM. To restrict it, you can use this selector within another element. Since you're reading the keyup event on the input, you can simply use $(this) to obtain the input object. Then go over 1 level with .parent() to select the <div class="form-group"> containing it and finally use find('.validation-container') to select the correct span you want to hide.
As one-liner:
$(this).parent().find('.validation-container').hide();
Even more dynamic
If you want to make this even more dynamic, you can avoid calling a keyup event for each separate input, and create a single function that manages all your inputs correctly.
$('.form-lable').on('keyup', function () {
var type = $(this).attr('id')
// You can use the variable type to distinguish between the two inputs
$(this).parent().find('.validation-container').hide();
});
Try this
$('#fname').on('keyup', function () {
$("div[for='fname']").find('.validation-container').hide();
});
$('#lname').on('keyup', function () {
$("div[for='lname']").find('.validation-container').hide();
});
Here is my jsfiddle
Basically I want to append a span element within the span with id 'spanValidation'. And also I want to add and remove some classes in some elements.Previously it was done using Custom Model validation in MVC and JQuery,but now I want to handle it in JQuery.
This is my HTML:
<div class="form-group">
<div class="row">
<div class="col-md-4">
<label class="control-label text-primary" for="SSN">Social Security Number</label><span> </span><span class="help-inline">(Last Four Digits Only)</span>
<input name="SSN" class="form-control" id="SSN" type="text" value="" data-val-length-max="4" data-val-length="Enter only the last four digits of the SSN." data-val="true" data-val-regex-pattern="^\d{4}$" data-val-regex="Enter only the last four digits of the SSN.">
</div>
<div class="col-md-4">
<br class="hidden-sm hidden-xs">
<span class="field-validation-valid text-danger" id="spanValidation" data-valmsg-replace="true" data-valmsg-for="SSN"></span>
</div>
<div class="col-md-4">
</div>
</div>
</div>
<button type="submit" id="btnSubmit" class="btn btn-primary">Submit</button>
This is my JS:
$('#btnSubmit').click(function (event) {
alert("hi");
if ( $("#SSN").val() === "" ) {
$(".spanValidation").addClass("field-validation-error").removeClass("field-validation-valid");
$(".spanValidation").append("<span >Enter at least one of the following: Account Number, SSN, or Birth Date.</span>");
}
else {
$(".spanValidation").removeClass("field-validation-error").addClass("field-validation-valid");
$('span[id^="errorSpan"]').remove();
}
}
The problem is, even though the code is getting executed, but ut is not adding the new span with id 'errorSpan' and also it is not updating the classes associated with the elements.
Thanks in advance.
You want to include jQuery and add a closing ) and bear in mind that id selectors are referenced by a # and not by a . as noted in the comments:
$('#btnSubmit').click(function (event) {
alert("hi");
if ( $("#SSN").val() === "" ) {
$("#spanValidation").addClass("field-validation-error").removeClass("field-validation-valid");
$("#spanValidation").append("<span >Enter at least one of the following: Account Number, SSN, or Birth Date.</span>");
}
else {
$("#spanValidation").removeClass("field-validation-error").addClass("field-validation-valid");
$('span[id^="errorSpan"]').remove();
}
});
DEMO
If you inspect the HTML you'll see that the span does get appended.
UPDATE
To remove the span use:
$('#spanValidation').empty();
Instead of $('span[id^="errorSpan"]').remove(). The new span does not have an id and, unless there's any content you'd want to retain in the parent span, you should not worry about assigning a selector as .empty() removes all content.
DEMO
Use it like this: spanValidation is id while you are using it like a class
$('#btnSubmit').click(function (event) {
alert("hi");
if ( $("#SSN").val() === "" ) {
$("#spanValidation").addClass("field-validation-error").removeClass("field-validation-valid");
$("#spanValidation").append("<span >Enter at least one of the following: Account Number, SSN, or Birth Date.</span>");
}
else {
$("#spanValidation").removeClass("field-validation-error").addClass("field-validation-valid");
$('span[id^="errorSpan"]').remove();
}
}
i am trying to validate some fields in my webpage s an input can only take a number. But it is not working.
this is the html:
<div class="form-group has-feedback">
<label class="control-label" for="mcc">GSM.Identity.MCC</label>
<br/>
<input type="text" class="form-control" name="mcc" id="mcc" value="${mcc}">
<span class="glyphicon form-control-feedback"></span>
</div>
and this is the script:
<script type="text/javascript">
$(document).ready(function(){
$("#mcc").on('keypress',function(){
if(!$.isNumeric(this.val())){
$(this).parent("div").removeClass("has-feedback").addClass("has-error");
}
else{
$(this).parent("div").removeClass("has-feedback").addClass("has-success");
}
});
});
</script>
i have tried altering and changing in someways, it gives no result whatsoever.
note: i am using bootstrap for css and styles, "hass-error" class marks the input red
change this:
if(!$.isNumeric(this.val())){
to this:
if(!$.isNumeric(this.value)){
or more jQuery way:
if(!$.isNumeric($(this).val())){
and in the else part, may be in some case you need to remove the has-error class too:
else{
$(this).parent("div")
.removeClass("has-feedback has-error")
.addClass("has-success");
}
HTML5
<input type="number" class="form-control" name="mcc" id="mcc" value="${mcc}">
Notice the input type is now number instead of text.
Javascript:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#first").keyup(function(event){
event.preventDefault();
ajax_check("#first");
});
$("#last").keyup(function(event){
event.preventDefault();
ajax_check("#last");
});
});
function ajax_check(current)
{
var check=$(current).val();
$.post("validate.php", {tocheck : check}, function(filled) {
if(filled == '1')
{
$(".check").html("");
$(".ajax_check").removeClass("error");
$(".ajax_check").addClass("success");
}
else
{
$(".check").html("");
$(".ajax_check").removeClass("error");
$(".ajax_check").removeClass("success");
}
})
}
HTML
<div class="control-group ajax_check">
<label class="control-label" for="first">First Name</label>
<div class="controls">
<input type="text" id="first" class="validate" placeholder="First" required>
<span class="help-inline check" ></span>
</div>
</div>
<div class="control-group ajax_check">
<label class="control-label" for="last">Last Name</label>
<div class="controls">
<input type="text" id="last" class="validate" placeholder="Last" required>
<span class="help-inline check" ></span>
</div>
</div>
The issue I'm having is when I enter in info for one of the input, the other one gets highlighted too, which isn't suppose to happen. And I think my code is kind of sloppy, but I'm trying to reuse the ajax_check function instead of making a function for each input field.
Is there a way I could reuse the function for both of the inputs? I'm new to Javascript, so I'm kind of lost. Thank you!
http://i.imgur.com/BiLObRF.png
it has to do with the scope you're requesting .check within in the ajax call. You're going back to document-level (instead of just within the current node). A simple change makes this work as intended:
var $this = $(current), // store reference to jquery object
$scope = $this.closest('.ajax_check'), // set scope to .ajax_check
check = $this.val();
$.post("validate.php", {tocheck : check}, function(filled) {
if(filled == '1')
{
// use .find() to search _within_ $scope and not across
// the entire document.
$scope.find(".check").html("");
$scope.removeClass("error").addClass("success");
}
else
{
// same thing, search within $scope
$scope.find(".check").html("");
$scope.removeClass("error success");
}
})
You can also refactor your bindings a bit to make this a little more brief as well:
$("#first,#last").keyup(function(event){
event.preventDefault();
ajax_check(this); // this is automatically going to be #first or #last
// just by the selector above
});
You can use comma to add items in selector, you can use this to get current element,
$("#first, #last").keyup(function(event){
event.preventDefault();
ajax_check('#'+this.id);
});
OR, pass object instead of id.
$("#first, #last").keyup(function(event){
event.preventDefault();
ajax_check($(this));
});
function ajax_check(current)
{
var check=current.val();
You need to save the this reference and search the closest form :
function ajax_check(e)
{
e.preventDefault()
var $this = $(this)
var check=$this.val();
$.post("validate.php", {tocheck : check}, function(filled) {
$this.siblings(".check").html("");
$this.closest(".ajax_check").removeClass("error").toggleClass("success", filled == '1');
})
}
$("#first, #last").keyup(ajax_check);
siblings
closest
Here is my HTML Form :-
<input name="inputPassword" type="password" id="inputPassword" placeholder="Password.."><span class="add-on"><i class="icon-eye-open"></i></span>
And here is my try with Jquery [I am not Jquery Student :(]
<script type="text/javascript">
$(".icon-eye-open").click(function(){
$('.icon-eye-open').removeClass('icon-eye-open').addClass('icon-eye-close');
document.getElementById("inputPassword").setAttribute('type', 'text');
});
$(".icon-eye-close").click(function(){
$('.icon-eye-close').removeClass('icon-eye-close').addClass('icon-eye-open');
document.getElementById("inputPassword").setAttribute('type', 'password');
});
</script>
So, you might have guessed, what i am trying to do. I am actually trying to replace class of clicked class [toggle-ing between class] and than trying to change attribute from password to text and vice versa.
And this is not Working.
Here is jsfiddle demo :- http://jsfiddle.net/gR5FH/
Can you please suggest / help me find my mistake.
Thanks
Try this
$(".icon-eye-open").on("click", function() {
$(this).toggleClass("icon-eye-close");
var type = $("#inputPassword").attr("type");
if (type == "text")
{ $("#inputPassword").attr("type", "password");}
else
{ $("#inputPassword").attr("type", "text"); }
});
Your problem is that the element $(".icon-eye-close") does not exist when you start listening the click event, so that code never runs. You can prevent this by using an unique event handler for the click and then toggle classes and input type within it.
Try this HTML:
<input name="inputPassword" type="password" id="inputPassword" placeholder="Password...">
<span class="add-on">
<i id="visibilitySwitch" class="icon-eye-close"></i>
</span>
With this JS:
$("#visibilitySwitch").click(function(){
$(this)
.toggleClass('icon-eye-open')
.toggleClass('icon-eye-close');
if ($('#inputPassword').attr('type') == 'password')
$('#inputPassword').attr('type', 'text')
else
$('#inputPassword').attr('type', 'password')
});