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();
}
}
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();
});
I have a form with a price calculator and while I am able to set all text fields and such using a jQuery script, I can't figure out how to simply set a variable in that jQuery script that is used in a price calculator in another Javascript on the page.
There is a text field with an id of #price_draftarticles that I set a value to - that works but I also have a variable called price_draftarticles that is being added to other variables to create a total. I referenced my Form_Calculator() function but it's still not updating the total.
Relevant form code
<div class="col-sm-8">
<div class="radio">
<label>
<input class="structype" type="radio" name="CorpStructure" id="price_structureop3" value="I want to provide my own structure" onClick="checkRadioCS(); Form_Calculator();"><strong>I want to provide my own structure</strong>
</label>
</div>
</div>
<div class="row">
<div class="col-sm-8">
<div class="checkbox">
<label>
<input name="DraftArticles" type="checkbox" id="DraftArticles" onClick="checkRadioTF(); Form_Calculator();" value="Yes">DETAILS
</label>
</div>
</div>
<div class="col-xs-4 col-sm-2">
<input name="price_draftarticles" type="text" class="form-control fcalc" id="price_draftarticles" value="" readonly>
</div>
</div>
My jquery function
<script>
$(function () {
$('.structype').change(function () {
if ($(this).val() === 'I want to provide my own structure')
{
$("#DraftArticles").prop("checked", true);
$("#price_draftarticles").val('$25.00');
$("price_draftarticles").val('25.00');
$('#CustomStructureDetail').show('500');
}
if ($(this).val() == 'Standard structure template one class of shares') {
$('#CustomStructureDetail').hide('500');
}
if ($(this).val() == 'Two classes of shares') {
$('#CustomStructureDetail').hide('500');
}
});
checkRadioTF();
checkCheckBox();
Form_Calculator();
checkeFileJur();
});
</script>
Looks like you forgot the '#' character in
$("price_draftarticles").val('25.00');
This should be
$("#price_draftarticles").val('25.00');
As what #BYates said the selector missed '#' for price_draftarticles.
$("#price_draftarticles").val('25.00');
But if you're trying to get/set value of the input using it's name. The selector should be like this:
$('input[name="price_draftarticles"]').val('25.00')
i'm using jQuery append function to clone the input fields on front-end, it is working fine but the issue is i have validation on parent element, it is not working on the newly append input fields. This is my jQuery code.
jQuery(function($) {
$("#addChild").click(function() {
$(".name-field:first").clone().find("input").val("").end()
.removeAttr("id")
.appendTo("#additionalselects")
.append($('<a class="delete" href="#"><i class="fa fa-times"></i></a>'));
});
$("body").on('click', ".delete", function() {
$(this).closest(".name-field").remove();
});
});
//Validation
$(document).ready(function() {
$('.name-field').on('input', function() {
// added for bit of simplicity or you can directly get valuess
var name = $('input[name="firstname"]').val();
var date = $('input[name="date"]').val();
if (name != "" && date != "") {
// values seems filled remove class
$('#stepname').removeClass('disabled');
} else {
// user has emptied some input so add class again.
$('#stepname').addClass('disabled');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="name-field" class="name-field row">
<div class="col-xs-12 col-sm-6 childname">
<div class="field text-left">
<label class="text-left">Name of child</label>
<input id="firstname" class="firstname" name="firstname" type="text" />
</div>
</div>
<div class="col-xs-12 col-sm-6 dateofbirth">
<div class="field text-left">
<label class="text-left">Date of birth</label>
<input type="text" class="date" id="thedate" name="date" />
</div>
</div>
</div>
Next Step
Can anyone help me with this, how can achieve this?
Thanks in advance.
As you are adding .name-field dynamically so event are not binding to the new rows try to change your parent element like,
$('#additionalselects').on('input','.name-field input',function(){
//^^^ use other static element or document if not works
var parent = $(this).closest('.name-field'); // get the parent of focused input
var name = parent.find('input[name="firstname"]').val();
var date = parent.find('input[name="date"]').val();
$('#stepname').toggleClass('disabled',(!name || !date));
});
Also you should make the below changes in your HTML,
Remove all id which are part of cloning
Make an array of fields which are to be cloned like firstname[]
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');
}
});
I want to find the closest span with class error_span. How can I do that using jQuery?
<div class="form-group row">
<div class="col-sm-4">
<label for="reimburse_price" class="control label">Amount</label>
</div>
<div class="col-sm-8">
<div>
<input type="text" name="reimburse_price" min="1" placeholder='0.00' class="form-control numberOnly" id="reimburse_price" required>
</div>
<div>
<span class="small text-danger error_span"></span>
</div>
</div>
</div>
My javascript is here
$("#reimburse_price").blur(function(){
checkNumInput("#reimburse_price");
});
My jquery function is here
function checkNumInput(id){
if ($(id).val() == "") {
$(id)[0].setCustomValidity('Please fill out this field');
$(id).closest("span .error_span").text("Please fill out this field").removeClass("hidden").addClass("text-danger");
}
}
The issue with your current code is that closest() looks at parent elements, yet the span you want to find is a child of a parent's sibling to the input.
To solve your issue traverse to a common parent of both the input and span and use find() from there. Try this:
$("#reimburse_price").blur(function() {
checkNumInput('#' + this.id);
});
function checkNumInput(id) {
var $input = $(id);
if ($input.val() == "") {
$input.get(0).setCustomValidity('Please fill out this field');
$input.closest('.form-group').find('.error_span').text("Please fill out this field").toggleClass("hidden text-danger");
}
}