最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get 'event.target.id' as String - Stack Overflow

programmeradmin5浏览0评论

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?

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?

Share Improve this question asked Nov 26, 2013 at 15:19 EyalEyal 4,7839 gold badges44 silver badges59 bronze badges 2
  • 7 The method name is indexOf (note the capital O). – Heretic Monkey Commented Nov 26, 2013 at 15:20
  • 1 mike already gave the solution but in case you need string cast : eti = String(event.target.id) or the uggly fast version eti =event.target.id+'' – TecHunter Commented Nov 26, 2013 at 15:23
Add a ment  | 

2 Answers 2

Reset to default 4

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.

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/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

发布评论

评论列表(0)

  1. 暂无评论