Home > Back-end >  How to get URL attribute from form action using jQuery?
How to get URL attribute from form action using jQuery?

Time:09-17

After spending several hours on trying differents codes, I would love to get your help ! I try to get URL attribute with jQuery from differents urls on my page that are contained inside a form elements. Exemple of HTML :

<form action="https://www.example.com/register-offer?provider=directEnergie" target="_blank" method="post"></form>

<form action="https://www.example.com/register-offer?provider=engie" target="_blank" method="post"></form>

I use this code which is working for getting the first clicked url, but if I click on another form URLs, it always returns the first one :

function () {
var f = $('form').attr('action');
return f.split('=').pop(); //
               

CodePudding user response:

// url = "https://www.example.com/register-offer?provider=directEnergie";
let url = new URL($("form").attr("action"));

console.log(url.searchParams.get('provider'))

//output:
// directEnergie

CodePudding user response:

You can try this code :

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function click_form(element){
    var action = element.action;
    var param = action.split('=').pop();
    alert(param);
}
</script>
</head>
<body>

<form action="https://www.example.com/register-offer?provider=directEnergie" target="_blank" method="post" onclick="click_form(this);">Click Form 1</form>
<br>
<form action="https://www.example.com/register-offer?provider=engie" target="_blank" method="post" onclick="click_form(this);">Click Form 2</form>

</body>
</html>

CodePudding user response:

This should work

function click_form(e) {
  console.log(e.action.split('=').pop())
  return e.action.split('=').pop();
}
<form action="https://www.example.com/register-offer?provider=directEnergie" target="_blank" method="post" onclick="click_form(this);">Click Form 1</form>
<br>
<form action="https://www.example.com/register-offer?provider=engie" target="_blank" method="post" onclick="click_form(this);">Click Form 2</form>

CodePudding user response:

function callback() {
// to get single url
var form = $('form')
var f = $('form').attr('action');
//console.log(f);

// to get each url
$.each(form, function (i,data) {
    console.log($(this).attr('action'));
});

// to get each url provider
$.each(form, function (i,data) {
    console.log($(this).attr('action').split('=').pop());
});
}

callback()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form action="https://www.example.com/register-offer?provider=directEnergie" target="_blank" method="post"></form>

<form action="https://www.example.com/register-offer?provider=engie" target="_blank" method="post"></form>

  • Related