[jquery] How to get input type using jquery?

I have a page where the input type always varies, and I need to get the values depending on the input type. So if the type is a radio, I need to get which is checked, and if it is a checkbox I need to now which are checked, and if it is a drop down I need to know which is selected, and I if it is a text/textarea I need to know the values.

Any idea on how to do that?

This question is related to jquery input types

The answer is


GetValue = function(id) {
  var tag = this.tagName;
  var type = this.attr("type");

  if (tag == "input" && (type == "checkbox" || type == "radio"))
    return this.is(":checked");

  return this.val();
};

var val = $('input:checkbox:checked, input:radio:checked, \
   select option:selected, textarea, input:text',
   $('#container')).val();

Comments:

  1. I assume, that there is exactly one form element, that can be either a textarea, input field, select form, a set of radio buttons or a single checkbox (you will have to update my code if you need more checkboxes).

  2. The element in question lives inside an element with ID container (to remove ambiguences with other elements on the page).

  3. The code will then return the value of the first matching element it finds. Since I use :checked and so on, this should always be exactly the value of what you're looking for.


It would seem that the attr functionality is getting further deprecated

$(this).attr('TYPE')
undefined
$(this).prop('type')
"text"

In my application I ended up with two different elements having the same id (bad). One element was a div and the other an input. I was trying to sum up my inputs and took me a while to realise the duplicate ids. By placing the type of the element I wanted in front of #, I was able to grab the value of the input element and discard the div:

$("input#_myelementid").val();

I hope it helps.


The best place to start looking is http://api.jquery.com/category/selectors/

This will give you a good set of examples.

Ultamatly the selecting of elements in the DOM is achived using CSS selectors so if you think about getting an element by id you will want to use $('#elementId'), if you want all the input tags use $('input') and finaly the part i think you'll want if you want all input tags with a type of checkbox use $('input, [type=checkbox])

Note: You'll find most of the values you want are on attributes so the css selector for attributes is: [attributeName=value]

Just because you asked for the dropdown as aposed to a listbox try the following:


$('select, [size]).each(function(){
  var selectedItem = $('select, [select]', this).first();
});

The code was from memory so please accound for small errors


If what you're saying is that you want to get all inputs inside a form that have a value without worrying about the input type, try this:

Example: http://jsfiddle.net/nfLfa/

var $inputs = $('form').find(':checked,:selected,:text,textarea').filter(function() {
    return $.trim( this.value ) != '';
});

Now you should have a set of input elements that have some value.

You can put the values in an array:

var array = $inputs.map(function(){
    return this.value;
}).get();

Or you could serialize them:

var serialized = $inputs.serialize();

$("#yourobj").attr('type');

You could do the following:

var inputType = $('#inputid').attr('type');

  <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <script type="text/javascript" src="hs/jquery1.js"></script>
        <title>Document</title>
    </head>
    <body>
        <form>
            <input type="text" class="tamil">
            <input type="button" class="english">
        </form>
        <script>
            $("input").addClass(function(index){
                    console.log($(this).attr('type'));
            })
        </script>
    </body>
    </html>

i get wright form type


Very Simple using jQuery... To check that selected element is type of input

$(".elementClass").is('input')

To check that selected element is type of textarea

$(".elementClass").is('textarea')

To check that selected element is type of Radio

$(".elementClass").is('input[type="radio"]')

To check that selected element is type of Checkbox

$(".elementClass").is('input[type="checkbox"]')

To check that selected element is type of Input type number

$(".elementClass").is('input[type="number"]')

To check that selected element is type of Input type password

$(".elementClass").is('input[type="password"]')

To check that selected element is type of Input type email

$(".elementClass").is('input[type="email"]')

.....

...

So Basically you can change selection and type to determine required input type


<!DOCTYPE html>
<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
          $(".show-pwd").click(function(){
          alert();
            var x = $("#myInput");
            if (x[0].type === "password") {
              x[0].type = "text";
            } else {
              x[0].type = "password";
            }
          });
        });
    </script>
</head>

<body>
    <p>Click the radio button to toggle between password visibility:</p>Password:
    <input type="password" value="FakePSW" id="myInput">
    <br>
    <br>
    <input type="checkbox" class="show-pwd">Show Password</body>

</html>

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to input

Angular 4 - get input value React - clearing an input value after form submit Min and max value of input in angular4 application Disable Button in Angular 2 Angular2 - Input Field To Accept Only Numbers How to validate white spaces/empty spaces? [Angular 2] Can't bind to 'ngModel' since it isn't a known property of 'input' Mask for an Input to allow phone numbers? File upload from <input type="file"> Why does the html input with type "number" allow the letter 'e' to be entered in the field?

Examples related to types

Cannot invoke an expression whose type lacks a call signature How to declare a Fixed length Array in TypeScript Typescript input onchange event.target.value Error: Cannot invoke an expression whose type lacks a call signature Class constructor type in typescript? What is dtype('O'), in pandas? YAML equivalent of array of objects in JSON Converting std::__cxx11::string to std::string Append a tuple to a list - what's the difference between two ways? How to check if type is Boolean