user3163063 user3163063 - 4 months ago 9
Javascript Question

jQuery: how to read the name attribute?

I have little of an issue writing my script.

$(function(){
$(".wolny").click(function() {
var godzina = this.id;
var minuta = this.name;
alert(godzina + ":" + minuta);


});

alert should give me output looking like so hour:minute. Instead of that I am getting this: hour:undefined. I really dont know what to do :x

Here's HTML code (php generated)

<div class="col-sm-3 kafelek wolny" name="15" id="9"></div>


Thank's for any help.

Answer

Try using .attr() function instead like so:

var minuta = $(this).attr('name');

This works because name in your case is a attribute and not a property. This will work with any random attribute like foo that you may add.

A better way is to add a data attribute like data-name="something" and read it with $(this).data(name).

Working Example:

$(function(){
   $(".wolny").click(function() {
      var godzina = this.id;
      var minuta = $(this).attr('name');
      alert(godzina + ":" + minuta);
   });
});  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-3 kafelek wolny" name="15" id="9"> Click me! </div>