Parse onclick = "setLocation (...)" with jQuery / prototype

I have this tag in an example:

<button onclick="setLocation('http://mysite.com/checkout/cart/add/product/17/')" />

What I need to do is to initiate an ajax request when the button is clicked. I need the product / 17 url above added to my ajax url. Any smart ways to extract this without using regular expressions? HTML does not change - however, I can change the URL, in which case I will need to extract the exact URL from the onclick attribute.

So I need a URL or "product / 17" extracted from the onclick attribute, hopefully without using regular expressions.

thanks

+6
source share
2 answers

So, if there is no use of RegExp and no criteria for parsing a string, here is the simplest solution:

 var str = ​$("button").attr("onclick"​​​​); str = str.substring(str.lastIndexOf("add/") + 4, str.length - 3);​ 
+6
source

You can try using the split () function:

 var url = 'http://mysite.com/checkout/cart/add/product/17'; var array = url.split('add/'); alert(array[1]);​​​​​​​​​​​ 
+4
source

Source: https://habr.com/ru/post/927933/


All Articles