check if object is a textbox - javascript

大兔子大兔子 提交于 2019-12-22 01:32:58

问题


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?


回答1:


var isInputText = obj instanceof HTMLInputElement && obj.type == 'text';



回答2:


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;
}



回答3:


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');
}



回答4:


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
}



回答5:


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');
}



回答6:


if(textbox instanceof HTMLInputElement && textbox.getAttribute("type") == "text") {
    alert("I'm an input text element");
}


来源:https://stackoverflow.com/questions/6444968/check-if-object-is-a-textbox-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!