jQuery if hasClass hide element on blur - javascript

I have a form that displays error message in a HTML label when users don't enter valid data into form fields. The label displays beneath the form field onBlur and stays there until data is entered into the form field. I would like the label to only show when users click back into the form field instead of showing persistently. Below is the script where I'm attempting to hide the error label as a user tabs out of the form field. I figured I'd worry about making it appear again once I can effectively hide it.
Here is the HTML:
<div class="field">
<input type="text" name="firstname" id="firstname" class="error has-error">
<label for="firstname" class="error">First Name is required.</label>
</div>
And the script
<script type="text/javascript">
if($('.fieldset #firstname').hasClass('error')) {
$(this).blur($('.field label')).hide();
}
</script>

You need to pass a function into the .blur() function as a callback, something like this:
$(".fieldset #firstname").blur(function(evt) {
if($(this).hasClass('error')) {
$(".field label", $(this).parent()).hide();
}
});
Note that I am doing a .field label selector within the context of the parent() of the $(this). $(this) will refer to #firstname, so if you get the parent, you can easily select within that node tree and not accidentally get some other .field label in your page.

You need to put the if condition inside the on blur handler.
$('.fieldset #firstname').blur(function(){
if ($(this).hasClass('error')){
$('.field label')).hide();
}
})

Related

Jquery: function on .blur() of form, not elements

