0

I have the value in an td attribute 'field', but I can not find a proper way to check or validate its value.

i.e.

<td class="edit" field="qcat_id" user_id="1">MyCat</td>

The way I tried:

function makeEditable(element) { 
    console.log (element);
        if (element.field =="qcat_id"){
            alert('yes');
        }
}

It will never show yes, and the console.log returns the whole <td>...</td> as string.

Update====================== Below is the code where gather the element parameter

$(function() {
    $(document).on("dblclick", "td.edit", function(){ makeEditable(this); });
});

Thank you all

ey dee ey em
  • 7,991
  • 14
  • 65
  • 121

5 Answers5

6

With JQuery it should just be as follows:

if (element.attr("field") =="qcat_id"){
    alert('yes');
}

This assumes that element is a JQuery object, if not you need to get that using an appropriate selector, something like:

var element = $(".edit");

Here is a working example


As RGraham has suggested, it would be better to use data-* attributes for storing this kind of data. You can do that like so:

<td class="edit" data-myid="qcat_id" user_id="1">MyCat</td>

Which can be retrieved with the following:

var myId = $(".edit").data("myid");

Here is an example using data attributes

musefan
  • 47,875
  • 21
  • 135
  • 185
  • I encounter error of "Uncaught TypeError: Object # has no method 'data' " Do you know why this happened? – ey dee ey em Dec 10 '13 at 14:00
  • @Chen: Instead of `makeEditable(this);` try `makeEditable($(this));` which will convert the element (`this`) into a JQuery object, which has the function `data` – musefan Dec 10 '13 at 14:19
0

Try this

$(".edit").attr("field")
Abhisek Mishra
  • 269
  • 3
  • 15
0
$(document).ready(function(){
   var a = $('.edit').attr('field');
   alert(a);
})
ramchauhan
  • 228
  • 2
  • 6
0
var element = $("td[user_id='1']");

if (element.attr("field") == "qcat_id"){
    alert('yes');
}
Guillermo Gutiérrez
  • 17,273
  • 17
  • 89
  • 116
0

You can get the value of the attribute as below.

$("td[user_id='1']").attr("field");

You should prefix the attributes with data-, this is how custom attributes are named. Also, all the attributes prefixed by data- are ignored by user agents.

Sajad Deyargaroo
  • 1,149
  • 1
  • 7
  • 20