naswgr naswgr - 3 months ago 7
jQuery Question

Append URL with text from any clicked link

I have a table of part numbers. My goal is to have the user click on the part number and have that part number populate into a form field on a separate page. I have successfully accomplished this by appending the current page's URL with the clicked link text and then extrapolating it from the URL to populate the form field. My issue is that I have only had success with inline "onclick" script. I have hundreds of part numbers and putting the script on each line isn't ideal (or proper I imagine). This is what I am currently doing to accomplish this task:

onclick="location.href = $(this).attr('href')+ '?' + $.trim($(this).text());return false"


How do I do this without the inline script?

I'm cobbling a website together for my family's business. I'm not a professional - so please forgive my ignorance. I'm extremely grateful for any assistance.

Answer

If you don't want the script on each line in your javascript section you could add the following code:

$(function(){
    $('table a').on('click',function(){
      var url=$(this).attr('href')+'?'+$.trim($(this).text());
      $(this).attr('href',url);
    });
});

The jquery $('table a') is specific to only change the url if a in the table is clicked. Then you can create the url from the current href and append what you want and reset the href. However this will only change the current href of the element the user clicks and currently with return false you are stopping the user from progressing to the next page.