BlackHatSamurai
BlackHatSamurai

Reputation: 23483

Change HTML Form Action from 'HTTPS' to 'HTTP' with JQuery

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?

Upvotes: 0

Views: 1467

Answers (4)

Thiago Duarte
Thiago Duarte

Reputation: 941

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.

Upvotes: 1

PeterKA
PeterKA

Reputation: 24638

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>

Upvotes: 2

charlietfl
charlietfl

Reputation: 171679

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 )

Upvotes: 3

user2755150
user2755150

Reputation:

They way you did it is wrong, should be:

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

Upvotes: 0

Related Questions