Jess McKenzie
Jess McKenzie

Reputation: 8385

jQuery data-id undefined

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();

    });
}

Upvotes: 2

Views: 7429

Answers (2)

Alessandro Minoccheri
Alessandro Minoccheri

Reputation: 35963

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");

Upvotes: 5

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143061

Your attribute is dataid, not data-id.

Upvotes: 3

Related Questions