0

I have a link that redirects the user to the admin of a page and adds ?delete= with a number at the end, for example: ?delete=1.

On the page that it redirects to, I want jQuery to find the id with the numeric value, in this case 1, and then execute a function.

I thought it'd be best to store the numeric value as a variable, because it'd be easier to execute, but I don't know how to do that.

The number is different so I can't just add that number.

I wanted to do:

var exampleid = 1; (the end number on the URL)

$('body').find('#' + example).addClass('selected');

I know that I could use window.location.pathname, but it'll store ?delete= as well as the number when I only need the numeric value.

user998692
  • 5,172
  • 7
  • 40
  • 63
user2203362
  • 259
  • 1
  • 7
  • 11
  • Ah, I didn't know they were called query string values. Can I get the numeric value from a query string? – user2203362 Apr 06 '13 at 17:50
  • 1
    Yes...? Use `parseInt()` if you need to. – jeremy Apr 06 '13 at 17:51
  • I wouldn't suggest setting `id` attributes as numbers (although it's allowed). At least make them something like `id="delete2"` and then find it with `.find("#delete" + exampleid)`. Just a design suggestion – Ian Apr 06 '13 at 18:14

1 Answers1

2

You can do like this:

var url = window.location.href;

var exampleid = url.substring(url.lastIndexOf('=') + 1);

$('body').find('#' + exampleid).addClass('selected');


or if you always want to get the last character in your url, just do:
var exampleid = url.slice(-1);


If you want to get the last number, you need to use regex:
var exampleid = parseInt(url.match(/\d+$/), 10);
Eli
  • 14,779
  • 5
  • 59
  • 77
  • This will only work under very specific circumstances... – jeremy Apr 06 '13 at 17:50
  • What's the `1` for? The 1 in my example was just an example, it'll be different everytime. – user2203362 Apr 06 '13 at 17:51
  • 1
    @user2203362 that statement is to get the next character of your url after the last occurence of `=` – Eli Apr 06 '13 at 17:53
  • Hmm..but your slice wont work if numbers are in more than one digit like `10, 100, 1000` etc `.substr()` is quite better. – Jai Apr 06 '13 at 18:01
  • 1
    @Jai I said character :) – Eli Apr 06 '13 at 18:02
  • 1
    @user2203362 I'd suggest using the last example in this answer - the Regex one. It allow for any number of digits at the end of your URL...so it will get `103` from `?delete=103`, when the first two examples will not. I guess it's up to you. If it will only ever be one digit, stick to `slice` then. – Ian Apr 06 '13 at 18:12
  • Oh, I see. I'll use Regex then. Thank you! – user2203362 Apr 06 '13 at 18:49