Javascript onfocus event - javascript-events

I have textbox whose value if entered needs to be validated using some regularexpression
I need to validate the value as user is entering the data.
Which is suitable event can be used for this ? some sample example of using onfocus event on textbox will be helpful

Use onKeypress or onKeyup.
Beginners often think that onChange will do what you want, but that only fires when the input loses the focus.
OnFocus is irrelevant - that is when the box first gets the focus, not when the user types.

Typically you would do this when the text input loses focus, so it would be using the blur event. The reason is that many inputs aren't valid until some sufficient number of characters has been typed. It can be very annoying to the user to put up a validation error while they are still typing a valid string. For example, when doing email validation, the input cannot be valid until the # sign has been entered. Note that you'd also need to validate when the form is submitted to catch the case where the field has never had focus.
Using jQuery it might look like:
$('.klass').blur( function() {
if (!$(this).val().match( /your-regular-expression/ )) {
$(this).next('.validation-message').show();
return false; // keep focus on field
}
return true;
});
This assumes some HTML like
<input type="text" class="klass" name="myInput" />
<span class="validation-message" style="display: none;">This is not valid</span>

To stop the user from writing invalid characters, or to validate the fields as he types you can use .onkeypress.
document.getElementById(fieldId).onkeypress = onkeypressHandler;
var onkeypressHandler = function (event) {
var eKey = event.charCode;
var str = String.fromCharCode(eKey);
var pattern = /[^0-9]/g;
var strTmp = str.replace(pattern, "");
if (str!== strTmp) {
return false;
}
return true;
}
In this example the only valid characters are numbers, if the pressed key is not a number then the function will return false and the key will be ignored.
Also validate a field after the user is done typing you can use .onchange
document.getElementById(fieldId).onchange= onChangeHandler;

Related

<ui:inputText> keyup returns incorrect value (one less)

I am using in one of the lightning components and I am using it to filter a table. But when I'm trying to get its value in JS controller with the keyup function, it's giving one less value than actual.
This question has been already asked for HTML here , But for HTML, we have a solution that we can use onkeyup instead of keyup.
But in salesforce lightning, we don't have any onkeyup function for ui:inputText Source ,
So how to solve this issue?
I have already tried keypress, keyup, keydown.
All are giving one less value than actual one
Component :
<ui:inputText aura:id="search-phrase" class="slds-input" keyup="{!c.filterTable}" placeholder="Search Table" />
JS Controller :
, filterTable :function(component, event, helper) {
var dynamicVal = component.find("search-phrase");
var week = dynamicVal.get("v.value") ;
alert((week+'').toLowerCase());
var searchTerm = (week+'').toLowerCase() ;
$('#userTbl tbody tr').each(function(){
var lineStr = $(this).text().toLowerCase();
if(lineStr.indexOf(searchTerm) === -1){
$(this).hide();
}else{
$(this).show();
}
});
}
I found it's solution.
Just need to add updateOn="keyup" in <ui:inputText>
So new one will become :
<ui:inputText aura:id="search-phrase" class="slds-input" updateOn="keyup" keyup="{!c.filterTable}" placeholder="Search Table" />
Include updateOn attribute to ui:inputtext control. By default, it is mapped to change event so you will get only the exact value when the change event fires. updateOn="eventName"
event details : enter link description here

How to trigger DataBinding Validation for all Controls?

