0

How do you use $(this) with a JS function and then find the attr?

 function date_box() {
   alert(this.getAttribute(week));
  }

I want to get the attribute week from an element called gospel_table4. On click of gospel_table4, the function is triggered:

<a href='#'><div id='gospel_table4' week='$one_date' onclick='date_box()'> Week $one_date </div></a>

I can't do this:

$(this).click...

Because only one element of gospel_table4 is clickable. With the other method, all the elements of gospel_table4 are clickable.

Basicially, how do I get the attr from the function of date_box()?

user6902601
  • 123
  • 2
  • 10
  • 4
    `onclick='date_box(this)'` then `function date_box(this) { alert($(this).attr('week')); }` – guradio Sep 30 '16 at 03:13
  • @guradio Doesn't work... – user6902601 Sep 30 '16 at 03:20
  • @guradio - You can't have a function argument called `this`. – nnnnnn Sep 30 '16 at 03:21
  • *"I can't do this: `$(this).click...` Because only one element of gospel_table4 is clickable."* - I think you'll find that you *can* use jQuery to bind the click handler if you do it properly. But why are you making an element *inside* an anchor clickable? Normally anchors are clickable already, and a user who doesn't have a mouse will only be able to use their keyboard to "click" the *anchor*, not the div. – nnnnnn Sep 30 '16 at 03:24
  • use `getAttributes` in `JAVASCRIPT` – Karthikeyan Sekar Sep 30 '16 at 03:28

3 Answers3

6

You need a param inside your function

HTML:

<a href='#'><div id='gospel_table4' week='$one_date' onclick='date_box(this)'> Week $one_date </div></a>

Javascript:

function date_box(thisdiv){
   alert($(thisdiv).attr("week"));
}
JC Hernández
  • 777
  • 3
  • 13
0

JAVASCRIPT

function date_box(that)
{
   $attr=that.getAttribute('week');
  alert($attr);
}
<a href='#'><div id='gospel_table4' week='$one_date' onclick='date_box(this)'> Week $one_date </div></a>
0

so the reason why click is not working is that div is inside anchor tag, and anchor is clicked there are references like Anchor tag becomes non-working link in a div with float: right; or Is putting a div inside an anchor ever correct? which can give more details. So following is the code in jQuery()

$("#gospel_table4").parent("a").click(function(){
    var week = $(this).children("#gospel_table4").attr("week");
    console.log(week);
});

Explanation : Since we know that anchor is clicked first we place the click event listener on anchor tag . Then we can access the relative child element.

This will work but date_box() will also be invoked at the same time, I would recommend that you remove the onclick and and place it in side the above that way you would have more control over the code. Hope this is helpful.

Community
  • 1
  • 1