I have the following form
<form action="http://www.domain.com/processing.php?page=first§ion=77&userid=replaceme">
how using jquery can I update 'replaceme' with a jquery variable?
I think you should use a regular expression and match the name of the "userid" parameter, rather than the "replaceme" value.
Try:
var $form = $('form');
$form.prop('action', $form.prop('action').replace(/([\?&])(userid=)[^&#]*/, '$1$2' + newValue));
Where newValue
is a variable holding what you want in place of "replaceme".
Note: In your html, the "&" characters in the URL should be replaced with the character entity &
.
UPDATE:
Using the suggestion from @undefined, this would be:
$('form').prop('action', function(i, action){ return action.replace(/([\?&])(userid=)[^&#]*/, '$1$2' + newValue); });
Now there's no need for the $form
variable.
Here's a jsfiddle demo showing the following cases:
Explanation of the regular expression:
$1
matches a '?' or '&'.$2
matches 'userid='.prop
and regex
. You can also pass a function to prop
method, $('form').prop('action', function(i, action){ return action.replace('..', '...'); })
.First add an ID:
<form id="myForm" action="http://www.domain.com/processing.php?page=first§ion=77&userid=replaceme">
Then on DOM ready:
$(function() {
var $form = $('#myForm');
var someVar = 'foo';
$form.attr('action', $form.attr('action').replace('replaceme', someVar));
});
Let's say that you have the following markup:
<form id="testform" action="http://www.domain.com/processing.php?page=first§ion=77&userid=replaceme">
</form>
and you want to change some text in the action
attribute ::
action = $('#testform').attr('action');//get the action attribute.
console.log(action);
action = action.replace('replaceme','changed');//change the action text.
$('#testform').attr('action',action);//change the action attribute.
console.log($('#testform').attr('action'));//test the results.