Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get id of an element through a function

I have a function that is called in an onclick event in a checkbox field.

<input type='checkbox' checked='' onclick='return changeEnable();' id='someid'>

and the function

function changeEnable()
{
    var val = $(this).attr('id');
    alert(val);
}

I have that but it returns undefined. Is my syntax wrong or did I miss something?

Those checkboxes are dynamically created and have different id's, that's why I want to get the id for some task.

like image 258
jackhammer013 Avatar asked Jul 02 '15 06:07

jackhammer013


People also ask

How do I find an element ID?

Once you have located your inspect element tool, right click on the element and click Inspect Element. It will bring up the element ID.

Is get element by id a method?

The getElementById() is a DOM method used to return the element that has the ID attribute with the specified value. This is one of the most common methods in the HTML DOM and is used almost every time we want to manipulate an element on our document.

How do you find the value of an element by ID?

The getElementById() method returns the elements that have given an ID which is passed to the function. This function is a widely used HTML DOM method in web designing to change the value of any particular element or get a particular element. If the passed ID to the function does not exist then it returns null.


2 Answers

Note that this in your changeEnable function will be the window. You need to pass the reference to the element as a parameter to the function:

<input type='checkbox' checked='' onclick='return changeEnable(this);' id='someid'>
function changeEnable(el) {
    var val = el.id
    alert(val);
}

Or, as an improvement, use Javascript to attach your events for a better separation of concerns:

<input type="checkbox" id="someid">
$(function() {
    $('#someid').change(function() {
        var val = this.id
        alert(val);
    }
});

Note that the above uses the change event of the checkbox, which is better for accessibility reasons.

like image 178
Rory McCrossan Avatar answered Sep 28 '22 03:09

Rory McCrossan


i think this code will help u a lot

<input type='checkbox' checked='' onclick='return changeEnable(this);' id='someid'>`
function changeEnable(thisobj)
{
    var val = thisobj.id;
    alert(val);
}
like image 37
Ankit Kathiriya Avatar answered Sep 28 '22 01:09

Ankit Kathiriya