When an input gets focus, I want to pop up a warning if the input is invalid. The message is in the observable.
So given this code, how do I find the observable bound to it.
$(document).on("focus", "input.invalid", function(){
console.log("ahaaaa!");
//your code here
//dig out observable from this and find the message
//create element with class invalid-message and place it next to this
}).on("blur", function(){
$(".invalid-message").remove();
});
I'm using knockout validation and I only want to show the error message when the field has focus. Other suggestions are welcome.
EDIT: When I'm using dataFor:
$(document).on("focus", "input.invalid", function(){
console.log(this);
console.log(ko.dataFor(this));
...
I get this in the console:
The underlined observable is the one I'm after.
EDIT2: I'm working around it like this:
$(document).on("focus", "input.invalid", function(){
var fieldName = $(this).attr("name");
var errorMessage = ko.dataFor(this)[fieldName].error;
...
You can use:
ko.dataFor(this)
which will give you the observable of the current element.
For more details, look here: Using unobtrusive event handlers