2

I have the following form

<form action="http://www.domain.com/processing.php?page=first&section=77&userid=replaceme">

how using jquery can I update 'replaceme' with a jquery variable?

3 Answers 3

3

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 &amp;.

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:

  1. The "userid" parameter is the last parameter, after at least one other parameter.
  2. The "userid" parameter is the middle parameter, with a parameter before it and another after it.
  3. The "userid" parameter is the first parameter, with others after it.
  4. There is a parameter with a name that ends with "userid", which should not be replaced.
  5. There is a #tag at the end of the URL, just after the "userid" parameter.

Explanation of the regular expression:

  • The first group $1 matches a '?' or '&'.
  • The second group $2 matches 'userid='.
  • Then characters are matched until either an '&' or '#' is reached or until the end of the string.
Sign up to request clarification or add additional context in comments.

1 Comment

+1 For using prop and regex. You can also pass a function to prop method, $('form').prop('action', function(i, action){ return action.replace('..', '...'); }).
2

First add an ID:

<form id="myForm" action="http://www.domain.com/processing.php?page=first&section=77&userid=replaceme">

Then on DOM ready:

$(function() {
    var $form = $('#myForm');
    var someVar = 'foo';
    $form.attr('action', $form.attr('action').replace('replaceme', someVar));
});

Demo: http://jsfiddle.net/HBQcx/

Comments

1

Let's say that you have the following markup:

  <form id="testform" action="http://www.domain.com/processing.php?page=first&section=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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.