By event.target, how I know that it is checkbox or it is radio?

JavascriptHtmlJqueryFormsRadio Button

Javascript Problem Overview


In my html:

<input type="checkbox" name="select">

<input type="radio" name="select">

name property same due to some logical reason

in my JS

I write below code:

$('input[type="checkbox"],input[type="radio"]').on("change",function(event){
    console.log(event.target.nodename);
    // on both cases it show "INPUT"
    }

    }); 

How I will know that I click on checkbox or radio button?

Javascript Solutions


Solution 1 - Javascript

.nodeName gives the html tag used so you have to use .type to get the type of the node there.

Try this one:

console.log(event.target.type);

Demo

Solution 2 - Javascript

For those of you looking for the pure JavaScript way, it's event.target.tagName.

That property is an uppercase string of the element type, like "A", "UL", "LI", etc.

Solution 3 - Javascript

console.log($(event.target).is(':radio'));
console.log($(event.target).is('[type="radio"]'));

Solution 4 - Javascript

you can use event.target.getAttribute('type') instead

Solution 5 - Javascript

Try to use attr() like,

console.log($(this).attr('type'));// checkbox or radio

Code

$('input[type="checkbox"],input[type="radio"]').on("change", function (event) {
    console.log($(this).prop('tagName'));// INPUT
    console.log($(this).attr('type'));// checkbox or radio
});

Solution 6 - Javascript

For the node type with jQuery you can use:

  • $(event.target).attr('type')
  • event.target .type

> $("SELECTOR").click(function (event) { > var idEventTarget = $(event.target).attr('id'); > console.log($(event.target).attr('type')); > console.log(event.target.type); > });

Solution 7 - Javascript

you can use

function test(e)
{
   var eve = e || window.event;
   var ele = eve.target || eve.srcElement;

   switch(ele.getAttribute('type'))
   {
     case "radio" : //do whatever

     case "checkbox" : //do
   }

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRituraj ratanView Question on Stackoverflow
Solution 1 - JavascriptJaiView Answer on Stackoverflow
Solution 2 - JavascriptJameyView Answer on Stackoverflow
Solution 3 - JavascriptArun P JohnyView Answer on Stackoverflow
Solution 4 - JavascriptPranav GuptaView Answer on Stackoverflow
Solution 5 - JavascriptRohan KumarView Answer on Stackoverflow
Solution 6 - Javascriptuser6830821View Answer on Stackoverflow
Solution 7 - JavascriptVoonicView Answer on Stackoverflow