As described in ScriptUI reference, there are 2 ways to implement changing listener on EditText:
editText.onChanging = function() {
...
}
editText.addEventListener('changing', function(event) {
...
})
However, the function is triggered after an edit to EditText.text has been made, denying opportunity to obtain old text value as a fallback option is new value is undesired. I'm looking for something like this:
editText.onChanging = function(oldValue) {
var newValue = this.text
if (!isCorrect(newValue)) {
this.text = oldValue
}
}
editText boxes have an onActivate callback which is triggered when the element gets focus. If you store the current text value of the editText at that point, it can be returned to its original state if the new value doesn't validate.
Note that it might be worth thinking about the UX here—if you enter an invalid value, and the value just reverts, you might not realise that it has done so. For the user this could be very confusing: it looks like I enter a value, but nothing happens. It might be better to throw an error, such as a dialog, or disable other controls, e.g. grey out the "do the things" button if the parameters are incorrect.
I am attempting to use a class method to clear a form that may have been previously submitted using vanilla Javascript. While the functionality works outside of a class, inside has been a nightmare to figure out, and using .reset() returns the previously submitted values. Ideally I'd be able to call this methods inside of other methods to keep things DRY as clearing the form is used quite a lot.
The result of what I have below is no console errors, and otherwise expected functionality, just the previously submitted data still populating the form. Console logging the elements (input) in the clearForm() method returns the expected DOM element.
There seems to be some sort of knowledge gap on my part and I'd like to fill it.
Currently I have this for clearing:
[class and constructor]...
/* in my constructor this._form = document.querySelector(target); where target is a param
containing the target element's id or class */
clearForm() {
[...this._form.elements].forEach((input) => {
if (input.type == "checkbox") {
input.checked = false
input.setAttribute("value", false);
return;
}
input.value = "";
input.setAttribute("value", "");
});
}
And I put it to use in other methods such as:
async populateForm(id) {
try {
await this.clearForm();
[additional functionality]...
} catch (e) {
...
}
}
Thanks for any help!
I have a problem with the javascript code I am trying to work with. I am trying to call a function to set an event handler and within that event handler also remove it when the event is called. In this particular instance I am trying to ADD an event handler whenever I want input, then a callback is passed to the function and the code is run when the input is ready. Also at this stage I try to remove it so the callback doesn't get triggered more than once, but there seems to be a problem with this. Here is the code:
this.validateInput = function(NaN, callback) {
// Wait for the user to click submit or press
// enter, then if the input is a valid number
// return true. If it is not valid return false
$(document).keydown(function(e) {
// If the enter key is pressed, if the box is focused and if
if (e.which == 13 && $("#inputBox").is(":focus")) {
// Print the user's input regardless of whether it is a
// number or not.
var newOutput = $("#inputBox").val()
$("#output").append(newOutput + "<br>");
// If the user wants the input to be a number then
// the program checks if the input is not numerical.
if (NaN && !isNaN($("#inputBox").val())) {
// Get input from screen
var newInput = $("#inputBox").val();
// Remove this handler
this.removeKeyhandler();
// Call the code passed to the function
callback(newInput);
// Return from the function.
return;
// This checks if the user wants non-number input
// and runs the following code IF the input is not numerical
} else if (!NaN && isNaN($("#inputBox").val())) {
// Get input from screen
var newInput = $("#inputBox").val();
// Remove this handler
this.removeKeyhandler();
// Call the code passed to the function
callback(newInput);
// Return from the function
return;
}
}
});
}
For reference, #inputBox is an input box, #output is the <div> I am trying to output to, and removeKeyHandler() simply contains the code $(document).off("keydown", document);. If you want to see the full file/project, it is here.
The only thing that seems not to be working is the event handler not removing, it keeps going as many times as you add input. If you download the project and open up index.html you should see what I mean.
I see your problem.. your 'this' you refer to in your code is not in the right scope..
simply do this:
function display() {
var ref = this;
}
Now replace these:
this.removeKeyhandler();
with this:
ref.removeKeyhandler();
Also in your removing function change it to this:
$(document).off("keydown");
good luck!
I'm trying to use jQuery to build a home-made validator. I think I found a limitation in jQuery: When assigning a jQuery value to a json variable, then using jQuery to add more DOM elements to the current page that fit the variable's query, there doesn't seem to be a way to access those DOM elements added to the page which fit the json variable's query.
Please consider the following code:
var add_form = {
$name_label: $("#add-form Label[for='Name']"),
$name: $("#add-form #Name"),
$description_label: $("#add-form Label[for='Description']"),
$description: $("#add-form #Description"),
$submit_button: $("#add-form input#Add"),
$errors: $("#add-form .error"),
error_marker: "<span class='error'> *</span>"
}
function ValidateForm() {
var isValid = true;
add_form.$errors.remove();
if (add_form.$name.val().length < 1 ) {
add_form.$name_label.after(add_form.error_marker);
isValid = false;
}
if (add_form.$description.val().length < 1) {
add_form.$description_label.after(add_form.error_marker);
isValid = false;
}
return isValid
}
$(function(){
add_form.$submit_button.live("click", function(e){
e.preventDefault();
if(ValidateForm())
{
//ajax form submission...
}
});
})
An example is availible here: http://jsfiddle.net/Macxj/3/
First, I make a json variable to represent the html add form. Then, I make a function to validate the form. Last, I bind the click event of the form's submit button to validating the form.
Notice that I'm using the jQuery after() method to put a span containing an '*' after every invalid field label in the form. Also notice that I'm clearing the asterisks of the previous submission attempt from the form before re-validating it (this is what fails).
Apparently, the call to add_form.$errors.remove(); doesn't work because the $errors variable only points to the DOM elements that matched its query when it was created. At that point in time, none of the labels were suffixed with error_marker variable.
Thus, the jQuery variable doesn't recognize the matching elements of it's query when trying to remove them because they didn't exist when the variable was first assigned. It would be nice if a jQuery variable HAD AN eval() METHOD that would re-evaluate its containing query to see if any new DOM elements matched it. But alas...
Any suggestions?
Thanks in advance!
You are correct that a jQuery object is not "live" – that is, the set of elements in the jQuery object is not dynamically updated. (This is a good thing.)
If you really want to update an arbitrary jQuery object, you can get the selector used to create the object from .selector:
var els = $('#form input');
els.selector // '#form input'
So you could do els = $(els.selector); to re-query the DOM.
Note, however, that if you modified the collection after the initial selector (functions like add, filter, children, etc.), or if the jQuery object was created without using a selector (by passing a DOMElement), then .selector will be pretty much useless, since the selector will be empty, incorrect, or even potentially invalid.
Better is to re-structure your code in such a way that you aren't holding on to a stale jQuery object; the other answers make some good suggestions.
Also, please make sure you're validating input server-side too!
For the objects that are going to be changing, instead of making the JSON object reference a static value, make it a function:
$errors: function() { return $("#add-form .error"); },
since it's a function, it will re-evaluate the error fields every time you call add_form.$errors().
Your approach to the problem has got many structural problems:
Avoid using global variables
There may not always be just one form on the page that you are validating. What if one day you will decide that you will have several forms. Your add_form variable is a global variable and therefore would be conflicting.
Do not use the submit button click event for detecting form submissions.
What if a form is submitted by a js call like $("form").submit(); or by the enter key?
Store the selectors instead of the DOM objects if you are not certain that the objects already exist at the creation time of the configuration object.
.live is deprecated. Use .on instead.
It is 3. that will solve your actual problem, but I strongly recommend addressing all 4 issues.
For 2, the best place to attach the validator is not on the submit button, but on submit event of the form. Something like this:
$("#add-form").submit(function(event) {
event.preventDefault();
if (validateForm(this))
$.ajax({
url: $(this).attr("action"),
data: $(this).serialize(),
//ETC
});
});
Note how the form is now also much easier to access. Your configuration object no longer needs to store a reference to the submit button.
Your configuration object could now be simplified to be something like this:
{
name_label: "Label[for='Name']",
name: "#Name",
description_label: "Label[for='Description']",
description: "#Description",
errors: ".error",
error_marker: "<span class='error'> *</span>"
}
Within validateForm, you can use these selector as follows:
var $name_label = $(configuration.name_label, this); //Finds the label within the current form.
Now, to allow different configuration parameters for each form use something like this:
function enableValidation(form, configuration) {
$.extend(configuration, {
//Default configuration parameters here.
});
function validateForm(form) {
//Your original function here with modifications.
}
$(form).submit(funciton(e) {
if (!validateForm(this))
e.preventDefault();
});
}
function enableAjax(form) {
$(form).submit(function(e){
if (!e.isDefaultPrevented()) {
e.preventDefault();
$.ajax(...);
}
});
}
$(function() {
enableValidation("#add-form", {/*specialized config parameters here*/});
enableAjax("#add-form");
});
I'm working on a validation project and I currently have it set up where my inputs are listed as objects. I currently have this code to setup and run the events:
setup method and functions used
function setup(obj) {
obj.getElement().onfocus = function() {startVal(obj)}
obj.getElement().onblur = function() {endVal(obj)}
}
function startVal(obj) {
obj.getElement().onkeyup = validate(obj)
}
function endVal(obj) {
obj.getElement().onkeyup = ""
}
Take note to how I have it where the onkeyup event should set when the object is receives focus, However when I activate the input it acts like I tagged the validate() function directly to the onfocus and it only validates when I initially focus the input.
edit the reason I have it set up this way is so that I don't have every single one of my form elements validating each time I launch an onkeyup event(which would be a lot since forms usually involve a decent amount of typing). I got it to work by simply attaching the validate() function to the onkeyup event. I just would prefer limit it this way so the there's no unnecessary processing.
Can you not set events with other events or is there something more specific that I'm doing wrong?
Any help is appreciated!
Here is some additional information that might help:
getElement Method
function getElement() {
return document.getElementById(this.id)
}
setEvents function
function setEvents() {
firstName.setup(firstName)
}
You are calling validate directly. Unless it is returning a function, it won't work (maybe you should have read my other answer more thoroughly ;)). I think you want:
obj.getElement().onkeyup = function() {validate(obj)};
And as I stated in my comment, there is no reason to add or remove the event handler on focus. The keyup event is only raised if the element receives input, so not when other elements receive input.