Valentin Chernsyh
Valentin Chernsyh

Reputation: 3

How can i get element id in js function?

JS doesn't see input ID(undefined). I have no idea why it doesn't work. I found many solutions in google, but it still doesn't work.

index.html :

<div ng-class="{'form-group has-success':checkValue(answer) == true,'form-group has-warning': checkValue(answer) == false}">
    <input id="422" 
        maxlength="3" 
        type="Integer" 
        class="form-control" 
        style="width: 100px" 
        ng-model="answer" 
        ng-blue="checkValue(answer, id)">
</div>
$scope.checkValue = function(value, id) {
    $scope.val = id;
    console.log($scope.val);
    if ($scope.val == value)
        return true;
    else
        return false;
}

The console just shows:

undefined

Upvotes: 0

Views: 88

Answers (4)

Akshay Khale
Akshay Khale

Reputation: 8371

You can get ID by following code:

var element_id = $("input[ng-model='answer']").attr("id"); //Here I am using other unique property of the element to get its attribute

You can also make use other property also or else you can make use of other Jquery selector like this

var element_id = $(".form-control").attr("id"); //This may give unexpected result if class name is repeated

or

var element_id = $("input.form-control").attr("id"); //This is more assuring way since, we are providing class name along with element name

Upvotes: 0

Akshay Khale
Akshay Khale

Reputation: 8371

You can get the ID by using the following code:

$('.form-control').attr('id');

Upvotes: 0

Refilon
Refilon

Reputation: 3489

You can get the ID by using the following code:

$('ELEMENT').attr('id');

You can also use this code for getting other attributes as class name etc.

Upvotes: 0

Timotheus0106
Timotheus0106

Reputation: 1586

with jquery:

(function($) {
    $( document ).ready(function() {
        var inputId = $('input').attr('id');
        console.log(inputId)
    });
})( jQuery );

with pure javascript:

var inputs = document.getElementsByTagName("input");
var inputId = inputs[i].id;
console.log(inputId);

Upvotes: 1

Related Questions