Clear error message (jquery) on input field focus - javascript

function customAlert(inputID,msg){
var div = $(".errorPopup");
div.css({"display":"block"});
$("#"+inputID).addClass("CO_form_alert").parent().addClass("alertRed");
if (div.length == 0) {
div = $("<div class='ErrorPopup' onclick='$(this).hide();'></div>");
$("body").prepend(div);
}
div.html(msg)
}
I am using the above jquery to hijack my form's javascript validation and error handling. It's working well, except I need to clear the error messaging and styling once the user clicks back into the field to correct it.
EDIT:
based on answers below, got it working - but I need to remove the focus on the field for IE (it already does this in firefox) -
<!--Jquery function to override JS alert with DOM layer alert message-->
function customAlert(){
var args = arguments;
if(args.length > 1) {
// check that custom alert was called with at least two arguments
var msg = args[0];
$("li").removeClass("alertRed");
$("input").removeClass("CO_form_alert");
$("select").removeClass("CO_form_alert");
var div = $(".errorPopup");
div.css({"display":"block"});
if (div.length == 0) {
div = $("<div class='errorPopup' onclick='$(this).hide();'></div>");
$("body").prepend(div);
}
div.html(msg);
for(var i = 1; i < args.length; i++) {
var inputID = args[i];
$("#"+inputID).addClass("CO_form_alert").parent().addClass("alertRed");
$("#"+inputID).focus(function(){
$(this).unbind('focus'); // remove this handler
$('.errorPopup').hide(); // hide error popup
});
}
}
}

$(":input").keypress(function(event) {
$(".ErrorPopup").html("");
});

Hide the error popup div on the input's focus event:
$('#' + inputID).focus(function() { $('.ErrorPopup').hide(); });

Try this:
function customAlert(inputID,msg){
var div = $(".errorPopup");
div.css({"display":"block"});
$("#"+inputID).addClass("CO_form_alert").parent().addClass("alertRed");
if (div.length == 0) {
div = $("<div class='errorPopup' onclick='$(this).hide();'></div>");
$("body").prepend(div);
}
div.html(msg);
$("#"+inputID).focus(function(){
$(this).unbind('focus'); // remove this handler
$(this).removeClass("CO_form_alert")
.parent().removeClass("alertRed"); // undo changes
$('.errorPopup').hide(); // hide error popup
});
}

Related

Event is not firing on button located in a table in an iframe (no jQuery)

