Reputation: 23483
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
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
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
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
Reputation:
They way you did it is wrong, should be:
$('.pagination').attr('action', $('.pagination').attr('action').replace('https', 'http'));
Upvotes: 0