0

I've used this solution to select the text content for a code box using the code tag.

Jason's Answer which is the following:

function SelectText(element) {
    var doc = document
        , text = doc.getElementById(element)
        , range, selection
    ;    
    if (doc.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } else if (window.getSelection) {
        selection = window.getSelection();        
        range = document.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    }
}

$(function() {
    $('span').click(function() {
        SelectText('selectme');
    });
});

This is my code box:

 <div class="codebox"><span>{L_CODE}: {L_SELECT_ALL_CODE}</span><div id="selectme"><code></code></div></div>

The problem is that when there are multiple code boxes in the same page, only the first one is selected because of the ID being the same. How can I use a dynamic way so that when the users clicks to select the desired text, the clicked container will be selected regardless of how many boxes are present?

Community
  • 1
  • 1
user2513846
  • 1,151
  • 2
  • 16
  • 39

1 Answers1

3

First of all, you should never have more than one element using the same ID (use the attributes CLASS or DATA for this purpose).

Then you just need to do:

$(".class").click(function(element) {
  // Do crazy stuff with element
})

Or with the data attribute:

$("data[foo='blah']").click(function(element) {
  // Do crazy stuff with element
})
htatche
  • 693
  • 3
  • 17
  • I edited my comments to reflect the code I'm using. I still don't understand how to use your code. – user2513846 Feb 21 '14 at 20:28
  • Try to pass a param to your click callback, like I do in my code, this param is actually the element being clicked. – htatche Feb 21 '14 at 20:34
  • Try this otherwise: SelectText($(this).attr('id')), without passing any params, this sould work for your code above. – htatche Feb 21 '14 at 20:36
  • I tried this and it's not working: $(function() { SelectText($(this).attr('selectme')); }); – user2513846 Feb 21 '14 at 20:52
  • "selectme" is not a valid attribute, what you are looking for is the "id" attribute of your DOM element. Look at your function above: `text = doc.getElementById(element)` – htatche Feb 21 '14 at 20:55
  • so what should I use if I dont specify an element? This is so confusing – user2513846 Feb 21 '14 at 20:59