0

I have several forms on an HTML page that look like this:

<form class="pagination" action="https://www.myaction.com" method="post">
...
</form>
<form class="pagination" action="https://www.myaction.com" method="post">
...
</form>
<form class="pagination" action="https://www.myaction.com" method="post">
...
</form>

and I want to change the action to http://www.myaction.com. What is the easiest way do this?

I tried this:

$('.pagination').attr('action').replace('https', 'http'); 

but that didn't work. Any other simple idea's?

4 Answers 4

3

All you are doing is changing a string, but not affecting the dom elements themselves.

Try:

$('.pagination').attr('action', function( _, action){
    return action.replace('https', 'http');
});

Using the function argument of attr() will loop over all matching selectors providing index and existing value as arguments.

Reference attr( attributeName, function )

Sign up to request clarification or add additional context in comments.

Comments

2

You can use the following:

$(document).ready(function() {
    $('form.pagination').attr('action', function() {
        return this.action.replace(/https:/i, 'http:');
    });
});

function out( sel ) {
     $('.pagination').each(function() {
       $(sel).append( this.action + '\n' );
     });
   }


   $(document).ready(function() {
        out('.before');
        $('form.pagination').attr('action', function() {
            return this.action.replace(/https:/i, 'http:');
        });
        out('.after');
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="pagination" action="https://www.myaction.com" method="post">
...
</form>
<form class="pagination" action="https://www.myaction.com" method="post">
...
</form>
<form class="pagination" action="https://www.myaction.com" method="post">
...
</form>
<pre class="before"><h1>BEFORE</h1></pre>
<pre class="after"><h1>AFTER</h1></pre>

1 Comment

Good idea on using regex to account for case, even if it does seem a bit overkill technically.
1

Do it like this:

$('.pagination').each(function() {
    var url = $(this).attr('action').replace('https', 'http');
    $(this).attr('action', url);
});

If you call attr with just one parameter, jQuery will understand you want to read the value. If you call it with two parameters, it'll know you want to set the value.

1 Comment

won't work if forms have different action values, will set them all the same as the value will come from first form encountered
0

They way you did it is wrong, should be:

$('.pagination').attr('action', $('.pagination').attr('action').replace('https', 'http')); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.