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");
}
}
Related
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 a number of inputs like this:
<div class="fg-line">
<input type="text" class="form-control fg-input place-edit placeInformation" id="place_name">
<label class="fg-label">Place Name</label>
</div>
<div class="fg-line">
<input type="text" class="form-control fg-input place-edit placeInformation" id="place_address">
<label class="fg-label">Place Address</label>
</div>
I get some data from an API and then append to these inputs (so the user can edit).
This works fine. The issue is that I want to add a class to this:
<div class="fg-line">
This is simple enough if I only have one of these and one input, but since I have multiple, I need some way to check each input and if not empty add the class fg-toggled such that the line becomes:
<div class="fg-line fg-toggled">
If I had just one input, I'd do this:
if (('#place_name').value != '' || ('#place_name').value != ('#place_name').defaultValue) {
$('.fg-line').addClass('fg-toggle')
}
But I don't know how to do this without writing this out for every class (there are 30+). Is there a way to iterate this somehow? I tried checking .place-edit but since it's a class, if any of the inputs with the class are not empty then they all get the new class added.
Simply loop through each input and find the parent using .closest().
$('.placeInformation').each(function() {
var $input = $(this);
if ($input.val()) {
var $parent = $input.closest('.fg-line');
$parent.addClass('fg-toggled')
}
});
Sample plunkr
Can use filter()
$('.fg-line').has('.placeInformation').filter(function(){
return !$(this).find('.placeInformation').val()
}).addClass('fg-toggled')
Not sure what "default" should be or how it is declared. Could be set in a data attribute and add an || to above filter condition
Use each() and closest()
Try this :
$(".fg-input").each(function() {
if ($(this).val() != '') {
$(this).closest(".fg-line").addClass('fg-toggle');
}
})
.fg-toggle
{
color:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fg-line">
<input type="text" class="form-control fg-input place-edit placeInformation" id="place_name">
<label class="fg-label">Place Name</label>
</div>
<div class="fg-line">
<input type="text" class="form-control fg-input place-edit placeInformation" id="place_address">
<label class="fg-label">Place Address</label>
</div>
You could just loop through the .place-edit class and then check the values and add the class to the parents, like this:
$('.place-edit').each(function(){
if($(this).val() != '' || $(this).val() != $(this).defaultValue) {
$(this).parent().addClass('fg-toggle');
}
})
Try this.. I'm assuming they all have the same class
if (('#place_name').value != '' || ('#place_name').value != ('#place_name').defaultValue) {
$('.fg-line').each(function(){
$(this).addClass('fg-toggle')
});
}
Alright so I have a form. In the form I have a lot of check boxes. If a person clicks on the checkbox. It shows the field below the box. If they click on the checkbox again it makes the field below the checkbox disappear and makes the field have no value.
here is the code. I have JS running the show and hide. and Html calling it.
function ShowCutSewDescription() {
var select = $('#send_item_to_cutsew');
console.log(select)
//select = parseInt(select);
if (select.attr('checked', true)) {
$('#cutsew-checked').show();
}else {
$('#cutsew-checked').hide();
}
}
<div class="form-group">
<label class="col-md-3 control-label">Sending item to Cut/Sew Manager</label>
<div class="col-md-9">
<input type="checkbox" name="send_item_to_cutsew" class="form-control input-inline input-medium" placeholder="Enter text" onchange="ShowCutSewDescription()">
</div>
Changes made
► select.attr('checked', true) to select.is(":checked")
► $('#send_item_to_cutsew') to $('[name="send_item_to_cutsew"]') since there is no element with that Id.
Working Demo
function ShowCutSewDescription() {
var select = $('[name="send_item_to_cutsew"]');
if (select.is(":checked")) {
$('#cutsew-checked').show();
} else {
$('#cutsew-checked').hide();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label class="col-md-3 control-label">Sending item to Cut/Sew Manager</label>
<div class="col-md-9">
<input type="checkbox" name="send_item_to_cutsew" class="form-control input-inline input-medium" placeholder="Enter text" onchange="ShowCutSewDescription()">
</div>
<div id="cutsew-checked">
Sample box
</div>
I assume this is using jQuery. If so, the selector that you have input is looking for something with an id of send_item_to_cutsew.
jQuery uses css selectors as a base, as referenced by this page: https://api.jquery.com/category/selectors/
The proper way to get the input that you want based on the name is as follows:
var select = $('[name="send_item_to_cutsew]');
or you can set the id to the above like so:
<input type="checkbox" id="send_item_to_cutsew" name="send_item_to_cutsew" class="form-control input-inline input-medium" placeholder="Enter text" onchange="ShowCutSewDescription()">
i want to get each value when a button clicked.
what i missed?
//add row
$("#btnAdd").click(function(){
$(".oItem:last").clone().insertAfter(".oItem:last");
});
//submit
$("#btnCalc").click(function(){
$("[id^=txtItemName]").each(function(){
alert($("#txtItemName").val());
});
});
my fiddle here
https://jsfiddle.net/k5ndm840/3/
thanks
You are using the same ID for each new field being added. You should use class instead of id in your case as id has to be unique.
Use $(this).val(); as you will be getting this => current element in each iteration. In each callback, this refers to the element
$("#txtItemName") will always select first element having id as txtItemName
Try this:
$("#btnAdd").click(function() {
$(".oItem:last").clone().insertAfter(".oItem:last");
});
$("#btnCalc").click(function() {
$("[id^=txtItemName]").each(function() {
alert($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="btnAdd">Add</button>
<button id="btnCalc">Submit</button>
<div class="masterItem">
<div class="row oItem">
<div class="col-md-4">
<div class="form-group">
<div class="input-group"><span class="input-group-addon" style="font-weight:bold;color:#330099">Quantity</span>
<input id="txtItemName" type="text" class="form-control" placeholder="put random number here" aria-describedby="basic-addon1">
</div>
</div>
</div>
</div>
</div>
Fiddle here
Edit: As per the www standards, There must not be multiple elements in a document that have the same id value. [Ref]. As you are dealing with attribute selector, you are not facing any issue but ID MUST BE UNIQUE
Edit: To find another child under the parent element, use .closest() to find the parent element and .find() to select child of the parent.
Try this:
$("#btnAdd").click(function() {
$(".oItem:last").clone().insertAfter(".oItem:last");
});
$("#btnCalc").click(function() {
$("[id^=txtItemName]").each(function() {
alert($(this).val());
alert($(this).closest(".form-group").find('[id=txtTwo]').val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<button id="btnAdd">Add</button>
<button id="btnCalc">Submit</button>
<div class="masterItem">
<div class="row oItem">
<div class="col-md-4">
<div class="form-group">
<div class="input-group"><span class="input-group-addon" style="font-weight:bold;color:#330099">Quantity</span>
<input id="txtItemName" type="text" class="form-control" placeholder="put random number here" aria-describedby="basic-addon1">
<input id="txtTwo" placeholder="second input">
</div>
</div>
</div>
</div>
</div>
when you are trying to access the elements with id it will always give the first element matching the selector criteria.
$("#txtItemName").val()
This will always give the value of first matching element. Try to do like this.
//submit
$("#btnCalc").click(function(){
$("[id^=txtItemName]").each(function(){
console.log($(this).val());
});
});
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();
}
}