Reputation: 480
My English in not good. sorry.
URL address example:
example.com/action.php?id=1&name=JOHN&[email protected]
I want change "name" only:
example.com/action.php?id=1&name=JACK&[email protected]
by Jquery or JavaScript Click Function.
I found a solution but I do not want to write everything again. I want to call name=JOHN and turn it into name=JACK.
I do not want is:
$('.element').click(function () { window.location = 'action.php?id=1&name=JACK&[email protected]'; });
Upvotes: 1
Views: 54
Reputation: 1130
I assume your link is in an href in an <a>
element .
You change change the href (or any attribute) value with the JQuery attr() function:
element.on(“click”, function () {
$(this).attr(“href”, “ example.com/action.php?id=1&name=JACK&[email protected]”);
});
Here element is the element on which you need to click, could also be a JQuery call $(“#elementID”). The this object refers in this context to the object being clicked on, so the element. If we wrap ‘this’ in a JQuery selector you can acces JQuery methods on that element, which would be .attr(). See the docs for further documentation: https://api.jquery.com/attr/
Upvotes: 1
Reputation: 31992
You can split the string by a question mark (?
) to get the parameters, then use the URLSearchParams
constructor to parse it and URLSearchParams.set
to set the name
parameter to "JACK"
:
const url = "example.com/action.php?id=1&name=JOHN&[email protected]";
const split = url.split('?');
const params = new URLSearchParams(split[1]);
params.set('name', 'JACK')
const result = split[0] + params.toString();
console.log(result)
Upvotes: 1