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

javascript - jQuery data-id undefined - Stack Overflow

programmeradmin2浏览0评论

I am unsure why I am not getting my data-id value its being showed as undefined

The data-id shows an int

<li>
    <input style="width:100%;" placeholder="Page Title" id="post_title" onclick="urlCheck()" dataid="<?php echo($website_id);?>" name="post_title" type="text" value="<?php echo set_value('post_title', $post['post_title']); ?>" />
    <?php echo form_error('post_title'); ?>
</li>

JS:

function urlCheck() {

    $(".postForm").on('click', '#post_title', function (e) {
        var id = $('#post_title').attr("data-id");

        console.log(id);

        e.preventDefault();

    });
}

I am unsure why I am not getting my data-id value its being showed as undefined

The data-id shows an int

<li>
    <input style="width:100%;" placeholder="Page Title" id="post_title" onclick="urlCheck()" dataid="<?php echo($website_id);?>" name="post_title" type="text" value="<?php echo set_value('post_title', $post['post_title']); ?>" />
    <?php echo form_error('post_title'); ?>
</li>

JS:

function urlCheck() {

    $(".postForm").on('click', '#post_title', function (e) {
        var id = $('#post_title').attr("data-id");

        console.log(id);

        e.preventDefault();

    });
}
Share Improve this question asked Oct 23, 2013 at 19:42 Jess McKenzieJess McKenzie 8,38528 gold badges104 silver badges172 bronze badges 1
  • There is no hyphen - in your html.Try .attr("dataid") – Selvakumar Arumugam Commented Oct 23, 2013 at 19:43
Add a ment  | 

2 Answers 2

Reset to default 5

The problem is that you are using dataid instead of data-id, and to retrieve the attibute you need to use .data() instead of .attr()

change this:

<input style="width:100%;" placeholder="Page Title" id="post_title" onclick="urlCheck()" dataid="<?php echo($website_id);?>" name="post_title" type="text" value="<?php echo set_value('post_title', $post['post_title']); ?>" />

to this:

<input style="width:100%;" placeholder="Page Title" id="post_title" onclick="urlCheck()" data-id="<?php echo($website_id);?>" name="post_title" type="text" value="<?php echo set_value('post_title', $post['post_title']); ?>" />

and retrieve the data in this mode:

var id = $('#post_title').data("id");

Your attribute is dataid, not data-id.

发布评论

评论列表(0)

  1. 暂无评论