I have to show a spinner upon clicking an add button in a HTML form waiting for the Ajax to load the content in a select box. The select box is located in an iframe. I have set up a simplified reproduction of what I am trying to achieve in jsfiddle. There are 2 tables, one for Research Project and one for
Primary research group. The tables contain an add icon. I want to fire a console.log upon clicking the add button of just the Research Project.
I have to use the name of the parent container in the selector as there are no other non-textual identifiers in the user interface. I want to just plain JavaScript, but if jQuery or some other framework offers a solution, then I will go for that.
var formFrame = document.getElementById('form_iframe');
formFrame.src = "/catorarn/tabLe/24/show/";
var formFrameDoc = formFrame.contentDocument;
formFrame.onload = function() {
//click event on add button
var btn = getElementByXpath("//i[contains(#class,'fa fa-plus-circle') and ../../td/span[text()='Research project']]", formFrame);
console.log('showSpinner === btn is ' + btn);
addEvent(btn, 'click', function(e){
console.log('inside event listener');
e.stopPropagation();
});
};
function getElementByXpath(path, iframe) {
console.log('iframe is ' + iframe );
var doc = iframe.contentDocument;
return doc.evaluate(path, doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}
function addEvent(elem, evnt, funct){
if (elem.attachEvent){
console.log('addEvent === attachEvent');
return elem.attachEvent('on' + evnt, funct);
} else {
console.log('addEvent === addEventListener == elem is ' + elem );
return elem.addEventListener(evnt, funct, false);
}
}
I have created a fiddle reproducing the problem here
The event is not registering on the button at all, when I click Run in jsfiddle.
Why is the event not registered?
var formFrame = document.getElementById('form_iframe');
formFrame.src = "/catorarn/tabLe/29/show/";
formFrame.onload = function() {
var formFrameDoc = formFrame.contentDocument;
//click event on add button
var tables = formFrameDoc.getElementsByClassName('iw-formspub-container');
var children ;
for (var i = 0 ; i < tables.length; i++ ){
children = tables[i].getElementsByTagName('*');
for (var j = 0; j < children.length; j++ ){
if( children[j].textContent === 'Research project' ){
var btn = formFrameDoc.querySelector(".fa.fa-plus-circle");
btn.addEventListener('click', function(){ console.log('finally'); });
}
}
}
};
The xpath selector that I had to use was going to be ugly and complex, something like
//i[contains(#class,'fa-plus-circle') and ../../../../../../../../../../../td/table/tbody/tr/td/span[contains(text(),'Research project')]]

Call script from another script

In HTML5 I have a dropdown menu . When choosing different options I hide or show different parts of my page. Here is that script:
document
.getElementById('target')
.addEventListener('change', function () {
'use strict';
var vis = document.querySelector('.vis'),
target = document.getElementById(this.value);
if (vis !== null) {
vis.className = 'inv';
}
if (target !== null ) {
target.className = 'vis';
}
});
However what I want to do now, in another script is to preload an option from the dropdown. I can do it easily with this script:
setSelectedIndex(document.getElementById('target'),'content_1');
function setSelectedIndex(s, valsearch)
{
// Loop through all the items in drop down list
for (i = 0; i< s.options.length; i++)
{
if (s.options[i].value == valsearch)
{
// Item is found. Set its property and exit
s.options[i].selected = true;
break;
}
}
return;
}
This is where my problem comes up, my dropdow will get the value I want, but the part that I want to be shown when choosing that option won't come up.
That is because change events need to happen from the browser.
When the user commits the change explicitly (e.g. by selecting a value
from a 's dropdown with a mouse click, by selecting a date
from a date picker for , by selecting a file in the
file picker for , etc.);
If your using Jquery you can:
$("#id").val("value").trigger('change');
or you can use javascript if your not worried about building the event object:
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
element.dispatchEvent(evt);
}
else
element.fireEvent("onchange");
I would recommend moving your anonymous onchange function into a named function that you can call once onload, and again onchange.
Here is the function I wrote:
function setContent(id) {
//get the current visible content
var vis = document.querySelector('.vis');
//get the target element by id
var target = document.getElementById(id);
//make current vis element inv
if (vis) vis.className = "inv";
//make target element vis
if (target) target.className = 'vis';
}
and a fiddle
edited: got rid of querySelectorAll to stick closer to OP original code and updated fiddle. clarified and commented code.
The problem you have is changing a vale or the selected value of an input with JavaScript does not trigger any change event. So you would need to manually trigger the event.
function setSelectedIndex(s, valsearch)
{
// Loop through all the items in drop down list
for (i = 0; i< s.options.length; i++)
{
if (s.options[i].value == valsearch)
{
// Item is found. Set its property and exit
s.options[i].selected = true;
break;
}
}
//Setting the selected value with JavaScript does not trigger the change event so you need to manually trigger the change event
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
s.dispatchEvent(evt);
} else {
s.fireEvent("onchange");
}
return;
}

JavaScript in Zend and jQuery Mobile

