Live form validation using javascript - javascript

I want to do live form validation using javascript like if I type number in text field it should give error message instantly or vice versa.How can I achieve this.

You need to start by detecting changes in the input entries. You can do that easily by using the oninput event (read more here).
Looking at that example:
<script>
window.addEventListener('input', function (e) {
console.log("input event detected! coming from this element:", e.target);
}, false);
</script>
<input placeholder="type here and see console.">
Each time your input value changes, an event will be fired an received in that listener.
In your case, you need to add an event listener for each of the inputs and, instead of doing a console.log in the handler function, just call a generic function that will validate all the values for all the inputs in the form.
For the validations, you can look at multiple libraries, like validate.js or jQuery Validation. Also, take a look at validator.js.

Related

jQuery validate not binding to keyup events [duplicate]

This question already has answers here:
onkeyup and onfocusout is not working in jQuery Validate
(1 answer)
jQuery validate plugin: validate on blur() by default
(1 answer)
Closed 5 years ago.
I'm making a "contact me" page, with jQuery validation. My main content box is reloaded with ajax to change content when the user clicks on a new page. The problem I'm having now is to bind an event handler for the validate function. what I got now is
$(document).ready(function(){
$('body').bind('focus focusout keyup', function() {
$('#contact_me').validate({
But it's not working like intended. I have to start typing, then click out of the input field and then click on it again before it starts to validate the input field value. I want it to validate on focus, focusout and keyup. I think the problem is with the event handler somehow. Any suggestions?
Here is a JSfiddle with the script: https://jsfiddle.net/z6h9d028/4/
I can see now that the eventhandler is not the problem. When i type in a input field its not validating the value until i click out of the box. After the first validation i works on keyup as well. How can i get i to work on keyup stright away?
Edit 2:
Updated fiddle: https://jsfiddle.net/z6h9d028/7/
It's almost working now! I just need to get all the error messages to show when clicking the submit button. And to find a way to show the error message when you type one character and then remove it if the input field is required (it does show it if you type once, then remove, type again and remove. but not the first time)
You don't need to set your own event listeners, or at least if you do, you shouldn't be using them on the .validate() method (see alternative method below).
Remove the whole $('body').bind() part, and add the following to your validate settings object:
onkeyup: function(element) {
$(element).valid();
// As sparky mentions, this could cause infinite loops, should be this:
// this.element(element);
},
This should be better too, as it may give you some extra freedom as to how you handle the onkeyup events, such as adding a setTimeout if you don't want it to be instantaneous.
Fiddle: https://jsfiddle.net/z6h9d028/5/
Inside the onkeyup, you can also call $('#contact_me').valid(), which will revalidate the whole form, although that may not be your desired outcome.
Edit: Sparky also helpfully mentioned that jquery-validate by default does allow keyup events, but it only does so after the first submit: jQuery validate plugin: validate on blur() by default
An alternative way would be to set the details of your validation as you currently are, without the onkeyup function, then set your own listeners and run $(element).valid():
$('#contact_me').validate({
rules: {
// ...
}
});
$('input').on('focus focusout keyup', function () {
$(this).valid();
});
Edit regarding your other issues:
Your errorPlacement function is doing some funky things. How it decides what is the next sibling or not seems to be working incorrectly. Also, you're adding the error HTML divs into your DOM manually, but they are actually generated by the plugin. So really, you're creating both, then trying to show them, kinda over-riding the plugin, kinda not, and the whole thing is going into a frenzy.
The solution is, I reckon, to remove those error divs, remove that errorPlacement function, and then modify the CSS selectors to get any id ending with "-error", which is what the plugin generates. So [id$='-error'] instead of .error_message
https://jsfiddle.net/z6h9d028/8/

Is there a way to check a form when it actually changes?

I realize there is a onchange event attribute for the purpose of detecting a change in a form and performing a certain javascript function. However, this requires the user to click outside of the form field, making it very similar to onblur.
Is there actually a way to perform a function when a form changes, without having to wait for the user to click outside of the form?
I know you can use JavaScript timeouts to check the form every few milliseconds, but I would prefer a solution without them. Also, I am not limited to just form elements; I'm okay with using contenteditable divs.
I don't think a code is necessary, but I can add a sample code of what I mean if needed.
jQuery has powerful functions that deliver what you're after, but if you just need to run a simple script, you can use functions such as onkeydown and onkeypress.
<input type="text" onkeydown="myFunction()">
Sources:
W3 Schools - OnKeyPress
W3 Schools - OnKeyDown
If I were to do this myself I would listen to the change event on the inputs of a form. Personally I think this would be easier for you to do using jQuery.
$('form input, form select').change(function() {
console.log('form has been changed');
});
If you want to ensure you catch when any type of input in your form changes (ie. checkbox, select lists, radio buttons etc and not just text) then you could use the following snippet I put together (assuming you're using jQuery)
$('form input[type=text]').keyup(formUpdated);
$('form input[type!=text], form select').change(formUpdated);
function formUpdated() {
alert('input changed');
}
You can see it in action here.
This is all just a nice way of removing the need for this:
<input type="text" onkeyup="formUpdated();">
<select onchange="formUpdated();">
</select>
<input type="radio" onchange="formUpdated();">
<input type="checkbox" onchange="formUpdated();">

When user types into HTML <input/> where is that data stored?

I am writing a jQuery script that needs to work with an existing unchangeable plugin. This plugin listens for text being typed into an <input type='text'> and then processes the result. I can't alter this. My script is setting the text of the input via $('#display).val(newValue); as a jQueryUI Slider is dragged. I need the plugin to recognize this value as being typed by the user so that it processes the newValue as the slider is dragged.
Can anyone point me in the write direction for this?
You probably need to 'trigger' the keyup (or keypressed?) event so that the event handler is fired.
Here is one (slightly dirty) way to do it:
var e = jQuery.Event("keyup");
e.which = 50; // # Some key code value
$("#display").trigger(e);
Note that the plugin may be looking for particular keys, and I may have guessed the event wrong.
The more sophisticated way to do it would be to track down the plugin's event handler, and then invoke it directly. FireBug may help you find it by step-through debugging. Otherwise, you can use jquery to start inspecting the input's event handlers.
var events = $('#display').data("events");
jQuery.each(events, function(key, handlerObj) {
console.log(handlerObj); // alert(handlerObj);
});
Once you've found the relevant handler, you can invoke it directly.
HTH
You have to put an Onchange listener to the text field and trigger the necessary function to listen to onchange values of the user. eg:
function func(){.....put your logic.....}
If you are looking at reading value from a text field on changing a slider, then you have to put the necessary function on the slider control.

Submit form when contents of MVC3 Html.TextBoxFor changes

This should be fairly easy but I've tried a few things with no luck.
I have a series of Html.TextBoxFor fields on a page, each inside their own Ajax.BeginRouteForm. Next to each box I have a submit button, and this, when clicked, performs the Ajax update as desired.
I'd like to automate this so that when the user changes a value in a field (the onchange event) the form is submitted the same way it currently using using the submit button.
I tried using the htmlattributes to assign a JavaScript function to the onchange event (as shown below) and this causes the form to submit, but it redirects the page instead of working in the ajax fashion (as opposed to clicking the submit button which works correctly).
#(Html.TextBoxFor(model => answer.Value, new { onchange = "document.forms[" + answer.AnswerID + "].submit()" }));
(fortunately my answer.AnswerID is numeric and matches up with the numeric position of the appropriate form in the forms collection; I was referencing them by name but Razor (or something) was htmlencoding my JavaScript code...)
My only guess is that I'm breaking something by attaching code directly to the onchange event, but I'm at a loss as to the "right" way to hook into that event chain.
If you're willing to use JQuery, it's very simple to do:
http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
Calling submit() on a form will ignore any submit event handlers, as seen here. You can either
call the event handler directly, or
call click() on the submit button for the form.
The former works best if you use onsubmit and return false instead of using the event argument to the callback, because otherwise you need to pass another messy object or something.

Selectively enable enter key in HTML textarea (javascript)

I am using openjs.com's shortcut handling (1)
to disable the enter key in my html forms. However, inside of textareas in those forms I want enter key to emit the normal CR-LF pair (because that's what users expect).
At the moment assuming I have a form/input structure as follows:
<form id="f1">
<fieldset>
<input>
<textarea id="f2"> ...
The following scripts are run:
shortcut.add('Return', function () { /*empty*/ },
{ 'type':'keydown', 'disable_in_input':false,'propagate':true,
'target':document.getElementById('f1')});"
This effectively disables the enter key.
I have tried using the following code to re-enable it for the textarea:
shortcut.add(\"Enter\", function() { }, {'type':'keydown','propagate':false,
'disable_in_input':false, 'target':document.getElementById('f2') } );
But that does not work. What is the order of propagation of this event? Should it bubble up from the textarea or bubble down from the form element?
It doesn't look like this library was really meant to be used this way. I would hazard a guess that adding any shortcut disables the browser's handling of it entirely, no matter what you do afterwards.
What are you actually trying to accomplish? If you just want to prevent the form from being submitted, you could add a submit event listener for the whole form that calls event.preventDefault().

Categories