1

I am trying to get a checkbox name when a checkbox is clicked...i am using a javascript function but it returns undefined.

Here is the code:

notType= document.getElementById($('[type="checkbox"]').attr('id')).value;
alert(notType);
2
  • 2
    Why would you select an element with jQuery than use getElementById? Now you want the name and you are reading the value? Commented Nov 20, 2015 at 14:01
  • Does this answer your question? How can I get checkbox attribute with using javascript? Commented Dec 4, 2023 at 12:51

5 Answers 5

1

In your code example, you are retrieving the value of the field, rather than the name. Instead, you should use:

var notType = document.getElementById(id).name;
Sign up to request clarification or add additional context in comments.

Comments

0

This should work. $("#" + id) finds the element with the specified id. After that, you get the attribute called "name".

var notType = $("#" + id).attr("name");

3 Comments

But now I have another issue: the functionality to check if the check box is checked or not.it shows true when checkbox is unchecked.
I'm happy to help, but if I'm correct stackoverflow allows one question at once. If you got the solution, you accept the answer and after that you can ask another question by creating a new one.
This assumes you have jQuery.
0

you can do it like this:

$('input[type="checkbox"]').on('click', function(event){
alert(event.target.id);
});

Comments

0
let checkbox = $("input[type="checkbox"]");

// if (checkbox.is(":checked")) { OR
if (checkbox.prop('checked') == true){
    let name = checkbox.name;
}

Comments

0

Pure JavaScript way of getting the checkbox name attribute when clicked:

document.querySelector('input[type="checkbox"]').addEventListener('click', ({ target }) => {
    const name = target.getAttribute('name');
    ...
});

JQuery way of getting the checkbox name attribute when clicked:

$('input[type="checkbox"]').on('click', function() {
    const $checkbox = $(this);
    const name = $checkbox.attr('name');
    ...
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.