views:

45

answers:

4

If I have id's of the form: t_* where * could be any text, how do I capture the click event of these id's and be able to store the value of * into a variable for my use?

A: 
var CurrentID = $(this).attr('id');
var CurrentName = CurrentID.replace("t_", "");

That should help with the repalce.

Pino
replace("t_", ""); does not work with id of "t_myidt_endit" as that gives "myidendit" not "myidt_endit"
Mark Schultheiss
+3  A: 

Use the starts with selector ^= like this:

$('element[id^="t_"]').click(function(){
  alert($(this).attr('id'));
});

Where element could be any element eg a div, input or whatever you specify or you may even leave that out:

$('[id^="t_"]').click(function(){
  alert($(this).attr('id'));
});

Update:

$('[id^="t_"]').click(function(){
  var arr = $(this).attr('id').split('_');
  alert(arr[1]);
});

More Info:

Sarfraz
thanks, this alerts the full 't_*' string. How can I get only *?
aeq
$(this).attr('id').substr(1);
jpluijmers
@aeq: See my update please.
Sarfraz
Well not exactly precise try the id string "t_myt_endit". See my answer for getting just the beginning of the ID attribute.
Mark Schultheiss
@Mark Schultheiss: I knew that, assumed as OP says it is in **t_x** format but thanks anyways :)
Sarfraz
Yes so your answer on the string I indicated gives "my" not "myt_endit" as the OP says "any text" (not beating on you, just giving an explaination for others as I see you know that :))
Mark Schultheiss
A: 

Try this:

// handle the click event of all elements whose id attribute begins with "t_"
$("[id^='t_']").click(function()
{
    var id = $(this).attr("id");

    // handle the click event here
});
Tim S. Van Haren
half the answer, nothing to get the character string for the id attribute.
Mark Schultheiss
A: 
$("[id^='t_']").click(function() 
{ 
    var idEnding = $(this).attr("id");
    idEnding.replace(/\t_/,''); 

}); 

Using the click event capture the ID that begins with t_, then replace that with nothing giving a capture the end of the ID value.

Mark Schultheiss