JQuery selecting only the element inside the selected one - javascript

I'm currently having problem selecting the right element on a form
Here is my code:
$(document).ready(function(){
$(".wpcf7-submit").click(function () {
if($('.errorName').length > 0){
return false;
}
});
var selectorArray = [$('input[name="name"]'), $('input[name="Company"]')];
$.each(selectorArray, function(){
$(this).on('blur',function(){
if($('.errorName').length == 0 && (($(this).val().length < 4 && $(this).val().length != 0) || /^[a-zA-Z0-9- ]*$/.test($(this).val()) == false))
{
$(this).after('<span class="wpcf7-not-valid-tip errorName" role="alert">Field is not right.</span>');
}
else
{
if($(this).val().length > 3 && /^[a-zA-Z0-9- ]*$/.test($(this).val()) == true)
{
$(this).find('.errorName').remove();
}
}
});
});
});
Basically, I want to check, on unfocus, if what the user has input is good for a couple of fields inside the form, else an error message appears. Unfortunately, I can't seem to remove the error message, and this code stucks that message on the first field the user inputs wrong. After that, it won't come off even if the input typed after the first unfocus satisfies the conditions.
I'm testing on a simple form with 2 text inputs and 1 submit. Without the remove part, I can see both messages being displayed and on
$(this).find('errorName').first().remove();
It's the second element that gets stuck with the error message.

You're placing the errorName span after the input element, so you need to look for a sibling instead. You can use .next() for this.
$(this).next('.errorName').remove();

Related

Enable form submit button only after all fields are filled jQuery/JS without repeated checking of all fields

I am trying to find out how can I disable the submit button until all form fields are filled. I have seen there are many solutions online in jQuery and JS.
But what I am looking for is, instead of checking all fields every time when there is a change in the field value, isn't there a way that checks the all the fields altogether at once at the end just like 'required' attribute?
For example, if you see the below solution provided here here.
$("input[type='text'], textarea").on("keyup", function(){
// checking for all fields on "keyup"
if (
$(this).val() != ""
&& $("textarea").val() != ""
&& $("input[name='category']").is(":checked") == true
) {
$("input[type='submit']").removeAttr("disabled");
} else {
$("input[type='submit']").attr("disabled", "disabled");
}
});
$("input[name='category']").on("change", function () {
if (
$(this).val() != ""
&& $("textarea").val() != ""
&& $("input[name='category']").is(":checked") == true
) {
$("input[type='submit']").removeAttr("disabled");
} else {
$("input[type='submit']").attr("disabled", "disabled");
}
});
We can see it's checking for all fields every time on keyup or on change is called. But I need to know if there is any other efficient way rather than checking all fields every time on keyup or on change is called?

jQuery Stop duplicate append

