Form dynamic attribute changing and submission not working - javascript

I have the following code:
Html:
<form action="/" id="mainForm" method="get">
<input type="text" name="val1" />
<button id="cmdSubmit">Submit</button>
</form>
<button id="cmdSubmit2">Submit 2</button>
Javascript:
$("#cmdSubmit2").bind('click', function () {
Submit2();
});
var Submit2 = function() {
var form = $("#mainForm").clone();
form.attr("action", "/testing");
form.submit();
}
What I'm trying to do is dynamically change the action attribute of a form with javascript and then submit it (to a different url).
What I expect to happen (in JsFiddle) is that clicking the submit button should load the jsfiddle home page, and clicking the Submit2 button should load a 404 page since the /testing url doesn't exist.
This works fine in chrome (28.0.1500.95), but does not work in Firefox (23.0.1) or IE for that matter(10.0.9200.16660).
None of these browser show any errors in the console either - I'm stumped. Any ideas?
JSFiddle
EDIT: I do actually have to clone the form, forgot to mention that. Also, this works fine in Safari (v5.1.7).

You need to somehow insert it in the DOM :
function Submit2() {
var form = $("#mainForm").clone();
form.attr("action", "/testing");
form.hide().appendTo('body');
form.submit();
}
fiddle
Works for me (FF 23.0)

You don't need to clone() the form. Try this:
var Submit2 = function() {
var form = $("#mainForm");
form.prop("action", "/testing");
form.submit();
}
Updated fiddle

Related

SubmitForm weird behavior

I had implemented a preview button and a save button in a profile page, submitting a form to two different pages. One with the code to save data, and one where is a fake page that show the informations as the original page will show.
This is the code
<form id="personal-information-form" method="post" enctype="multipart/form-data">
<!--Some code to recollect info -->
<script type="text/javascript">
function submitForm(action)
{
document.getElementById('personal-information-form').action = action;
document.getElementById('personal-information-form').setAttribute("target", "_blank");
document.getElementById('personal-information-form').submit();
}
</script>
<p><input type="submit" name="preview-info" class="my-buttons" onclick="submitForm('url_to_preview')" value="Preview" >
<span><input type="submit" name="save-info" class="my-buttons" value="Save"></span></p>
</form>
If I click once on one of the two buttons, all work fine.
If I click in the preview first and then in the save button, the save button don't save the info, instead show me the preview page. Why? How can I solve it?
When you click the Preview button you are permanently setting the action attribute of the form to the preview URL.
Generally I would prefer to do something like this with AJAX rather than with form hackery, but you could amend your current solution like this:
function submitForm(action, target) {
var form = document.getElementById('personal-information-form');
var originalTarget = form.target;
var originalAction = form.action;
form.setAttribute("target", target || "_self");
form.action = action;
form.submit();
form.target = originalTarget;
form.action = originalAction;
return false;
}
This will restore the current action and target after submitting. (Haven't tested; let me know how this goes).
Then your onclick for the Preview button should say submitForm('url_to_preview', '_blank').

How can I refresh the page when the submit button of a form is clicked?

For example I have this code:
<form name="formm" action="http://example.com/" target="_blank">
<input type="text" name="txt" />
<input type="Submit" value="Submit" />
</form>
When I click submit it sends the form to the link which opens in a new tab. This is exactly what I want to happen. However, I would also like my page to refresh so I can run some PHP code. Simple enough, I add this to my submit input:
onclick="location.reload()"
This seems to work in any other case except when it's added to the submit button. How can I get this to work?
Within the form that is submitting to a new page, add onClick="reloadpage();". This works in all 5 browsers:
function reloadpage()
{
var returnURL = "this_pages_name.php?upd=" + Math.random() * 100;
setTimeout(function()
{
window.location=returnURL;
}, 50 );
}
You could try:
onsubmit="setTimeout(function () { window.location.reload(); }, 10)"
I use this for my forms and it works perfectly across all browsers :)
You could try;
$('#form_id').on("submit", function() {
location.reload();
});
This shouldn't prevent the default action of the form being submitted, but should capture the event and reload the page.
You will need to specify an ID on the form.
In your PHP before generating any output declare a header to move location to current file:
header('Location: .');
This will set header location to: '.' (current directory) and then look for your page again. It will also clear any form datasets preventing database spam

Form submission recognition: works only when a textarea is active. What do I do wrong?

