Display Results of Form Submission on New Tab or Window - javascript

There are several variations of this question already out there but I don't see the solution to this one specifically. Although I don't actually need this functionality it is killing me that I CAN'T make it work!
I have a field that allows the visitor to type in a URL and it will take them there.
<form name="urlField" onsubmit="return submitURLFieldForm();">
<input type="text" name="address" id="addressfield" />
</form>
The JS that handles this so that the necessary protocol is not left off is (special thanks to #h2ooooooo ):
function submitURLFieldForm() {
var url = document.getElementById('addressfield').value;
if (!url.match(/^[a-zA-Z]+:\/\//)) {
url = 'http://' + url;
}
window.location.href = url;
return false;
}
If I add a target="_blank" to my opening form tag it doesn't work. Why? And where should I add it?

You are never submitting the form.
You have an event handler that, when the form starts to submit, sets location and prevents the normal form submission.
Use window.open(url) instead of that if you want to open a new window.

var win=window.open(url, '_blank');
win.focus();
You can try this :)
happy coding :)

Related

Redirect to local html file doesn't open in same window

I know that similar questions have been asked but after various tests, no one seem to work. I think it has to do something with the fact I try to redirect from a local html file to another local html file using js.
Button in my creationPage.html:
<form>
<button id="createChar">Create character</button>
</form>
Code in my js file for redirect:
var Create = document.getElementById('createChar');
Create.addEventListener("click", function() {
//window.open(url); //opens in a new tab, WHICH IS NOT DESIRED !!!
//window.location.replace(url); //doesnt work either.
var url = "http://localhost/myprojects/L2/selectYourCharacter/test.html";
window.location.href = url;
return false;
});
I want to stick with addListenerEvent as it's best practice. If I run window.open(url, "_blank"), it doesnt work.
Summary: I want to redirect via my Button located in http://localhost/myprojects/L2/charCreation/creationPage.html to http://localhost/myprojects/L2/selectYourCharacter/selectYourCharacter.html staying in the same window.
Thanks a lot for your help as I have been stuck with this for hours...
Note: The window.open("www.youraddress.com","_self") doesn't work and I think it's because my files are running on localhost.
The complete answer to why your code is not working is because the button you have is submitting the form. Return false from the click listener just tells the browser you did not handle the click.
This code;
var Form = document.getElementById('form');
Form.addEventListener("submit", function(e) {
//window.open(url); //opens in a new tab, WHICH IS NOT DESIRED !!!
//window.location.replace(url); //doesnt work either.
var url = "http://localhost/myprojects/L2/selectYourCharacter/test.html";
window.location = url;
e.preventDefault();
});
will work because it will stop the default submit behavior of the form. The button submits the form and you handle the submit event to do what you want it to do.
Also:
var Create = document.getElementById('createChar');
Create.addEventListener("click", function(e) {
//window.open(url); //opens in a new tab, WHICH IS NOT DESIRED !!!
//window.location.replace(url); //doesnt work either.
var url = "http://localhost/myprojects/L2/selectYourCharacter/test.html";
window.location = url;
e.preventDefault();
});
this works on the same idea, but instead stops the default behavior of the button, which is submitting the form.
Try to use with a tag
like this:
<a href="/myprojects/L2/selectYourCharacter/selectYourCharacter.html" style="text-direction:none">
<button>Your Button Text</button>
</a>

How to get jQuery to open a page in the current tab rather than a new one

Before saying that the answers are already on the forum take note that I have already tried them to no avail. Basically the problem is that when I press enter to search it opens the google page in a new tab. How do I get it to open in the current tab?
This is the HTML
<div class="Search">
<img id="pic" src="http://i.imgur.com/fjAZgqe.png" alt="moose"/>
<form class="websearch">
<input autofocus placeholder="Google" type="text" id="GGLSite"> <!--this creates the textbox they can use to search. Note the ID is what the function grabs -->
<input type="button" id="GGLmeme" onclick="DoGGL()" style="display: none;" value="Search GGL"> <!-- this is just the button that calls the function. The value is whats shown on the button -->
</form>
</div>
This is the Javascript
function DoGGL(){
var GGLVar = document.getElementById("GGLSite").value; //this grabs the variable (search terms) from the textbox
var NewURL = "https://www.google.se/?gws_rd=ssl#safe=off&q=" + GGLVar; //this puts the site they typed into the wayback machines URL
var NewTabGGL = window.open(NewURL, "_blank"); //this opens a new tab with the URL.
if (NewTabGGL){ //make sure the browser can allow it
NewTabGGL.focus(); //switches them to the new tab -- done!
}
else{
alert("Popup didnt work");
}
}
$(document).ready(function(){
$('#GGLSite').keypress(function(e){
if(e.keyCode==13)
$('#GGLmeme').click();
});
});
I did some tweaks on your code (read the comments):
Javascript
// Remember capitalized functions are supposed to be used with the new operator, hence, this function must not be capitalized
function doGGL(event){
// Here we prevent the default behavior of the form submit
event.preventDefault();
// Javascript variables must not be capitalized
var gGLVar = document.getElementById("GGLSite").value;
var newURL = "https://www.google.se/?gws_rd=ssl#safe=off&q=" + gGLVar;
// This sentence navigates to desired URL in the same window
window.location.href = newURL;
}
$(document).ready(function(){
// There's no need to catch the enter key because that's the form default behavior. So I'm attaching the submit event to the function defined above
$('.websearch').on('submit', doGGL);
});
This didn't work in jsFiddle so I tried it in a local file called index.html with the same HTML, CSS but replacing the javascript with the latter.
Hope it helps!
If you are trying to just get to the page from this page, window.location = NewURL; would work. I don't see exactly what you're trying to do.