I have an OpenUI5 form consisting of a number of Inputcontrols. These Inputcontrols are bound to a model using the OpenUI5 DataBinding as described in the documentation.
For example:
new sap.m.Input({
value: {
path: "/Position/Bezeichnung",
type: new sap.ui.model.type.String(null, {
minLength: 1,
maxLength: 128
})
}
})
As in the example above I'm using constraints on the stringlength.
When a User changes the Value of the Input, the Validation is triggered and according to the Validationresult one of the functions descripted here is called.
In these functions I'm setting the ValueState of the control like this:
setupValidation: function() {
var oCore = sap.ui.getCore();
oCore.attachValidationError(function (oEvent) {
oEvent.getParameter("element").setValueState(sap.ui.core.ValueState.Error);
});
oCore.attachValidationSuccess(function (oEvent) {
oEvent.getParameter("element").setValueState(sap.ui.core.ValueState.None);
});
oCore.attachFormatError(function (oEvent) {
oEvent.getParameter("element").setValueState(sap.ui.core.ValueState.Error);
});
oCore.attachParseError(function (oEvent) {
oEvent.getParameter("element").setValueState(sap.ui.core.ValueState.Error);
});
},
Let's assume the bound model variable is initial.
I'm loading the view, the property value is parsed and displayed as empty.
The Validationerror/Parseerror method is not called although the constraints are not met.
This seems to be standard behaviour of OpenUI5. Only changes in the Control will be a validated.
Now let's assume I've a submit button and the Value of the Inputcontrol is still empty. When the user hits the submit button I'd like to trigger the DataBinding Validation for all childcontrols of my view. This would validate the above mentioned input and would result in an errorstate.
My question is: How can I trigger the databinding validation for all childcontrols of my view?
There is another question on SO where the poster asks for a way to define required fields. The proposed solution is to call getValue() on the control and validate the value manually. I think this is kind of cumbersome as formating and constraint information and logic is already present.
I suggest looking into field groups.
An example here in the UI5 docs
Field Groups allow you to assign group IDs to the input fields. Then you can call all of the input fields at once. You can set the name property and required property on each <Input> separately in your view, allowing you to handle some logic when you perform validation.
You can call this.getView().getControlsByFieldGroupId("fieldGroupId"), which will return an array of the input controls. Then you can loop through the controls, pass them through your logic, and use setValueState() to show the results.
Or, you can assign the validateFieldGroup event on the parent container, which is usually a form, but can be anything like a <VBox> that contains the controls. When the users focus moves out of the field group, the event is fired. You can then use the event handler in your controller to perform the validation.
In your case, I would assign a press event to your submit button, and in the handler, call the field group by ID and loop through the controls. At the end of your function, check to see if all fields are validated before continuing.
View
<Input name="email" required="true" value="{/user/email}" fieldGroupIds="fgUser"/>
<Input name="firstName" required="false" value="{/user/firstName"} fieldGroupIds="fgUser"/>
<Button text="Submit" press="onSubmit"/>
Controller
onSubmit: function() {
var aControls = this.getView().getControlsByFieldGroupId("fgUser");
aControls.forEach(function(oControl) {
if (oControl.getRequired()) {
//do validation
oControl.setValueState("Error");
oControl.setValueStateText("Required Field");
}
if (oControl.getName() === "firstName") {
//do validation
oControl.setValueState("Success");
}
});
var bValidated = aControls.every(function(oControl) {
return oControl.getValueState() === "Success";
});
if (bValidated) {
//do submit
}
}
The concept goes like this.
Use custom types while binding, to define validations. Validation
rules go inside these custom types (in the method 'validateValue').
When Submit is pressed, loop through the control hierarchy and
validate each control in your view. (By calling 'validateValue'
method of the Custom Type).
Validator (https://github.com/qualiture/ui5-validator ) uses this concept and it is a small library to make your life easy. Its main advantage is that it recursively traverses through the control library.
Using Message Manager (using sap.ui.get.core().getMessageManager() ) is the way to show the validation messages on the UI control.
Triggering data binding validations is not possible. Rather for empty fields that are having required property true you can do a work around using jQuery.
Please refer my answer to this same problem at Checking required fields

what is right jQuery event for a input field with timepicker

I have a input field that is formatted with the data-format HH:mm:ss PP. When the timepicker is clicked the focus on the input field don't appear that's why I couldn't use onblur event. What i want is like keydown or keyup event but it seems doesn't work in my case because focus is out in the input field so what jQuery event should i used?
change seems to work fine:
Fiddle
$("#datepicker").datepicker()
.on("change", function () {
console.log("Changed");
});
Example is with datepicker(), I'm not sure what your timepicker implementation is as it's not in the jquery(ui) api. But it should work as well.
Edit: after looking at the datetimepicker you are using, based on the DOM I'm seeing as a result of datetimepicker() - I think this should work for you:
Fiddle
$('#datetimepicker1').closest(".well").next(".bootstrap-datetimepicker-widget").on("click", "*", function () {
console.log("Changed");
});
Just make sure this is after your datetimepicker() call. Note that this will be triggered on any click within your calendar/time picker even if it is a click on something that is already selected (no change).
If you want, you could store the last value of your input and then check that if it changed before continuing with this event callback function. If it did change, be sure to update the variable you are holding the "last value" in... something like this.
If possible, the best option would actually be to modify datetimepicker()'s js to call a function or trigger an event from the same place it updates the text input. Looking at the code:
set: function () {
var formatted = "";
if (!this._unset) formatted = this.formatDate(this._date);
if (!this.isInput) {
if (this.component) {
var input = this.$element.find("input");
input.val(formatted);
input.trigger("change"); // added this
this._resetMaskPos(input)
}
this.$element.data("date", formatted)
} else {
this.$element.val(formatted);
this.$element.trigger("change"); //added this
this._resetMaskPos(this.$element)
}
},
With the two lines I added above, you should be able to rely on a change event bound to the input element.

Jquery validation question, how to validate the empty field?

I am using Jquery validation plugin for my form validation.
I just use this one as sample.
http://jquery.bassistance.de/validate/demo/milk/
there's one problem. first time you load the form. click on the first field, dont put anything there, then click on the "tab" button to move to the next input field, the error message is not showing, but that field is labeled as "required".
is there a way to fix it? or that is how it supposed to be it.
According to the Validate plugin's reference for onblur:
If nothing is entered, all rules are skipped, except when the field was already marked as invalid.
But you can force it to validate yourself by binding the inputs' blur event:
$("#signupform input").blur(function() {
$(this.form).validate().element(this);
});
$('#id).filter(function() { return $(this).val() == ""; });
You can get fields with empty value and ca validate.
You can also add class and can get all empty fields of that class i.e.
$('.className).filter(function() {
return $(this).val() == "";
});

Jquery form :input

Is there a "simple" way to ensure that ALL the inputs in a form have "an entry". I need/want to disable the submit button unless all inputs have a value they are all input type=text. I assume it is something like for each but I am not very good at the for each in JQuery. Possible problem is that the inputs are "dynamically" generated by sortables? All I need to know is is there a value in every input field. The "real" validation is done elsewhere.
So is it something like:
$j('#button').click(function (){
each(function(:input){
//check the length in here?
});
});
Is this post useful http://forum.jquery.com/topic/enable-disable-submit-depending-on-filled-out-form?
$("#button").click(function(event) {
var valid = true;
$(":input").each(function(index) {
if ($(this).val().length == 0) {
valid = false;
}
});
if (!valid) {
event.preventDefault();
}
});
Should work.
First part grabs the element with id of button, then assigns a function to the onclick event. Second part grabs all input fields, and run a function on each of them. Then you get the length of the value for each.
The $(this) works since the function is being applied to a specific element on the page, and will always get you the current element.

Resources