Plain JavaScript Custom Validation Run Validation on keyup - javascript

I wrote a custom JavaScript validator that needs to run on every keyup event that is attached to ever input and runs the vacillator() for every input field.
Problem is that it only works on load.
I want to to work on every key-up event.
Here is a jsfiddle https://jsfiddle.net/vo1npqdx/717/
function display_error(elem, message) {
elem.insertAdjacentHTML('afterend', "<label class='js-error' style='color:red;' >" + message + "</label>");
}
function check_error(elem) {
error_label = elem.nextElementSibling
if (error_label && error_label.classList.contains('js-error')) {
return true;
}
}
function add_error(elem,message) {
if (!check_error(elem)){
display_error(elem, message)
}
}
function delete_error(elem) {
if (check_error(elem)){
elem.nextElementSibling.remove();
}
}
function validateForm(elem) {
alert("Checking if form is vaild")
// If input type == text
if (elem.getAttribute("type") == 'text') {
//alert("elemcent is text")
maxlength = elem.getAttribute("maxlength")
minlength = elem.getAttribute("minlength")
data_error = elem.getAttribute("data-error")
// if has attribute maxlegnth
if (minlength) {
// if value is under min length
if (elem.value.length < parseInt(minlength)) {
// add errors
add_error(elem, data_error)
//alert("above min length")
} else {
// Delete
//alert("delere errror")
delete_error(elem)
}
}
}
// if input type == number
if (elem.getAttribute("type") == 'number') {
//alert("element is text")
max = elem.getAttribute("max")
min = elem.getAttribute("min")
data_error = elem.getAttribute("data-error")
// if has attribute maxlegnth
if (min) {
// if value is under min length
if (elem.value < parseInt(min)) {
// add errors
add_error(elem, data_error)
//alert("Belove Min Number")
}
else if(elem.value > parseInt(max)){
// add errors
add_error(elem, data_error)
//alert("above Max number")
}
else {
// Delete
//alert("delere errror")
delete_error(elem)
}
}
}
}
// Desired Result
// if keyup
// for input in inputs:
// someFunc(input) that makes input tags red
var inputs = document.getElementsByClassName('form-control');
for(var i=0;i<inputs.length;i++){
elem = inputs[i]
elem.addEventListener('keyup', validateForm(elem))
}

You are calling your event handler straight away. It needs to be wrapped with a function. So this:
elem.addEventListener('keyup', validateForm(elem))
should be:
elem.addEventListener('keyup', function(event) {
// do something with event
validateForm(this);
});

Related

How come multiple classes not targeting in textarea?