What i'm trying to do here i have 1 select box and one input.
The select box have 3 options with values 1,2 and 3 and the input is in div with id INPUT.
What i want here is when i select the options with value 3 to remove the whole div tag with id INPUT, and then when i click again example on 1 or 2 the DIV tag to append again. But when i'm clicking on 1 or 2 the div tag is appending again and again.
Is there is a chance to check if the div tag exist and not to append.
Here is my jQuery :
$('select').change(function(){
var val = $(this).val();
if(val == '3'){
$('#INPUT').remove();
}
if(val !== '3'){
$('.valuta').before('<div id="INPUT"><input type="text" class="price"></div>');
}
});
Any help will be appreciated.
Thanks.
Yes, it's possible. Change this:
if(val !== '3'){
to this:
if(val != '3' && $("#INPUT").size() == 0){
This way, we're asking if there is already a div with id = INPUT, if there is none, then we add one.
Cheers
Check whether the element with the id INPUT already exists before adding a new one
if (val != '3' && !$('#INPUT').length) {
$('.valuta').before('<div id="INPUT"><input type="text" class="price"></div>');
}
Demo: Fiddle
Also you can fine tune the if condition because if the value is not 3 then you want to have the input field so there is no need for the second if condition just use else block in the first condition
$('select').change(function () {
var val = $(this).val();
if (val == '3') {
$('#INPUT').remove();
} else if (!$('#INPUT').length) {
$('.valuta').before('<div id="INPUT"><input type="text" class="price"></div>');
}
})
Demo: Fiddle

jQuery to validate a form (check for atleast 10 characters and certain value)

On my webpage I have a form where a user enters information for their article. Right now I use jQuery to check if the entered values are not empty, if they are I show an error message.
Current validation
//Story Form
$('.error').hide(); //Hide error message initially
$(".button").click(function() { //On button click
$('.error').hide();
var title = $("input#sc_title").val();
if (title == "") { //if title is empty
$("label#title_error").show(); //show error
$("input#sc_title").focus(); //focus on title field
return false;
}
});
Right now it only checks if title == "". How would I edit the code to also check if there are at least 10 characters entered e.g. if title is empty and less than 10 chars are entered, show an error?
if user puts 20 space character in the title field in that case title.length returns 20 and it satisfy true condition so you can use jquery trim also
if ($.trim(title) == "" || $.trim(title).length < 10) {
$("label#title_error").show(); //show error
$("input#sc_title").focus(); //focus on title field
return false;
}
this should do it:
if(title.length < 10)
here's your code edited:
$('.error').hide(); //Hide error message initially
$(".button").click(function() { //On button click
$('.error').hide();
if ($("input#sc_title").val().length < 10) {
$("label#title_error").show(); //show error
$("input#sc_title").focus(); //focus on title field
return false;
}
});
Change your if to check the length instead - this will check anything less than 10 - ie empty too :
if (title.length < 10) {
// Show error message
}
Really simple example : http://jsfiddle.net/GFjpg/1/

JQuery Validation Problem

I doing a field validation using jquery to check if it is empty. If it is I want to display a message and then refocus on the field so the user can enter some data. Code:
$('#fieldId').blur(function() {
var fieldValue = $(this).val();
if(fieldValue == null || fieldValue.length == 0) {
$(this).addClass('error');
// show error message
$('#errorDivId')
.text('You must enter a value in this field')
.show();
$(this).focus();
}
else {
if ($(this).is('.error')) {
$(this.removeClass('error');
$('#errorDivId').hide()
}
}
});
It sort of works but it moves the cursor to the next field and not the one I refocused on.
You can try this:
$('#fieldId').blur(function(evt) {
var fieldValue = $(this).val();
if(fieldValue == null || fieldValue.length == 0) {
$(this).addClass('error');
// show error message
$('#errorDivId')
.text('You must enter a value in this field')
.show();
this.focus();
evt.preventDefault();
}
else {
if ($(this).is('.error')) {
$(this.removeClass('error');
$('#errorDivId').hide()
}
}
});
However that may not completely solve the problem, as some browsers might be confused. As an alternative, wrap your "focus" call up as a timeout and run it after the current event finishes:
var self = this;
setTimeout(function() { self.focus(); }, 1);
It's kind-of a hack but it should also work.
edit — #Gus is right about which "focus()" to call
The blur event is triggered during a focus change (as the control you are validating loses focus). This could cause weird behaviour if you try to alter the focus while it is already changing. Instead of blur, try attaching the validation to the change event.
Also, there's no need to call the jQuery version of focus: $(this).focus(), you can just call this.focus().
$('#fieldId').change(function() {
var fieldValue = $(this).val();
if(fieldValue == null || fieldValue.length == 0) {
$(this).addClass('error');
// show error message
$('#errorDivId').text('You must enter a value in this field').show();
this.focus();
} else {
if ($(this).is('.error')) {
$(this).removeClass('error');
$('#errorDivId').hide()
}
}
});

how to include multiple if statement conditions in jQuery

I have an if statement that needs to look like this:
UPDATE
$("input#textbox").keypress(function(e){
key==e.which;
if($("input#textbox").length <=7 && (key===13 || $("div#search-button").click())){
/////SOME FUNCTION////
};
});
I'm trying to execute the "SOME FUNCTION" area only if the input length is <=7 and either the enter button is pressed or the "search" button is clicked.
Furthermore, I want to combine these 2 different function initiators so that they execute the same function but don't know how to do it:
$("input#textbox").keypress(function(e){
FUNCTION A
};
AND
$("div#search-button").click(function(){
FUNCTION A
};
EDIT:
This is what you have to do:
I am assuming that you want the text length and not number of textboxes.
You want to execute FunctionA when enter is pressed on textbox or search button is clicked:
$("input#textbox").keypress(function(e){
key==e.which;
if (key === 13) // if enter is pressed
{
if ("#textbox").val().length >= 7) //if textbox has more than 7 characters
{
functionA();
}
}
});
$("div#search-button").click(function(){ functionA();});
HTH
This is how I would do it:
$("#search-button").click(function(){
$("#textbox").keypress(function(e,clicked){
(clicked || e.which===13) && $(this).val().length < 8 && functionA();
}).trigger("keypress",[true]);
});
function functionA(){
alert("hey!");
}

Categories

Resources