I'm developing an application in ZF1, using jQuery Mobile. I have a form (fragment):
$options = array('Employee', 'Supervisor', 'Other');
$form1->addElement('select', 'role', array('multioptions' => $options);
$form1->role->setAttribs(array('onchange', 'showHide()'));
$form2->addElement('text', 'position');
I have a script:
function showHide(){
var hide = false;
if(document.getElementById("form1-role").value === "Employee" ||
document.getElementById("form1-role").value === "Supervisor") {
hide = false;
} else {
hide = true;
}
var i;
var elements = [
"form2-position-label",
"form2-position-element"
];
for(i = 0; i < elements.length; i++) {
if(document.getElementById(elements[i]) !== null) {
document.getElementById(elements[i]).hidden = hide;
}
}
}
The idea is - when user selects 'Other' from the list the Textbox 'position' suppose to hide. Otherwise it should be visible. Everything works fine until form validation returns false - then validator messages appear and script stops working.
What is interesting - when I put alert("hello"); to the script, it does show the alert but still doesn't hide the textbox.
You can remove your $form1->role->setAttribs(array('onchange', 'showHide()')); and use this (seeing as you have jQuery on the page anyway).
$(function(){
$('#form1-role').on('change', function(){
var role = $(this).val();
$('#form2-position-label, #form2-position-element')
.toggleClass('hidden', role !== 'Employee' && role !== 'Supervisor');
});
});
This toggles a class on the target elements. So the CSS is simple:
.hidden {
display: none;
}
If you want this to activate on the page rendering as well (i.e. if there is an error message to display), you can put .change(); at the end of the on call.
$(function(){
$('#form1-role').on('change', function(){
var role = $(this).val();
$('#form2-position-label, #form2-position-element')
.toggleClass('hidden', role !== 'Employee' && role !== 'Supervisor');
}).change();
});
This will trigger a change event as soon as the page renders and execute the logic within the handler.

IE lose focus after field has been clicked into

I have an error layer that is presented on a form for an invalid/blank entries. When that error layer is presented, I want the current field to lose focus. In IE, I can't get this to work. The focus is always remaining in the field.
<!--Jquery function to override JS alert with DOM layer alert message-->
function customAlert(){
var args = arguments;
if(args.length > 1) {
// check that custom alert was called with at least two arguments
var msg = args[0];
$("li").removeClass("alertRed");
$("input").removeClass("CO_form_alert");
$("select").removeClass("CO_form_alert");
var div = $(".errorPopup");
div.css({"display":"block"});
if (div.length == 0) {
div = $("<div class='errorPopup' onclick='$(this).hide();'></div>");
$("body").prepend(div);
}
div.html(msg);
for(var i = 1; i < args.length; i++) {
var inputID = args[i];
$("#"+inputID).addClass("CO_form_alert").parent().addClass("alertRed");
$("input,select,radio,checkbox").focus(function(){
$(this).unbind('focus'); // remove this handler
$('.errorPopup').hide(); // hide error popup
});
}
}
}
I've tried ('body').focus(); and $("#"+inputID).focusout(); which also don't work.
I also tried:
div.css({"display":"block"});
$("input,select,radio,checkbox").blur();
and
$("input,select,radio,checkbox").blur(function(){
$(this).unbind('focus'); // remove this handler
$('.errorPopup').hide(); // hide error popup
});
but neither one works.
Use blur method.
$("input,select,radio,checkbox").blur();
Did you try
$("input,select,radio,checkbox").blur();
?

How to check/uncheck checkboxes by clicking a hyperlink?

I have 11 checkboxes with individual ids inside a modal popup.I want to have a hyperlink called SelectAll,by clicking on which every checkbox got checked.I want this to be done by javascript/jquery.
Please show me how to call the function
You could attach to the click event of the anchor with an id selectall and then set the checked attribute of all checkboxes inside the modal:
$(function() {
$('a#selectall').click(function() {
$('#somecontainerdiv input:checkbox').attr('checked', 'checked');
return false;
});
});
You can do like this in jquery:
$(function(){
$('#link_id').click(function(){
$('input[type="checkbox"]').attr('checked', 'checked');
return false;
});
});
If you have more than one form, you can specify form id like this:
$(function(){
$('#link_id').click(function(){
$('#form_id input[type="checkbox"]').attr('checked', 'checked');
return false;
});
});
This should work, clicking on the element (typically an input, but if you want to use a link remember to also add 'return false;' to prevent the page reloading/moving) with the id of 'selectAllInputsButton' should apply the 'selected="selected"' attribute to all inputs (refine as necessary) with a class name of 'modalCheckboxes'.
This is un-tested, writing on my phone away from my desk, but I think it's functional, if not pretty.
$(document).ready(
function(){
$('#selectAllInputsButton').click(
function(){
$('input.modalCheckboxes').attr('selected','selected');
}
);
}
);
$(function(){
$('#link_id').click(function(e){
e.preventDefault(); // unbind default click event
$('#modalPopup').find(':checkbox').click(); // trigger click event on each checkbox
});
});
function CheckUncheck(obj) {
var pnlPrivacySettings = document.getElementById('pnlPrivacySettings');
var items = pnlPrivacySettings.getElementsByTagName('input');
var btnObj = document.getElementById('hdnCheckUncheck');
if (btnObj.value == '0') {
for (i = 0; i < items.length; i++) {
if (items[i].type == "checkbox") {
if (!items[i].checked) {
items[i].checked = true;
}
}
}
btnObj.value = "1";
}
else {
for (i = 0; i < items.length; i++) {
if (items[i].type == "checkbox") {
if (items[i].checked) {
items[i].checked = false;
}
}
}
btnObj.value = "0";
}
}

Categories