简体   繁体   中英

Append programmatically current anchor/hash/fragment to any form action url with Javascript/jQuery

I have a JSP with some external API custom taglibs that handle URLs with hash (I know serverside does not handle them per se).

I am trying something like this

$(document).ready(function(){
    $('form').prop('action').append(window.locator.anchor)
});

But I am doing it wrong and I am not sure if it is the best way anyway. Could you help me?

There is no reason to do this because the hash is never sent to the server. But here is how you could do it:

$('form').prop('action', function(i, val) {
    return val + window.location.hash;
});

There are a couple of things which are not correct in your code:

  • .prop(name) [docs] returns the value of that property which is often a string.

  • .append [docs] is a jQuery method to append a DOM element to another element. It is not a string method and cannot be used to concatenate strings.

  • window.locator.anchor does not exist. window.location [MDN] holds information about the current URL and it has a property hash which refers to the fragment identifier of the URL.

I recommend to have a look at the jQuery documentation . It has examples for each method. You also have to learn some elementare JavaScript to be able to perform simple operations such as string concatenation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM