Bluemagica
Bluemagica

Reputation: 5158

Is it possible to attach value to form's action url through jQuery?

basically whenever the user clicks an anchor tag or submits a form, I need to ask the user for a "reason" via javascript prompt, and whatever text he inputs needs to be attached to the existing url parameters before sending.

so when anchor tag with href='index.php?id=32' is clicked, I want to visit the link 'index.php?id=32&reason="Some_reason"'....similarly for forms in the submit event I want to override the action url with the reason before proceeding with submit.

I think I can do the anchor tag by grabbing attr('href'), encoding it and then using header location replace. But I have no idea about the form....

Any suggestions on how to do this?

Upvotes: 0

Views: 466

Answers (3)

Jochem
Jochem

Reputation: 2994

$('#formId').attr('action', value); 

Should do the trick, note however that if you want to POST your reason, you will need RoToRa's approach.

Finally, to submit your form after parameter modification, you could simply use

$('#formId').submit();

Upvotes: 0

RoToRa
RoToRa

Reputation: 38431

You'll need to add a hidden field:

$("form").submit({
 var field = $("[name=reason]", this); // Check if the field already exists
 if (field.length == 0) { // If not generate one
   field = $("<input type='hidden' name='reason'>").appendTo($(this));
 }
 field.val(prompt("Reason?", field.val()));
});

Upvotes: 0

Adrian Serafin
Adrian Serafin

Reputation: 7715

Try with:

jQuery('#formId').attr('action', value);

Upvotes: 2

Related Questions