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/
Related
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!
}
}
});
I try to validate the textbox by mouse out in jquery, my code is running by any mouse out means it shows Enter valid Email. several times, any time that I click outside the textbox.
This is my code:
$(document).ready(function() {
$('#EmailAddress').focusout(function() {
var email = $.trim($('#EmailAddress').val() || '');
if (email.length == 0 || !emailregx.test(email)) {
$(this).addClass('ChangetoYellow');
$(this).after('<div class="Required">Enter valid Email.</div>');
return false;
} else {
$(this).next(".Required").remove();
$(this).removeClass('ChangetoYellow');
return true;
}
});
});
my code is not working when it is outside the document.ready.
This is what I get when I run by each time I click:
$(this).after('<div class="Required">Enter valid Email.</div>');
this will add a new after every focus out of the input box.
Instead have a placeholder div below the text box.
<div id="emailErrorMsg"></div>
and do
$('#emailErrorMsg').html('Enter valid Email.');
this will also let you add more error messages.
Remove the div before you add one to prevent repeats.
$(document).ready(function() {
$('#EmailAddress').focusout(function() {
var email = $.trim($('#EmailAddress').val() || '');
if (email.length == 0 || !emailregx.test(email)) {
$(this).addClass('ChangetoYellow');
if($(this).next().hasClass('Required'))
$(this).next().remove();
$(this).after('<div class="Required">Enter valid Email.</div>');
return false;
} else {
$(this).next(".Required").remove();
$(this).removeClass('ChangetoYellow');
return true;
}
});
});
I have implemented some code to validate text box and insert error div after the element if entered value is not valid.
I hope below code will solve your problem
$(document).ready(function() {
$('#EmailAddress').focusout(function() {
var email = $.trim($('#EmailAddress').val() || '');
if (email.length == 0 || !emailregx.test(email)) {
var errorLabel = errorsFor(this);
$(this).addClass('ChangetoYellow');
if(errorLabel.length > 0){
$(errorLabel).show();
}
else {
$(this).after('<div for='+ this.name +' class="required">Enter valid Email.</div>');
}
return false;
} else {
$(this).next(".required").remove();
$(this).removeClass('ChangetoYellow');
return true;
}
});
function errorsFor( element ) {
var name = idOrName(element);
return $('.required').filter(function() {
return $(this).attr("for") === name;
});
};
function idOrName( element ) {
return element.name ? element.name : element.id || element.name;
};
});
Test sample code
Try This one first remove previous error messages and add it.
JS
$(document).ready(function() {
$('#EmailAddress').focusout(function() {
var email = $.trim($('#EmailAddress').val() || '');
if (email.length == 0 || !emailregx.test(email)) {
$(this).parent().find(".Required").remove();
$(this).addClass('ChangetoYellow');
$(this).after('<div class="Required">Enter valid Email.</div>');
return false;
} else {
$(this).parent().find(".Required").remove();
$(this).removeClass('ChangetoYellow');
return true;
}
});
});
For Simple Example Fiddle (if u want add the regular expression and test it) -
http://jsbin.com/pujemay/edit?html,js,output
I have tried to write js for my html form. js is working fine with the logically. But if logic fails,I mean if any condition fails it reloads the page,which I don't want. I am providing the code. Please point me out the mistake in js if any.
window.onload = function() {
document.getElementById('submitlink').onclick = function() {
var bflag = document.addpro.brandflag;
var brand = document.addpro.brand1.value;
var cflag = document.addpro.catflag;
var cat = document.addpro.cat1.value;
var color1 = document.addpro.color1.value;
var color2 = document.addpro.color2.value;
if(cb_validation(bflag,brand))
{
if(cb_validation(cflag,cat))
{
if(colorcheck(color1,color2))
{
document.getElementById('addproform1').submit();
return false;
}
}
}
}
function cb_validation(flag,field)
{
if(flag[0].checked)
{
if(field==0)
{
alert('Please Select Both Brand And Category');
field.focus();
return false;
}
else
return true;
}
else
return true;
}
function colorcheck(c1,c2)
{
if((c1==0) && (c2==0))
{
alert('Please Select Both Colours');
document.addpro.color1.focus();
return false;
}
else if((c1==0))
{
alert('Please Select 1st Colour');
document.addpro.color1.focus();
return false;
}
else if((c2==0))
{
alert('Please Select 2nd Colour');
document.addpro.color2.focus();
return false;
}
else
return true;
}
}
I am rookie in js. Please also tell me if I have done any mistake.
return false is what keeps the page from reloading. Right now it is inside your final color check condition. If you never want the page to reload it needs to be after your first cb_validation condition.
Submit() is causing the page refresh which is in below line
document.getElementById('addproform1').submit();
Also both your function is returning true becauseyou are returning true in else block. Hope this points you to right direction....
Good luck....
My code basically adds a class error if field is invalid and if the field is valid, the error class is removed and form is submitted normally.
I am having trouble figuring out two small bugs for the form validation code I created.
Bugs listed below:
1) If you enter the correct content within one field, and click submit, the length of the error class does not update on first submit click. It takes two submit clicks for the length to update. (view console.log)
2) If you change the content of the input field and click submit (all works well, error class is removed) BUT if you decide to delete your updated text & leave the field blank, the error class does not get re-applied.
Would be great if I can get some assistance solving this.
Please let me know if anything is unclear.
Thanks in advance:
JSFIDDLE
$('form.requiredFields').submit(function(e) {
var req = $(this).find('.req'),
validateEmail = function(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
};
req.each(function() {
var $this = $(this),
defaultVal = $this.prop('defaultValue'); //cache default val
//checks for validation errors
if ( ( $this.hasClass('email') && !validateEmail( $this.val() ) ) ||
( defaultVal === $this.val() || $this.val() === '' || $this.val().length < 3 )
)
{
$this.addClass('error');
} else {
$this.removeClass('error req');
}
});
console.log(req.length);
if ( req.length === 0 ) {
return true;
} else {
return false;
}
});
Like dc5 said for #2 don't remove the req class.
And for #1 - You're looking for errors (.req) before it is removed.
See this working fiddle. It is an example how your code work but maybe you can find a cleaner solution.
$('form.requiredFields').submit(function(e) {
var req = $(this).find('.req'), errorCheck = 0,
validateEmail = function(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
};
req.each(function() {
var $this = $(this),
defaultVal = $this.prop('defaultValue'); //cache default val
//checks for validation errors
if ( ( $this.hasClass('email') && !validateEmail( $this.val() ) ) ||
( defaultVal === $this.val() || $this.val() === '' || $this.val().length < 3 )
)
{
$this.addClass('error');
} else {
$this.removeClass('error');
}
});
errorCheck = $(this).find('.error');
console.log(errorCheck.length);
if ( errorCheck.length === 0 ) {
return true;
} else {
return false;
}
});
for #2, You are moving the 'req' class as well as the 'error' class when clearing the error. The next time through the call, the input is no longer found through your selector $(this).find('.req')
For #1 - I don't understand the problem as you have described it.
I made it easier for you, actually your code is a mess,
here is a fiddle:
Jsfiddle validate Demo
CODE:
$('#submit_form').click(function() {
var flag = 0;
var count = 0,
total = $(".req").length;
var validateEmail = function(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
$('.req').each(function(){
count++;
if($(this).attr('id')=='email') {
if(!validateEmail($(this).val())){ $(this).addClass('error'); flag = 1; }
else { $(this).removeClass('error'); } }
if($(this).attr('id')=='name') {
if($(this).val().length < 3){ $(this).addClass('error'); flag = 1; }
else { $(this).removeClass('error'); } }
if($(this).attr('id')=='com') {
if($(this).val().length < 3&&$(this).val()!=''){ $(this).addClass('error'); flag = 1; }
else { $(this).removeClass('error'); } }
if ( total==count&&flag<1) { alert('submit'); }
});
});
Validation rules:
name - must be bigger then 2.
email - true on pattern match function.
comment - if typed, must be bigger the 2 chars (just to understand how can it be done).
If this example is not clear or you need more help don't hesitate... I'm bored.
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 ^^