I've searched around the community, and see there is a lot of guidance on how to make on(blur(function)) or on(focusout(function)) for form elements, but I have not seen a blur element kick in when a form itself loses focus. I want that kind of behavior that relies on two fields being updated before submit, but if I valid on a field onblur() it will give a false error, because the user didn't have the chance to update the other field.
Here is the code of my basic concept:
$(document).ready(function(){
$("form").blur(function(){
alert("This form has lost its focus.");
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<form>
Enter your name: <input type="text">
Enter your age: <input type="text">
</form>
<p>Write something in the input field, and then click outside the field to lose focus (blur).</p>
</body>
</html>
If I have the .ready statement focus on "input" instead, it works fine, but is totally unresponsive when I want the document to monitor the overall form instead. Any Ideas? Thank you!
The event you are looking for is not blur it's focusout. If we bind a focusout event to the form itself, the handler will be called whenever focus is lost on any element inside the form.
Also note that the tabindex attributes I added to the various elements have nothing to do with this code working. They were added because an erroneous comment was made on your post claiming that forms can't be focused.
From here tabindex
The tabindex global attribute indicates if its element can be focused, and if/where it participates in sequential keyboard navigation (usually with the Tab key, hence the name). It accepts an integer as a value, with different results depending on the integer's value:
A negative value (usually tabindex="-1") means that the element should be focusable, but should not be reachable via sequential keyboard navigation. Mostly useful to create accessible widgets with JavaScript.
As you can see any element can receive focus. It's just that only some elements will receive focus by default (anchors, inputs, buttons, etc...) without setting a tabindex for them. In the example below, if you click on the "Enter your name" text you will see the form itself gain focus. You can then tab to the inputs, then the div and finally the span. All of them receiving focus in turn.
$('#theForm').on('focusout', function(e) {
// do what you want/need to do here
console.log('Form has lost focus');
});
#theDiv {
height: 50px;
width: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="theForm" tabindex="1">
Enter your name: <input type="text" tabindex="2">
Enter your age: <input type="text" tabindex="3">
</form>
<div id="theDiv" tabindex="4"></div>
<span tabindex="5">Some Text</span>
<p>Write something in the input field, and then click outside the field to lose focus (blur).</p>

Binding a jAlert popup content to html content

I'm attempting to use jAlert to show a popup dialog with an input box. When clicking "OK" I want to grab the value from this input box to send to the server. I'm using jQuery to pull the content off a div which includes the input field. Problem is that when I use jQuery to try and get the contents of that input field, it doesn't work - it comes back as empty.
HTML as follows:
<div id="test">
<input type="text" id="def" />
</div>
JS as follows:
$.jAlert({ 'content' : $("#test").html()});
...and to try and access using jQuery...
$("#def").val();
I can get around it by force updating the field using a keyup listener, but it seems really clunky...
<input type="text" id="def" onkeyup="$('#def').val($(this).val())" />
After doing this I can access the content of the 'def' field. Is there a more elegant solution?

How do I validate all form fields in a div using parsley.js?

I have a div with a form field and a button that I would like to have parsley validate all the form fields in that div that have the proper data-validate attribute. I need it to work no matter how many form fields are in the div. So it needs to work on inputs, textareas, and select fields.
HTML:
<div id="parsley-div">
<div class="form-group">
<label for="city">City</label>
<input id="city-test" type="text" class="form-control" data-parsley-required data-parsley-required-message="Please enter a city name.">
</div>
<button class="btn btn-primary">Save Changes</button>
</div>
JS:
$('#parsley-div').find('button').click(function(){
$('#parsley-div').parsley().validate();
});
Unfortunately, this isn't working. I noticed it works if there is a form tag around the form fields, but I need it to be a div. I have created a JSFiddle that shows both cases: https://jsfiddle.net/8rkxzjx1/2/
How can I have parsley validate all form fields with data-parsley attributes within a specified div? If possible, please edit the JSFiddle to show the correct implementation. Thank you.
Edit:
I figured out this works, but it doesn't feel very efficient:
$('#parsley-div').find( "input, textarea, select" ).each(function (index, value) {
$(this).parsley().validate();
});
You could use
$('#parsley-div :input:not(:button)').parsley().validate();
See fiddle.
Edit
Looks like the above code won't work. The following can be used as the OP suggested.
$('#parsley-div :input:not(:button)').each(function (index, value) {
$(this).parsley().validate();
});
Here is the new fiddle.
Or the content can be wrapped in a form element and then be validated as follows:
$("#parsley-div").wrap("<form id='parsley-form'></form>");
$('#parsley-div').find('button').click(function() {
$('#parsley-form').parsley().validate();
});
Or since the OP does not want to have a form element in Dom, content can be wrapped in a form element and then the form can be removed after validation.
$('#parsley-div').find('button').click(function() {
$("#parsley-div").wrap("<form id='parsley-form'></form>");
$('#parsley-form').parsley().validate();
$("#parsley-div").unwrap();
});
Links to fiddle-wrap and fiddle-wrap-unwrap.

Select all text in textbox when label is clicked

I am using label for attribute for input elements in my website that will help blind users.
Currently when user click on label, the corresponding input is getting activated. That means if there is textbox for name, then cursor will
go in the start of textbox.
For example, if name in textbox is "John", then on click label, cursor will enter in textbox and will show before "John".
But what I want is that it should select "John". That means text of textbox should be selected.
Can anyone help me how I can implement this?
My code is shown below:
<div class="editor-label">
<label for="ContactName">*Name</label>
</div>
<div class="editor-field">
<div>
<input id="ContactName" maxLength="40" name="ContactName" type="text" value="John" />
</div>
</div>
I am unsure if you can achieve this by just using html/css, so it's very likely that you need to use a JS lib, such as jQuery.
By using jQuery, you can use the select() method when the label is clicked, using something like this;
$(function() {
$('label').click(function() {
var id = $(this).attr('for');
$('#'+id).select();
});
});
A working example can be found here: http://jsfiddle.net/sf3bgwxr/

Input validation on bootstrap html form with javascript addevent listener

i'm having difficulties with validating the value of a text box element in the html with the addeventlistener in my javascript. It does not properly validate my input in the following ways :
1)Showing "field is empty" even when I have values in that textbox.
2)Only validates when i click submit. <-- (how do i perform the validation as the user clicks out of the text box? )
The following is the relevant html code (with bootstrap classes):
<div class ="col-lg-8">
<div class="form-group">
<label for="inputfirstName" class="col-sm-2 control-label">First Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputfirstName"
placeholder="Enter First Name" />
</div>
</div>
The following is the relevant javascript code to valdiate that the First name text box field is not empty and if it is it should return a custom validation error
window.addEventListener('load',init);
function init()
{
var firstname = document.getElementById("inputfirstName");
firstname.addEventListener('onmouseclick',validateFirstname(firstname));
}
function validateFirstname(e){
var checker = e.value;
if (checker == ""){
e.setCustomValidity("This field must not be blank !");
}
}
I am not really sure, when you want to validate your input.
Currently, you are listening to the user clicking into your textbox and performing the validation in that very moment.
However, since you are only adding the validation error with your call to e.setCustomValidity it won't display until you post your form. This is by design of setCustomValidity. This is explained in more details here: How to force a html5 form validation without submitting it via jQuery
To validate your textbox after the user entered his text, you would use the input and change events. Input fires when the user types something into your textbox, change after the user leaves the textbox. To trigger the validation regardless of the user ever focusing on that field, you also have to set your input to "required". Then to display your message instead of the standard required message of HTML5 you also have to add the invalid event to your event listeners. You can find a more refined answer here with the complete code on how to accomplish this here: Set custom HTML5 required field validation message
<input type="text" class="form-control" id="inputfirstName"
placeholder="Enter First Name" required="required"/>
window.addEventListener('load',init);
function init()
{
var firstname = document.getElementById("inputfirstName");
firstname.addEventListener('input',validateFirstname(firstname));
firstname.addEventListener('change',validateFirstname(firstname));+
}
function validateFirstname(e){
var checker = e.value;
if (checker == ""){
e.setCustomValidity("This field must not be blank !");
}
else{
e.setCustomValidity("");
}
}

Categories

Resources