Finding the 'type' of an input element
JavascriptJavascript Problem Overview
I'd like to be able to find the type of something on the page using JavaScript. The problem is as follows: I need to check whether a specific area is a checkbox/radio button/ or text field.
If it's a checkbox or radio button it doesn't have a length (no strings in it), otherwise if it's a textfield I need to check whether or not it contains characters. The page is created dynamically so sometimes a checkbox may be displayed, other times a text field.
So my thinking is to find the type of the input, then determine what to do.
Any suggestions would be appreciated.
Javascript Solutions
Solution 1 - Javascript
Check the type
property. Would that suffice?
Solution 2 - Javascript
If you want to check the type of input within form, use the following code:
<script>
function getFind(obj) {
for (i = 0; i < obj.childNodes.length; i++) {
if (obj.childNodes[i].tagName == "INPUT") {
if (obj.childNodes[i].type == "text") {
alert("this is Text Box.")
}
else if (obj.childNodes[i].type == "checkbox") {
alert("this is CheckBox.")
}
else if (obj.childNodes[i].type == "radio") {
alert("this is Radio.")
}
}
if (obj.childNodes[i].tagName == "SELECT") {
alert("this is Select")
}
}
}
</script>
<script>
getFind(document.myform);
</script>
Solution 3 - Javascript
If you are using jQuery you can easily check the type of any element.
function(elementID){
var type = $(elementId).attr('type');
if(type == "text") //inputBox
console.log("input text" + $(elementId).val().size());
}
similarly you can check the other types and take appropriate action.
Solution 4 - Javascript
To check input type
<!DOCTYPE html>
<html>
<body>
<input type=number id="txtinp">
<button onclick=checktype()>Try it</button>
<script>
function checktype()
{
alert(document.getElementById("txtinp").type);
}
</script>
</body>
</html>