0

I have snippets of code that I don't quite understand

var row = $(this).prop('id').split('_')[1];
var col = $(this).prop('id').split('_')[2];

I'm trying to manipulate checkboxes and they're on a table. What will be the array value that's gonna be set on variables row and col?

Christos
  • 53,228
  • 8
  • 76
  • 108
  • 1
    Could you please post also the relevant HTML code ? Thanks – Christos Apr 19 '18 at 18:34
  • the id of `$(this)` seems to be a string split by two `_`'s - for example `foo_bar_string` - your `row` variable would be set to the 2nd element of the array (`bar`) and your `col` variable would be set to the 3rd element of the array (`string`). – h2ooooooo Apr 19 '18 at 18:37
  • I don't have access to the HTML code as we are using a template on an API but I have inspected the elements. The id of the elements were Q1_1_1 where Q1_[row]_[col]. And they are inside $(":checkbox").click(function(){}); – Adrian Parejo Apr 19 '18 at 18:42

1 Answers1

0

Split is a javascript web API method(Here) and does't have anything to do with jQuery.

In your case it will split the value of the id attribute if it does have a underscore (_). split returns and array , so [n] (n being any index of the array) , will return the value of the given index of the array. Eg. in the below example am is returned , which has an index of 1.

So ,

   $("#i_am_a_href").attr('id').split('_') // will return [ "i", "am", "a", "href" ]
   $("#i_am_a_href").attr('id').split('_')[1] // will return 'am'

See example below

var row = $("#i_am_a_href").attr('id').split('_');
console.log(row);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" id="i_am_a_href">Anchor Tag</a>

Pro Tip : you also probably want to learn the difference between prop() and attr() , and when to use which (LINK HERE)

Alexander Solonik
  • 9,838
  • 18
  • 76
  • 174