Eyal
Eyal

Reputation: 4763

Get 'event.target.id' as String

The following script return an error:

"Uncaught TypeError: Object Reg_8712 has no method 'indexof' 

Reg_8712 is the radio button id who fired the event.

The script:

$("input:radio").change(function (event) {            

            alert(event.target.id); // this works! it returns it as string.
            var eti =  event.target.id; // 'eti' gets the object and not the string.
            var n = eti.indexof("_"); // error! cannot indexof ('eti' is an object and not string)
            var fid = eti.substring(n);

How can I get the 'eti' as string?

Upvotes: 1

Views: 8597

Answers (2)

Krish R
Krish R

Reputation: 22711

Syntax for indexOf

string.indexOf(searchValue[, fromIndex])

      alert(event.target.id); // this works! it returns it as string.
        var eti =  event.target.id.toString(); // 'eti' gets the object and not the string.
        var n = eti.indexOf("_"); // error! cannot indexof ('eti' is an object and not string)
        var fid = eti.substring(n);

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

Upvotes: 0

Shadow Wizard
Shadow Wizard

Reputation: 66389

In case something is indeed not a string, most simple way to convert is use the generic .toString() method:

var eti =  event.target.id.toString();
var n = eti.indexOf("_");

Simple test case to prove the point.

Upvotes: 4

Related Questions