jquery append innerHTML by id in new window after load

I'm trying to use jquery to :
open a new window/tab (same domain, different page)
then add text to a text box (id = "BUpdates_SQL_Statement")
then click this button: <input type="submit" value="Apply Changes" name="BUpdates_Submit" id="BUpdates_Submit">
then close the window
here's the onclick element in the starting page (we'll call it www.mydomain.com/firstpage):
<li id="MainNav_Update"><span class="MainMenuText" onclick="runUpdateWindow();">Update</span></li>
and here's the area I want to edit in the new window (we'll call it www.mydomain.com/secondpage)
<textarea id="BUpdates_SQL_Statement"></textarea>
<input type="submit" value="Apply Changes" id="BUpdates_Submit">
<a onclick="v$('BUpdates_Submit').click();return false;" href="javascript:void(0);"><span>Apply Changes</span></a>
side note: v$('BUpdates_Submit').click();return false;" is for another external js file that has nothing to do with what I'm trying to do here.
and here's my jquery:
function runUpdateWindow() {
var updateWindow = window.open("www.mydomain.com/secondpage", "blank");
}
var updateSQL = 'UPDATE TABLE ...';
$(updateWindow).on("load", function (){
$("BUpdates_SQL_Statement", updateWindow.document).append(updateSQL);
$('BUpdates_Submit').trigger('click');
});
updateWindow.close();
The www.mydomain.com/secondpage is opening in a new tab, but the BUpdates_SQL_Statement should be:
<textarea id="BUpdates_SQL_Statement">
UPDATE TABLE...
</textarea>
but it's still blank.
I would sincerely appreciate any input. Thanks in advance!
From what I understand, what you're trying to do is automate filling out and submitting a form, and have selected a seemingly rather straightforward way of doing that. Whether or not that works, though, there's probably a simpler way.
Think about what happens when you open that other page, fill out the form, and press submit. If it's a normal HTML form with no JavaScript interfering with it, you'll probably just get a POST request. If I had this form, say:
<form action="run-sql" method="post">
<textarea name="sql"></textarea>
<input type="submit" value="Run query">
</form>
When I submitted it with some SQL, the browser would send a POST request to run-sql with one parameter, sql. Firing off a POST request is relatively simple to do from JavaScript, at least in comparison to automating another web page. Firing off an HTTP request from JavaScript is typically called AJAX, and fortunately, jQuery makes it easy with its $.post function.
So how would one use it? In that specific example, it would be as simple as this:
var mySQL = "select * from employees"; // e.g.
jQuery.post("run-sql", {sql: mySQL}, function() {
alert("Success!");
});
Now, some forms are not so simple as this, but it's worth a shot to see if your form is.
Went with doing an iframe rather than a new window:
function runUpdateWindow() {
var frame = document.createElement('iframe');
frame.src = "www.mydomain.com/secondpage";
document.body.appendChild(frame);
var frameWindow = frame.contentWindow
var updateSQL = 'UPDATE TABLE...';
frameWindow.onload = function (){
var textarea = frameWindow.document.getElementById("BUpdates_SQL_Statement");
var button = frameWindow.document.getElementById("BUpdates_Submit");
textarea.value = updateSQL;
frameWindow.v$('BUpdates_Submit').click();
};
}
a huge thank you to Dagg Nabbit for helping me figure this out!

Form not submitting to iFrame, opens in new tab

I'm using the following html beginning form code:
<form id="uploadpic" method="post" target="uppic" name="upform" action="/cgi-bin/inpost.cgi" enctype="multipart/form-data">
to try and load a page, however the page opens in a new tab.
I don't think this is part of the problem, but I'll include this anyways. This is the submit button code in the form:
<input name="filename" id="filename" type="file" onchange="submitFormAfterImageCheck();" />
And this is the function it calls:
function submitFormAfterImageCheck()
{
if(/(\.jpeg|\.jpg|\.JPG|\.gif|\.png|\.tiff)$/.test(document.getElementById("filename").value))
{
nogo = "go";
document.getElementById("uploadpic").submit();
$("#upload").html("<center>LOADING...</center>");
$('#link').hide();
$('#update_post').hide();
}
else
{
alert("You can only upload an image.");
}
}
iFrame code:
<iframe id="uppic" name="uppic"></iframe>
Why isn't this submitting to the iframe?
I also faced the same problem and found a work around.
When you set the target attribute of a form statically (as you are doing), even if the target iframe is in the same window, response is received in a new tab/window.
You can override this by setting the target attribute of form dynamically using javascript/jQuery.
javascript:
document.getElementById(formId).target = iframeId;
jQuery:
$("#formId").attr('target', iframeId);
Hope this helps.
If you are not having issues with your DOM elements (as #johndoe noted in his answer) and you are still having the problem when setting the target using Javascript (as #naren noted in his answer) then this should solve the problem:
Give your iFrame a name attribute and set your form target to that value:
<iframe name="myTarget"></iframe>
<form target="myTarget" method="post" ...></form>
The placement of the DIV element seemed to be the problem. While it was placed within the form tags, it never redirected once the form submitted. When removed from the form tags, it redirected fine.

How to post form using jQuery?

I have a form with a submit button and it works fine, but I now have a user request to make the form get saved (posted to save action) if a link on the page is clicked and the form is "dirty".
I've got the logic in place by having an isDirty JavaScript variable, now I would like to post the form from the JavaScript function when it is dirty.
My form declaration is as follows:
<form id="formSmart" action="<%= ResolveUrl("~/SmartForm/Proceed") %>"
method="post" enctype="multipart/form-data">
and my JavaScript is:
function checkLink() {
if (isDirty) {
$("#formSmart").submit();
}
}
The proceed action doesn't get called, yet when I click the submit button on the form it works fine. What am I doing wrong in the JavaScript?
Note: The call to checkLink() works fine, the ultimate problem is that $("#formSmart").submit(); is not posting to the Proceed action.
You have the correct way of submitting the form based on what you have posted and the names match up.
Are you sure you are calling checkLink and is isDirty equal to true?
Put and alert('Test'); right before you submit and in the if scope.
EDIT: To hookup your event you need to do the following:
$('#yourLinkID').click(checkLink(); return false;);
Note the return false which will cause your link to not execute a navigate. If you want the link to navigate, you can just remove that part.
Sounds like the requirement is that 'a link on the page is clicked'.
Perhaps attach this event to all the <a> tags on the page.
$(document).ready(function() {
// all <a> tags get the checkLink attached to them
$("a").click(checkLink());
});
your problem is that the browser navigate before the page performs your submit.
the solution is suspending the navigation till you save the form.
The UGLY solution:
you could do it buy saving the clicked url at a hidden field,
returning false to stop the navigation,
and after submit check for a value there and if it exists do navigation
A better solution:
post the form via ajax and after the ajax call completes(no need to check for success or error) perform the navigation(to make it really easy just use ajaxForm ajaxForm plugin)
the only problem with this solution is if the link has target="_blank" because then you have to use window.open which might be blocked by popup blockers
you can play with a simple jsbin sample i prepared showing this
this example post some values to an older version of this page + navigate to google, open fiddler and see that it first post and then navigate.
If you went to the jsbin page stop reading here
here is the Html:
<form id="formSmart" action="http://jsbin.com/oletu4/edit" method="post">
<input type="text" name="someLie" />
<input type="text" name="someLie2" />
<input type="submit" value="submit" />
<a id="lnkNavOut" href="http://www.google.com">www.google.com</a>
here is the JS:
$(document).ready(function(){
$("#lnkNavOut").click(function(){
var jqFormSmart = $("#formSmart");
//check here if the form is dirty and needs to be saved
var jqClickedLink = $(this);
$.ajax({
url: jqFormSmart.attr("action"),
type: "POST",
data:jqFormSmart.serialize(),
complete:function(){
location = jqClickedLink.attr("href");
}
});
return false;//stop navigation
});
});​

Categories