I want to use validate_empty_field function for both classes .log and .log2. For some reason only .log is targeted but .log2 textarea is not. When you click on text area, if empty, both should show validation error if the other one is empty or if both empty.
$(document).ready(function() {
$('#field-warning-message').hide();
$('#dob-warning-message').hide();
var empty_field_error = false;
var dob_error = false;
// $('input[type=text], textarea')
$('.log, .log2').focusout(function () {
validate_empty_field();
});
function validate_empty_field() {
var field = $('.log, .log2, textarea').val();
// var first_name_regex = /^[a-zA-Z ]{3,15}$/;
if (field.length == '') {
$('#field-warning-message').show();
$('#field-warning-message').html("Please fill out form!");
empty_field_error = true;
} else if (field.length < 1) {
$('#field-warning-message').show();
$('#field-warning-message').html("Please fill out form!");
empty_field_error = true;
} else {
$('#field-warning-message').hide();
}
}
$('.verify-form').submit(function () {
empty_field_error = false;
dob_error = false;
validate_empty_field();
if ((empty_field_error == false) && (dob_error == false)) {
return true;
} else {
return false;
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="log"></textarea>
<textarea class="log2"></textarea>
<div id="field-warning-message"></div>
You should pass the event to the handler so you have access to the target
Change your event listener line to this:
$('.log1, .log2').focusout(validate_empty_field);
and then accept an argument in validate_empty_field
function validate_empty_field(ev){
var field = $(ev.target).val();
if(!field.length){
//textarea is empty!
}else{
//textarea is not empty!
}
}
in fact, you could do all of this in an anonymous function you have already created, and use the on method to stick with JQuery best practices:
$('.log1, .log2').on('focusout', function(){
if(!$(this).val().length){
//this textarea is empty
}else{
//this textarea is not empty!
}
});
And yes, adding one class to all textareas and swapping out .log1, .log2 for that class would be a better option.
EDIT: Final option should cover all requirements.
$('.log').on('focusout', function(){
$('.log').each(function(){
if(!$(this).val().length){
//this textarea is empty
}else{
//this textarea is not empty!
}
}
});

jquery form validation without click -> when ok show div

is it possible to do this automatically. mean when i type text and click on the second textfield autocheck the first one. then when both ok show the div2 and so on.
here is some code
var step1 = function() {
var first = $("#f_name").val();
var last = $("#l_name").val();
var error = false;
if (first == "") {
$("#f_name").next().text("*ErrorMsg");
error = true;
} else {
$("#f_name").next().text("");
}
if (last == "") {
$("#l_name").next().text("*ErrorMsg");
error = true;
} else {
$("#l_name").next().text("");
}
if (error == false) {
$("#send").submit();
$('#div1').show('slow');
} else {
returnfalse;
}
}
var step2 = function() {
var email1 = $("#e_mail").val();
var adress1 = $("#adress").val();
var error2 = false;
if (email1 == "") {
$("#e_mail").next().text("*ErrorMsg");
error2 = true;
} else {
$("#e_mail").next().text("");
}
if (adress1 == "") {
$("#adress").next().text("*ErrorMsg");
error2 = true;
} else {
$("#adress").next().text("");
}
if (error2 == false) {
$("#send2").submit();
$('#div2').show('slow');
} else {
returnfalse;
}
}
$(document).ready(function() {
$('#div1').hide();
$('#div2').hide();
$("#send").click(step1);
$("#send2").click(step2);
});
hope anyone can help me. and sorry for my bad english :)
greatings
The way that I would do it is:
Assign a variable, something like numSteps and set its initial value to 1
onFocus and onBlur, run a function that steps through each field, based on numSteps
If any fields are empty (or however you want to validate them), set error = true
if !error numSteps++
Make all elements up to numSteps visible
Hope this helps
Very crude example, but demonstrates what I was referring to:
http://jsfiddle.net/aSRaN/

Return through all functions

Is it possible to return through multiple functions?
I have a jQuery on click function with a $.each loop in it. In the $.each loop I test for various conditions, and if not met display an alert message and then return. Here is a cut down version of my code:
$(document).on('click', '.add-to-basket, #add-to-basket', function(e) {
var data = {
id: $(this).data('id'),
quantity: 1
};
if($('#quant').length > 0) {
data.quantity = $('#quant').val();
}
var i = 0;
var j = 0;
if($('.product-option').length > 0) {
$('.product-option').each(function(index, element) {
if($(this).is('select')) {
//check to see if this is a required select, and return if a selection has not been made.
if($(this).data("force") == 1 && $(this).val() == 0) {
AlertDialogue($(this).data("title") + " requires a selection before you can add this product to your basket.", "Required Option");
return;
}
data.opts[i++] = $(this).val();
} else if($(this).is('input[type="checkbox"]:checked')) {
data.opts[i++] = $(this).val();
//check to see if this is a required group of checkboxes, and if so at least one has been checked. If not return.
} else if($(this).is('input[type="checkbox"]')) {
if($(this).data("force") == 1 && $('input[name="' + $(this).prop("name") + '"]:checked').length == 0) {
AlertDialogue($(this).data("title") + " requires at least one option to be checked before you can add this product to your basket.", "Required Option");
return;
}
} else if($(this).is('input[type="radio"]:checked')) {
data.opts[i++] = $(this).val();
} else if($(this).is('textarea')) {
//Check to see if this is a required textarea, and if so make sure there is some text in it.
if($(this).data("force") == 1 && $.trim($(this).val()).length == 0) {
AlertDialogue($(this).data("title") + " requires text before you can add this product to your basket.", "Required Option");
return;
}
if($(this).val().length > 0) {
data.text[j].id = $(this).data("id");
data.text[j++].val = $(this).val();
}
}
});
}
//submit product to the cart
});
However the return will only break that loop of the $.each loop, and start the next loop. I would like to not only break the $.each loop, but return from the on click function entirely.
Is this possible?
If so, how can I achieve this?
To exit from $.each you should return false
To exit from event handler function you should use return
As per your requirement you can do little like below,
var break = false;
$('.product-option').each(function(index, element) {
// rest of code
if(condition) {
break = true;
return false; // this will break out of each loop
}
});
if(break) {
return; // return from event handler if break == true;
}
// rest of code
Check out the docs for jQuery.each():
We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same
as a continue statement in a for loop; it will skip immediately to
the next iteration.
Essentially, use return false; instead of just return;.

JavaScript force an OnChange in Maximo

I'm currently working on a Bookmarklet for Maximo, which is a Java EE application, and I need to populate a few input boxes.
Generally when a use inputs data into the box they click a button that gives them a popup and they search for the value to be added to the script. Or they can type the name and hit tab/enter and it turns it to capital letters and does a few things in the background (not sure what it does exactly).
I currently use
Javascript: $('mx1354').value = "KHBRARR"; $('mx1354').ov= "KHBRARR";
But it does not work like I need it to. It set's the input box to the value needed, but it doesn't run the background functions so when I hit the save button it doesn't recognize it as any changes and discards what I put into the box.
How could I simulate a tab/enter button has been pressed?
So far I've tried to call the onchange, focus/blur, and click functions (Not 100% sure if I called them correctly).
The dojo library is part of the application, so I'm not sure if I can use one if it's feature or if jQuery would cause a conflict.
P.S. This needs to run in IE.
The OnChange Function:
function tb_(event)
{
event = (event) ? event : ((window.event) ? window.event : "");
if(DESIGNMODE)
return;
var ro = this.readOnly;
var exc=(this.getAttribute("exc")=="1");
switch(event.type)
{
case "mousedown":
if(getFocusId()==this.id)
this.setAttribute("stoptcclick","true");
break;
case "mouseup":
if (isIE() && !hasFocus(this))
{
this.focus();
}
if (isBidiEnabled)
{
adjustCaret(event, this); // bidi-hcg-AS
}
break;
case "blur":
input_onblur(event,this);
if (isBidiEnabled) // bidi-hcg-SC
input_bidi_onblur(event, this);
break;
case "change":
if(!ro)
input_changed(event,this);
break;
case "click":
if(overError(event,this))
showFieldError(event,this,true);
var liclick=this.getAttribute("liclick");
var li=this.getAttribute("li");
if(li!="" && liclick=="1")
{
frontEndEvent(getElement(li),'click');
}
if(this.getAttribute("stoptcclick")=="true")
{
event.cancelBubble=true;
}
this.setAttribute("stoptcclick","false");
break;
case "focus":
input_onfocus(event,this);
if (isBidiEnabled) // bidi-hcg-SC
input_bidi_onfocus(event, this);
this.select();
break;
case "keydown":
this.setAttribute("keydown","true");
if(!ro)
{
if(isBidiEnabled)
processBackspaceDelete(event,this); // bidi-hcg-AS
if(hasKeyCode(event, 'KEYCODE_DELETE') || hasKeyCode(event, 'KEYCODE_BACKSPACE'))
{
getHiddenForm().elements.namedItem("changedcomponentvalue").value = this.value;
}
if((hasKeyCode(event, 'KEYCODE_TAB') || hasKeyCode(event, 'KEYCODE_ESC')))
{
var taMatch = dojo.attr(this, "ta_match");
if(taMatch) {
if(taMatch.toLowerCase().indexOf(this.value.toLowerCase()) == 0)
{
console.log("tamatch="+taMatch);
this.value = taMatch;
input_keydown(event, this);
dojo.attr(this, {"prekeyvalue" : ""});
input_forceChanged(this);
inputchanged = false;
return; // don't want to do input_keydown again so preKeyValue will work
}
}
if(this.getAttribute("PopupType"))
{
var popup = dijit.byId(dojohelper.getPopupId(this));
if (popup)
{
dojohelper.closePickerPopup(popup);
if(hasKeyCode(event, 'KEYCODE_ESC'))
{
if (event.preventDefault)
{
event.preventDefault();
}
else
{
event.returnValue = false;
}
return;
}
}
}
}
input_keydown(event,this);
datespin(event,this);
}
else if(hasKeyCode(event,'KEYCODE_ENTER') || (hasKeyCode(event,'KEYCODE_DOWN_ARROW') && this.getAttribute("liclick")))
{
var lbId = this.getAttribute("li");
frontEndEvent(getElement(lbId), 'click');
}
else if(hasKeyCode(event,KEYCODE_BACKSPACE))
{
event.cancelBubble=true;
event.returnValue=false;
}
break;
case "keypress":
if(!ro)
{
if(event.ctrlKey==false && hasKeyCode(event,'KEYCODE_ENTER'))
{
var db = this.getAttribute("db");
if(db!="")
{
sendClick(db);
}
}
}
break;
case "keyup":
var keyDown = this.getAttribute("keydown");
this.setAttribute("keydown","false");
if(event.ctrlKey && hasKeyCode(event,'KEYCODE_SPACEBAR'))
{
if(showFieldError(event,this,true))
{
return;
}
else
{
menus.typeAhead(this,0);
}
}
if(!ro)
{
if(isBidiEnabled)
processBidiKeys(event,this); // bidi-hcg-AS
numericcheck(event,this);
var min = this.getAttribute("min");
var max = this.getAttribute("max");
if(min && max && min!="NONE" || max!="NONE")
{
if(min!="NONE" && parseInt(this.value)<parseInt(min))
{
this.value=min;
getHiddenForm().elements.namedItem("changedcomponentvalue").value = this.value;
this.select();
return false;
}
if(max!="NONE" && parseInt(this.value)>parseInt(max))
{
this.value=max;
getHiddenForm().elements.namedItem("changedcomponentvalue").value = this.value;
this.select();
return false;
}
}
var defaultButton = false;
if(event.ctrlKey==false && hasKeyCode(event,'KEYCODE_ENTER'))
{
var db = this.getAttribute("db");
if(db!="")
{
defaultButton=true;
}
}
input_changed(event,this);
}
else
{
setFocusId(event,this);
}
if(showFieldHelp(event, this))
{
return;
}
if(keyDown=="true" && hasKeyCode(event, 'KEYCODE_ENTER') && !event.ctrlKey && !event.altKey)
{
menus.typeAhead(this,0);
return;
}
if(!hasKeyCode(event, 'KEYCODE_ENTER|KEYCODE_SHIFT|KEYCODE_CTRL|KEYCODE_ESC|KEYCODE_ALT|KEYCODE_TAB|KEYCODE_END|KEYCODE_HOME|KEYCODE_RIGHT_ARROW|KEYCODE_LEFT_ARROW')
&& !event.ctrlKey && !event.altKey)
{
menus.typeAhead(this,0);
}
break;
case "mousemove":
overError(event,this);
break;
case "cut":
case "paste":
if(!ro)
{
var fldInfo = this.getAttribute("fldInfo");
if(fldInfo)
{
fldInfo = dojo.fromJson(fldInfo);
if(!fldInfo.query || fldInfo.query!=true)
{
setButtonEnabled(saveButton,true);
}
}
window.setTimeout("inputchanged=true;input_forceChanged(dojo.byId('"+this.id+"'));", 20);
}
break;
}
}
After some time I found that in order to make a change to the page via JavaScript you need to submit a hidden form so it can verify on the back-end.
Here is the code I used to change the value of Input fields.
cc : function(e,v){
e.focus(); //Get focus of the element
e.value = v; //Change the value
e.onchange(); //Call the onchange event
e.blur(); //Unfocus the element
console.log("TITLE === "+e.title);
if(e.title.indexOf(v) != -1) {
return true; //The value partially matches the requested value. No need to update
} else {
//Generate an hidden form and submit it to update the page with the new value
var hiddenForm = getHiddenForm();
var inputs = hiddenForm.elements;
inputs.namedItem("changedcomponentid").value = e.id;
inputs.namedItem("changedcomponentvalue").value = v;
inputs.namedItem("event").value = "X"; //Send a Dummy Event so the script see's its invalid and sets the right Event
submitHidden();
}
//Value isn't set to the required value so pass false
return false;
}
run this
input_changed(null,document.getElementById('IDHERE'));
In maximo 7.5 i built a custom lookup
when i click the colored hyperlink java script is called to update the values back to parent form values or updated but on save the value or not updated
function riskmatrix_setvalue(callerId, lookupId, value,bgrColor,targetid){
if (document.getElementById(callerId).readOnly){
sendEvent('selectrecord', lookupId);
return;
}
textBoxCaller = document.getElementById(callerId);
//dojo.byId(callerId).setAttribute("value", value);
//dojo.byId(callerId).setAttribute("changed", true);
//dojohelper.input_changed_value(dojo.byId(callerId),value);
//textBoxCaller.style.background = bgrColor;
//var hiddenForm = getHiddenForm();
//if(!hiddenForm)
// return;
//var inputs = hiddenForm.elements;
//inputs.namedItem("event").value = "setvalue";
//inputs.namedItem("targetid").value = dojo.byId(callerId).id;
//inputs.namedItem("value").value = value;
//sendXHRFromHiddenForm();
textBoxCaller.focus(); //Get focus of the element
textBoxCaller.value = value; //Change the value
textBoxCaller.onchange(); //Call the onchange event
textBoxCaller.blur(); //Unfocus the element
//Generate an hidden form and submit it to update the page with the new value
var hiddenForm = getHiddenForm();
var inputs = hiddenForm.elements;
inputs.namedItem("changedcomponentid").value = textBoxCaller.id;
inputs.namedItem("changedcomponentvalue").value = value;
inputs.namedItem("event").value = "X"; //Send a Dummy Event so the script see's its invalid and sets the right Event
submitHidden();
sendEvent("dialogclose",lookupId);
}
Description
I changed a bit #Steven10172's perfect solution and made it into a Javascript re-usable function.
Made this into a separate answer since my edits to the original answer where i added this were refused :)
I also had to change the line e.onchange() to e.onchange(e) because otherwise the textbox handler (tb_(eventOrComponent) function) would throw TypeError: textbox.getAttribute is not a function.
Code
var setFakeValue = function(e,v){
console.log("Changing value for element:", e, "\nNew value:", v);
e.focus(); //Get focus of the element
e.value = v; //Change the value
e.onchange(e); //Call the onchange event
e.blur(); //Unfocus the element
if(e.title.indexOf(v) != -1) {
return true; //The value partially matches the requested value. No need to update
}
else {
//Generate an hidden form and submit it to update the page with the new value
var hiddenForm = getHiddenForm();
var inputs = hiddenForm.elements;
inputs.namedItem("changedcomponentid").value = e.id;
inputs.namedItem("changedcomponentvalue").value = v;
inputs.namedItem("event").value = "X"; //Send a Dummy Event so the script see's its invalid and sets the right Event
submitHidden();
}
//Value isn't set to the required value so pass false
return false;
}
Usage
setFakeValue(html_element, new_value);
Fun fact
I spent a lot of time searching for a solution to programmatically change an <input> value in Maximo... At some point i got really frustrated, gave up and started to think it just wasn't possible...
Some time ago i tried to search with no expectations at all and after some time i found the solution... Here...
Now... As you can see this is literally just a total copy of StackOverflow, including questions and solutions (marking the upvotes with plain text lol), but in Chinese... This got me curious and after a little search i found this post on StackOverflow..
High five to Chrome built-in webpage translator that let understand something on that page ^^

How do I call a sub-function from within a function object in javascript

I've checked the related questions on stack overflow, but can't seem to find an answer to my predicament. I'm trying to use a plugin for javascript (Tag it! - Tag Editor) and I need to find a way to call one of its functions "create_choice()" EDIT: at some point after it has been initiated. Is there a way after calling :
$tagit = $("#mytags").tagit();
that I can then call something like
$tagit.create_choice('test123');
Here is a link for the example :
http://levycarneiro.com/projects/tag-it/example.html
Below is the code from the plugin if it is any help
(function($) {
$.fn.tagit = function(options) {
var el = this;
const BACKSPACE = 8;
const ENTER = 13;
const SPACE = 32;
const COMMA = 44;
// add the tagit CSS class.
el.addClass("tagit");
// create the input field.
var html_input_field = "<li class=\"tagit-new\"><input class=\"tagit-input\" type=\"text\" /></li>\n";
el.html (html_input_field);
tag_input = el.children(".tagit-new").children(".tagit-input");
$(this).click(function(e){
if (e.target.tagName == 'A') {
// Removes a tag when the little 'x' is clicked.
// Event is binded to the UL, otherwise a new tag (LI > A) wouldn't have this event attached to it.
$(e.target).parent().remove();
}
else {
// Sets the focus() to the input field, if the user clicks anywhere inside the UL.
// This is needed because the input field needs to be of a small size.
tag_input.focus();
}
});
tag_input.keypress(function(event){
if (event.which == BACKSPACE) {
if (tag_input.val() == "") {
// When backspace is pressed, the last tag is deleted.
$(el).children(".tagit-choice:last").remove();
}
}
// Comma/Space/Enter are all valid delimiters for new tags.
else if (event.which == COMMA || event.which == SPACE || event.which == ENTER) {
event.preventDefault();
var typed = tag_input.val();
typed = typed.replace(/,+$/,"");
typed = typed.trim();
if (typed != "") {
if (is_new (typed)) {
create_choice (typed);
}
// Cleaning the input.
tag_input.val("");
}
}
});
tag_input.autocomplete({
source: options.availableTags,
select: function(event,ui){
if (is_new (ui.item.value)) {
create_choice (ui.item.value);
}
// Cleaning the input.
tag_input.val("");
// Preventing the tag input to be update with the chosen value.
return false;
}
});
function is_new (value){
var is_new = true;
this.tag_input.parents("ul").children(".tagit-choice").each(function(i){
n = $(this).children("input").val();
if (value == n) {
is_new = false;
}
})
return is_new;
}
function create_choice (value){
var el = "";
el = "<li class=\"tagit-choice\">\n";
el += value + "\n";
el += "<a class=\"close\">x</a>\n";
el += "<input type=\"hidden\" style=\"display:none;\" value=\""+value+"\" name=\"item[tags][]\">\n";
el += "</li>\n";
var li_search_tags = this.tag_input.parent();
$(el).insertBefore (li_search_tags);
this.tag_input.val("");
}
};
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
};
})(jQuery);
I've created a working example at http://jsfiddle.net/nickywaites/DnkBt/ but it does require making changes to the plugin.
Change
$.fn.tagit = function(options) { ...
to
$.fn.tagit = function(options,callback) { ...
Add
if (callback && typeof callback == 'function') {
callback();
}
after
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
};
Now you can call a function of your choice right after the tagit call:
$tagit = $("#mytags").tagit(yourOptions, function(){
alert('hi')!
});
You can try to add
return this;
right after the function create_choice block. tagit will return itself and you can call make_choice or any function contained in .fn.tagit

Categories

Resources