0

I have a few checkboxes each with data atrribute data-route. On hover i alert first or any of the values i get only one letter ot symbol. Here is the code.

           foreach ($this->coords as $index=>$value) {
            echo '<label class="checkbox">
             <input checked type="checkbox" id='.$i .'
             data-route="[';
                 foreach ($value as $idroute){
                     echo '&#34;Route' . $id . '&#34;,';
                     $id++;
                 }
            echo ' ]" ';
            echo "onclick='isChecked(this);'> " . $index;
            echo "</label>";
            $i++;
        }

And the function for alert

    $('.checkbox').bind('mouseenter', function() {
    var Route = $('input', this).data('route');
    alert(Route[1]);
});

What I am doing wrong ? Thanks !

Lubomir Borisov
  • 166
  • 4
  • 18

1 Answers1

1

var Route is a string so when you will alert Route[1], it will alert the first character of the string, So you can split it with <,> and then you can access the elements of routes by the index.

Here is a sample code...

$('.checkbox').bind('mouseenter', function() {
    var Route = $('input', this).data('route').split(",");
    alert(Route[0]); // will alert the first route
});
void
  • 36,090
  • 8
  • 62
  • 107
  • This is working ! Thanks ! Btw how to pass without using split ? How the JSON should look ? – Lubomir Borisov Oct 24 '14 at 07:31
  • Well data-route is a comma seperated string, so in order to access the individual values you need to break the string. The other method to do this is use Regex. The regex expression should look like route.match(/(\S+?)(?:,|$)/g); – void Oct 24 '14 at 07:33
  • See this answer. http://stackoverflow.com/questions/16223786/store-and-retrieve-javascript-arrays-into-and-from-html5-data-attributes – Lubomir Borisov Oct 24 '14 at 07:37
  • 1
    Ohh nice, in your case the problem could be because their is an unwanted comma in your data-route which might be stopping you to access the array in that way, removing it will make the code work.. – void Oct 24 '14 at 07:41