I understand that we can use (javascript)
if (typeof textbox === "object") { }
but are there methods which will allow me to ensure that the object is a textbox?
var isInputText = obj instanceof HTMLInputElement && obj.type == 'text';
As of 2016, use this:
function isTextBox(element) {
var tagName = element.tagName.toLowerCase();
if (tagName === 'textarea') return true;
if (tagName !== 'input') return false;
var type = element.getAttribute('type').toLowerCase(),
// if any of these input types is not supported by a browser, it will behave as input type text.
inputTypes = ['text', 'password', 'number', 'email', 'tel', 'url', 'search', 'date', 'datetime', 'datetime-local', 'time', 'month', 'week']
return inputTypes.indexOf(type) >= 0;
}
Are you looking for something like this?
if(textbox.tagName && textbox.tagName.toLowerCase() == "textarea") {
alert('this is a textarea');
}
If you need to know if it's a text input, you can do this:
if(textbox.tagName && textbox.tagName.toLowerCase() == "input" && textbox.type.toLowerCase() == "text") {
alert('this is a text input');
}
If it's a text input you're looking for:
if (textbox.tagName == "input" && textbox.getAttribute("type") == "text") {
// it's a text input
}
If you're looking for a textarea
if (textbox.tagName == "textarea") {
// it's a textarea
}
if(textbox instanceof HTMLInputElement && textbox.getAttribute("type") == "text") {
alert("I'm an input text element");
}
I think perhaps you would want to get a reference to an element, and then check for the return value of .type i.e.
var element = document.getElementById('element_in_question');
if(element.type == "textarea"){
console.log('I must be textarea');
}
Related
I want to convert item.outerHTML to .text(), Actually I want to convert the html to text, now what do I do ?
$(imgAttr).each(function(index,item) {
var valImg = $(item).attr("alt");
if (typeof valImg == typeof undefined || valImg == "") {
$(".url-res").append(item.outerHTML.text());
}
});
i think if condition is not being satisfied try below one
$(imgAttr).each(function(index,item) {
var valImg = $(item).attr("alt");
if (typeof valImg ==='undefined' || valImg == "") {
$(".url-res").append(item.outerHTML.text());
}
});
Generate a div with the outerhtml as it's html property using jQuery, then use text() with that object.
$('.ele').each(function(index, item) {
var valImg = $(item).attr("alt");
if (typeof valImg == "undefined" || valImg == "") {
// -------------------^------ you can use "undefined` here
$(".url-res").append($('<div/>', {
html: item.outerHTML
}).text());
}
});
Or you can use outerText property
$('.ele').each(function(index, item) {
var valImg = $(item).attr("alt");
if (typeof valImg == "undefined" || valImg == "") {
// -------------------^------ you can use "undefined` here
$(".url-res").append(item.outerText).text());
}
});
I have some input filed into a form. I am trying to check the empty and null of those value.
My js code as:
$(function(){
$('#submit').click(function(){
var cid = $('#CTID').val();
var sid = $('#sbj').val();
var d = $('#bdate').val();
var t = $('#time').val();
var dt = d+' '+t;
var path = '/admin/exam_schedule';
if (cid ==''||cid==null || sid==''||cid==null || d==''||d==null || t==''||t==null) {
alert('Input all data fields');
}
else{
var url='/admin/insert_exam_schedule';
$.post(url,{c:cid,s:sid,d:dt},function(data){
alert(data);
window.location.href= path
});
}
});
});
But the problem of this code are: When I give space into the input field then it takes the space as input.But, I want to validate all of the possible way, so that I can take real data as input.
val() will only return null for a select element, everything else should return '', therefore, if you aren't using a select element then str != '' or str.length > 0 should be sufficient.
If you are using a select element then you check whethre the value is assigned first e.g. str && str != '' or str && str.length > 0 (or alternatively you default null to '' for consistency).
If you want to exclude whitespace-only strings then use trim() during validation.
var cid = $('#CTID').val();
var sid = $('#sbj').val();
var d = $('#bdate').val();
var t = $('#time').val();
var dt = d+' '+t;
if (cid.trim() == '' || sid.trim() == '' || d.trim() == '' || t.trim() == '') {
// data invalid
}
else {
// data valid
}
Try,
var condition = $('#CTID,#sbj,#bdate,#time').map(function(){
return $.trim(this.value);
}).get().join('') === '';
if(condition){ alert('Input all data fields'); }
DEMO
Improvised version,
var condition = false;
$('#CTID,#sbj,#bdate,#time').each(function(){
if($.trim(this.value) === "") {
condition = true;
return false;
}
})
if(condition){ alert('Input all data fields'); }
Full code would be,
$('#submit').click(function(e){
e.preventDefalut();
var condition = $('#CTID,#sbj,#bdate,#time').map(function(){
return $.trim(this.value);
}).get().join('') === '';
if(condition){ alert('Input all data fields'); }
else {
var url='/admin/insert_exam_schedule';
$.post(url,{c:cid,s:sid,d:dt},function(data){
alert(data);
window.location.href= path
});
}
});
I found several solutions to this using jquery and javascript, however, it has to declare all the fields in jquery, but its not efficient since I have 30+ asp textboxes on my form, how can i prompt the user to save the data or changes have been made on page unload.
I use this:
Be sure to set the default="" attribute on your fields!
function formIsDirty(form) {
var i, j, element, type;
if(typeof form === 'undefined') {
return false;
}
for (i = 0; i < form.elements.length; i += 1) {
element = form.elements[i];
type = element.type;
if (type === "checkbox" || type === "radio") {
if (element.checked !== element.defaultChecked) {
return true;
}
} else if (type === "hidden" || type === "password" || type === "text" || type === "textarea") {
if (element.value !== element.defaultValue) {
return true;
}
} else if (type === "select-one" || type === "select-multiple") {
for (j = 0; j < element.options.length; j += 1) {
if (element.options[j].selected !== element.options[j].defaultSelected) {
return true;
}
}
}
}
return false;
}
$( window ).unload(function() {
if(formIsDirty(document.forms["formName"])) {
return confirm("There are unsaved changes, leave this page?");
}
}
As an extra tip, when you generate the page in asp, if you set the default="" attribute to the current value in the database, you can detect not only if it's empty, but if the value has been changed.
This also allows proper use of the form.reset() button/method (w3Schools page here
Assuming that all text text boxes have the same style class ('inputField' is used below) you can use something like:
$( window ).unload(function() {
if ($('.inputField').is(':empty')){
alert('Please fill all text boxes');
}
});
what is the difference, in using class vs addClassName jscript?
in a for loop, whenever I was adding a class to the existing class, then after each loop cycle it was adding new class to it. So condition to enter the loop was changing after each time.
when I used class instead of addClassName then everything started to work as it should be. Which is after each reverse session the loop was matching the condition.
How it can be explained?
WORKING VERSION:
for (var i = 0; i < fields.length; i++) //instead of .each
{
alert(0.5);
alert(fields[i].className);
if (fields[i].className == 'text' || fields[i].className == 'date' || fields[i].className == 'number' || fields[i].className == 'text error' || fields[i].className == 'date error' || fields[i].className == 'number error' || fields[i].className == 'text valid' || fields[i].className == 'date valid' || fields[i].className == 'number valid' || fields[i].className == 'text valid error' || fields[i].className == 'date valid error' || fields[i].className == 'number valid error' )
{
alert(0.3);
var val = fields[i];
var classname = "";
if(val.value.length <= 4) {
classname = fields[i].className + " error";
fields[i].class = classname;
Effect.Shake(fields[i], { times:3 }, 50);
errorString = 'Please complete all required fields.';
alert(0.6);
alert(val.value);
alert(0.66);
alert(fields[i].name);
alert(val.value.class);
//error++;
}
else {
classname = fields[i].className + " valid";
fields[i].class = classname;
alert(8.5);
alert(val.value.class);
}
}
alert(8.8);
alert(fields[i].class);
}
VERSION WHICH IS NOT WORKING:
for (var i = 0; i < fields.length; i++) //instead of .each
{
if (fields[i].className == 'text' || fields[i].className == 'date' || fields[i].className == 'number' || fields[i].className == 'text error' || fields[i].className == 'date error' || fields[i].className == 'number error' )
{
var val = fields[i];
if(val.value.length <= 4) {
fields[i].addClassName('error');
Effect.Shake(fields[i], { times:3 }, 50);
errorString = 'Please complete all required fields.';
error++;
} else {
fields[i].addClassName('valid');
}
}
}
Explanation
class is a reserved keyword (for possible future use), therefore it should not be used as object attribute (like someobject.reservedKeyword) and therefore className instead of class is used as nnnnnn points out in the comment to your question.
In your code, this won't work:
fields[i].class = classname
...but this one will
fields[i].className = classname
This is the source code of prototypejs addClassName
function addClassName(element, className) {
if (!(element = $(element))) return;
if (!hasClassName(element, className))
element.className += (element.className ? ' ' : '') + className;
return element;
}
see the prototypejs link
Solution
Therefore use addClassName, removeClassName and hasClassName. In your code:
for (var i = 0; i < fields.length; i++) {
if(fields[i].hasClassName("text") || fields[i].hasClassName("number") || fields[i].hasClassName("date")) {
if(fields[i].value.length<=4) {
fields[i].addClassName("error");
fields[i].removeClassName("valid");
Effect.Shake(fields[i], { times:3 }, 50);
errorString = 'Please complete all required fields.';
}
else {
fields[i].addClassName("valid");
fields[i].removeClassName("error");
}
}
}
Note: in modern browsers we use classList attribute instead:
prototype.js | modern browsers
---------------------------------------------------------------------
element.hasClassName("someclass") | element.classList.contains("someclass")
element.addClassName("someclass") | element.classList.add("someclass")
element.removeClassName("someclass") | element.classList.remove("someclass")
addClassName is the prototypejs way of adding a class to an HTML element.
If you have been assigning to $('something').class what you did is add a property to that object in particular, each time you set it to that object it would be replaced, if you create a new object that refers to the same element it will not have that property and - of course - it will not be tied to the class of the HTML element.
This is my alert function to show the alert message:
function alertPopup() {
var image = "file://C:/stat.png";
var win = Components.classes['#mozilla.org/embedcomp/window-watcher;1'].
getService(Components.interfaces.nsIWindowWatcher).
openWindow(null, 'chrome://global/content/alerts/alert.xul',
'_blank', 'chrome,titlebar=no,popup=yes', null);
win.arguments = [image, 'Hi, there', 'You can make a PDE by clicking on the PDE button in the Status-bar', false,];
document.getElementById('myImage').setAttribute("hidden", "false");
}
This funciton to to get the entered text in the Firefox browser and paste in the textbox plugin.
onKeypress : function (e) {
var node = e.target;
var nodeName = node.nodeName.toLowerCase();
//text area cache onKeyPress code
if ( nodeName == "textarea" && node.value == "" && e.keyCode == 13 ) {
pde.fillText(node);
return;
}
// this node is a WYSIWYG editor or an editable node?
if ( ( nodeName != "html" || node.ownerDocument.designMode != "on" ) && node.contentEditable != "true" )
return;
if ( node.textContent == "" && e.keyCode == 13 ) {
pde.fillText(node);
return;
}
if (!node.tacacheOnSave) {
pde.fillText(node);
}
},
onChange : function (e) {
var node = e.target;
var nodeName = node.nodeName.toLowerCase();
//alert("onChange : "+nodeName);
if ( nodeName != "textarea" )
return;
pde.fillText(node);
},
onInput : function (e) {
var node = e.target;
var nodeName = node.nodeName.toLowerCase();
//alert("onInput : "+nodeName);
// Only for textarea node
if ( node.nodeName.toLowerCase() != "textarea" )
return;
if ( node.value == "" )
return;
pde.fillText(node);
},
fillText : function (node) {
nodeSRC = node;
if ( node.nodeName.toLowerCase() == "textarea" ) {
userContent = node.value;
}
else if ( node.nodeName.toLowerCase() == "html" ) {
userContent = node.ownerDocument.body.innerHTML;
}
else // element.contentEditable == true
userContent = node.innerHTML;
},
emptyNodeSRC : function (node){
if ( node.nodeName.toLowerCase() == "textarea" ) {
node.value = "";
}
else if ( node.nodeName.toLowerCase() == "html" ) {
node.ownerDocument.body.innerHTML = "";
}
else // element.contentEditable == true
node.innerHTML = "";
},
maxTextEntered : 20; I want to add this parameter to my above code.
How do i trigger the pop-up function if the user typed more than 20 characetrs in the FF browser textbox in my code and I would like to reset the time after 5 mins and the start the counting once again?
https://developer.mozilla.org/en/NsIAlertsService
https://developer.mozilla.org/en/Code_snippets/Alerts_and_Notifications from these links, I couldn't find any script for my requirement.
Please propose me good solution to my problem.
Thanks guys.
After 5 days, I have a solution for my problem.
The actual code buffers the userContent (i.e when ever if the user types something in FF browser text-box or text area) everything will be put in the buffer memory
& this will be stored until the user closes the present text-area or text-box.
If the user opens up a new text-box or a new text-area & types something the new userContent will be stored in the buffer memeory(the old buffer will be deleted).
The idea is very simple for my problem(which i couldn't think deep in the beginning):
The function onKeypress function:
if ( ( nodeName != "html" || node.ownerDocument.designMode != "on" ) && node.contentEditable != "true" ) // this tells it's a html text-box area//
return;
if ( node.textContent == "" && e.keyCode == 13 ) {
pdes.fillText(node);
return;
}
This tells the browser to detect the user is typing something and pass it to the fillText(node). This call my other function
fillText : function (node) to fill the values(texts).
To check value length of the userContent variabel to trigger my alert if the user reached the assigned number value.
else if ( node.nodeName.toLowerCase() == "html" ) // his tells it's a html text-box area of any website in FF browser//
{
userContent = node.ownerDocument.body.innerHTML;
var myTest = userContent.length;
if(userContent.length == 20)
{
alertPopup(); //calling my custom alert function.
}
function alertPopup() {
var image = "chrome://PDE/skin/build.png";
var win = Components.classes['#mozilla.org/embedcomp/window-watcher;1'].
getService(Components.interfaces.nsIWindowWatcher).
openWindow(null, 'chrome://global/content/alerts/alert.xul',
'_blank', 'chrome,titlebar=no,popup=yes', null);
win.arguments = [image, 'Hi, there', 'You can make a PDE by clicking on the PDE button on the tool-bar', false];
//document.getElementById('myImage').setAttribute("hidden", "false");
}
Here is the full code:
onKeypress : function (e) {
var node = e.target;
var nodeName = node.nodeName.toLowerCase();
//text area cache onKeyPress code
//alert('hi1');
if ( nodeName == "textarea" && node.value == "" && e.keyCode == 13 ) {
pde.fillText(node);
return;
}
// this node is a WYSIWYG editor or an editable node?
if ( ( nodeName != "html" || node.ownerDocument.designMode != "on" ) && node.contentEditable != "true" )
return;
if ( node.textContent == "" && e.keyCode == 13 ) {
pde.fillText(node);
return;
}
if (!node.tacacheOnSave) {
pde.fillText(node);
}
},
fillText : function (node) {
// declare tmpNodeVal OUTSIDE the function
nodeSRC = node;
var tmpNodeVal = "";
if ( node.nodeName.toLowerCase() == "textarea" ) {
userContent = node.value;
}
else if ( node.nodeName.toLowerCase() == "html" ) {
userContent = node.ownerDocument.body.innerHTML;
//alert(userContent);
var myTest = userContent.length;
if(userContent.length == 50)
{
alertPopup();//calling my custom alert function.
}
else if(userContent.length == 200)
{
PopupNotifications.show(gBrowser.selectedBrowser, "PDES-popup",
"Hi, there!, You have reached more than the max level !",
"pde-toolbar-button", /* anchor ID */
{
label: "Build PDES",
accessKey: "D",
callback: function() {
if(nodeSRC!=null) pde.emptyNodeSRC(nodeSRC);
window.openDialog("chrome://hello/content/hellouilder.xul", "hello", "chrome,width=400,height=360",userContent, nodeSRC);
}
},null, { timeout:1000});
}
}
else // element.contentEditable == true
userContent = node.innerHTML;
}
Note:
1. The above code covers the functionality of KeyPress counter and trigger an alert.
With the above code, we can trigger an alert for the "Subject" area in Gmail or Yahoo websites during email writting process.