I have a page where Ajax updates the feed every once in a while. Under each post there's a textarea for a reply. JQuery/Ajax can post the reply to the database without any problems when the textarea is active. I press the submit button and everything goes well.
However, if I click somewhere else on the page and the textarea becomes inactive, the submit button doesn't work anymore like it should: it submits the form to root and doesn't run the Ajax function.
Can you figure out what's wrong in my code? Thank you for your help!
There are as many forms as there are messages on the pages. The forms look like this:
<form class="reply-form">
<textarea id="reply-11123" name="comment" class="plain-editor"></textarea>
<input type="submit" class="submit" value="Reply" />
<input type="hidden" value="URL HERE" name="url" />
</form>
Ajax code (at <head>) looks like this:
<script type="text/javascript">
$(document).ready(function()
{
$('.reply-form').on('submit', function (event) {
event.preventDefault();
var $form = $(this),
message_data = $form.find('textarea[name="comment"]').val(),
url = $form.find('input[name="url"]').val();
var postData = {};
var prefix = 'data';
postData[prefix + '[message]'] = message_data;
var posting = $.post(url, postData);
});
}
</script>
If your forms are being added to the page dynamically then you need a different event binding that will attach itself to all current and future forms. The current binding you have is called a direct binding, but what you really need is a delegated binding. A different usage of on() will give you that:
$(document).on('submit', 'form.reply-form', function (event) {
...
});

onsubmit property fails to open new window

A quick question here regarding forms. I've searched the web and can't seem to figure out why what I've implemented isn't working.
The idea is simple. I have a form inside a JSP page. The form has an 'onsubmit' property defined to open a different jsp with some parameters. Inside the form I have a few buttons, one of which calls a JavaScript function, which in turn submits the form (under some conditions).
Here's the code:
JSP:
...
<form id='testForm' onsubmit="window.open('another.jsp')">
<input type="button" onclick="callJsFunction()" />
..
</form>
JavaScript:
function callJsFunction() {
if (launchNow == 1) {
var form = document.getElementById("testForm");
form.submit();
}
}
If I add target="_blank" to the form definition, a new window does open, but NOT the jsp I want to open. Ultimately, I want the form to perform a servlet action (using the action attribute) and then open the new jsp. Any ideas???
Thanks!
The solution to what I was looking for is found here: Javascript Post on Form Submit open a new window
Rather than setting target="_blank", I can set the target to the window I define and open. In my servlet, I redirect to the desired jsp, and it appears in the new pop-up window.
<form id='testForm' action='another.jsp' target='_blank'>
I might be wrong but is this what you are looking for?
Please see the working demo at this link: http://fiddle.jshell.net/vf6AC/show/light/ (don't work in the jsfiddle)
<form action="http://google.com" id="testForm">
<input type="submit" />
</form>​
<script type="text/javascript">
var testForm = document.getElementById("testForm");
testForm.onsubmit = function(e){
window.open("http://stackoverflow.com");
return true;
};​
</script>
See the jsfiddle here: http://jsfiddle.net/vf6AC/

Bug in IE when using Javascript to change a form action, when method=get and URL contains a hash

I'm using Javascript to change a form's URL when you submit the form. If that URL contains a hash string (#), then Internet Explorer ignores it and just submits to the part of the html before that. Firefox and Chrome are fine.
Demonstration:
<script type="text/javascript">
function changeURL() {
var myform = document.getElementById('myform');
myform.setAttribute("action", "page2.html#hello");
return false;
}
</script>
<form id="myform" action="page1.html" method="get" onsubmit="changeURL()">
<input type="submit">
</form>
If I change the method to a "post" then it's fine. If I use a "get", IE lands on page2.html but without the #hello in the URL.
This happens regardless of if I use jquery or only javascript, tried each of the following:
myform.action = "page2.html#hello";
myform.attr("action", "page2.html#hello");
myform.get(0).setAttribute("action", "page2.html#hello");
Any suggestions (assume that I have to keep the method as a 'get', and that I must use a hash in the URL, and that I must use Javascript to change this action dynamically)?
Testing on my own in IE8 reveals that it does insist that the hash (#hello) come after the query string (?foo=bar) in a URL. Sadly, your form doesn't do this for you and there's no way to force it to do so when submitting the form.
Try encoding the hash in the form instead:
<script type="text/javascript">
function changeURL() {
var hidden = document.createElement('input');
hidden.setAttribute("type", "hidden");
hidden.setAttribute("name", "hash");
hidden.setAttribute("value", "hello");
var myform = document.getElementById('myform');
myform.setAttribute("action", "page2.html");
myform.appendChild(hidden);
// return false;
}
</script>
<form id="myform" action="page1.html" method="get" onsubmit="changeURL()">
<input type="submit">
</form>
And at the top of page2.html, extract it back out:
<script type="text/javascript">
var qs = window.location.search.substring(1);
var qsarr = qs.split("&");
for (var i=0; i<qsarr.length; i++) {
var tarr = qsarr[i].split("=");
if (tarr[0]==="hash") {
window.location.hash = tarr[1];
}
}
</script>
I believe that IE just behaves differently with the hash and I don't think it is is meant to be used in this manor.
No javascript in the following will produce the same results...displays in FF and not in IE
<form action="#test" method="get">
<input type="text" value="test" />
<input type="submit" />
</form>
At least you know it's not a javascript problem. I lied about the question mark lol oops.
In the end we decided we could just update window.location.href to go to the new location rather than submit the form. This might seem like an odd answer, but actually the way we were handling our form meant this wasn't a problem to do. i.e. we were disabling all our form fields (hence no querystring being appended to the URL normally), then generating one of several different SEO-friendly style URLs based on what the form fields contained, then updating the form action and submitting the form. So now we do all that but don't bother submitting the form, just change the page location.

Categories