Form submit not working in Javascript function after innerhtml update - javascript

I have a Javascript function called from a OnClientClick which is changing a forms action. The reason for this is there are other buttons on the form but only one of them is required to do the postback. I would like the target of the postback to open in a new window whilst altering the content of the sender form using div.innerhtml="Some HTML Code HERE!"
I have managed to write a function that works in Chrome, IE and Opera but I cannot get it to work in Firefox. As soon as I add the code to change the content of the Div for some reason the Form.Submit does not appear to happen. The content of the div updates but the new window does not open. If I remove the innerHTML edit from the code below the submit works and new window or tab opens as required. This problem on appears to occur in Firefox.
This is my code.
<script type="text/javascript">
/* Used to change form submission to another address , by dynamically setting a buttons OnClientClick property on server side */
function SetFormAction() {
var frm = document.getElementById("form1");
var paybut = document.getElementById("altCtButton1");
var canbut = document.getElementById("altCtButton2");
var altdiv = document.getElementById("divAltContent");
frm.action = "http://www.awebite.com";
paybut.disabled = "disabled";
canbut.disabled = "disabled";
frm.target = "_blank";
altdiv.innerHTML = "<br /><p>Process has been started, please complete in the new browser window and return to the jobs list when done!</p>" +
"<p><a href='/mysite/apage.aspx' class='btnType2' >Jobs List</a></p><br />";
frm.submit();
return false;
}
</script>
So the function above is called on a OnClick event in from a submit button within the browser. It changes the action of form1, disables the button that called it then for paranoia changes the content of the div that contained the button.
Any help with why this function does not work in Firefox would be appreciated.
So, the markup which calls this function is from a div which rendered from vb code behind but looks like this:
<!-- ShowAltContentMessage() Template ASPX Code Block - BEGIN -->
<div id="divAltContent" class="box">
<div class="content">
<input type="hidden" name="altCtStateData" id="altCtStateData" />
<span id="altCtHdrLabel"><P><B>Proceed to Payment Details Entry?</B></P></span>
<span id="altCtBdyLabel"><P>It appears a process was previously initiated however it may have been cancelled, please ensure you are not making a duplicate process.</P></span>
<span id="altCtFtrLabel"></span>
<input type="submit" name="altCtButton1" value="Yes - Process Job" onclick="SetPaymentServiceAction();" id="altCtButton1" class="btnType2" />
<input type="submit" name="altCtButton2" value="No - Abort" id="altCtButton2" class="btnType2" />
</div>
</div>
<!-- ShowAltContentMessage() Template ASPX Code Block - END -->
Whats interesting is if I remove the line of code:
altdiv.innerHTML = "<br /><p>Process has been started, please complete in the new browser window and return to the jobs list when done!</p>" +
"<p><a href='/mysite/apage.aspx' class='btnType2' >Jobs List</a></p><br />";
From the Javascript function everything works in Firefox with the exception of the content updating. I.E the new window or tab opens with the new web address and the buttons get disabled.
As I mentioned this code works perfectly in Chrome, IE and Opera so appears to be a browser specific issue?
Thanks

Related

html, javascript - open a new tab every time a form gets submitted using Post method

I have an html form with a select field where user selects which table we'll show him/her from the mySql database.
<form action = "tableOutput.php" method="post" name="frmTableSelect" target="_blank">
<p>Select a table from the list</p>
<select name="tableName" autofocus>
<!-- here I load a list of tables from mySql. for simplicity let it be: -->
<option>table 1</option>
<option>table 2</option>
<p><br><input name="submit" type="submit" id="knopka" value="show table"></p>
</form>
Like this, when user hits the button, a new tab opens up where the selected table gets printed (I process it in "tableOutput.php") - this is fine.
But the user needs to return to the first form and select another table, that should be printed in another tab, whereas it gets printed in the same tab as the first one replacing it.
In other words, we need to be able to open many new tabs with output.
I inserted this javascript:
<script>
knopka.onclick = function() {
window.open("tableOutput.php")
};
</script>
Now a tab gets open every time one hits the button, but the POST method in "tableOutput.php" does not work anymore, so we get an error while processing the query.
If I write
<script>
knopka.submit = function() {
alert('inside javascript');
window.open("tableOutput.php")
};
</script>
nothing happens, even the alert does not get executed.
Please help.
I am surprised the _blank reuses the same new tab
You cannot use window.open to post to a new window/tab without a lot of code.
Try this:
let cnt = 0;
document.querySelector("[name=frmTableSelect]").addEventListener("submit", function() {
this.target=`win${cnt++}`;
})
Change .submit to .onclick:
document.getElementById('knopka').onclick = function() {
alert('inside javascript');
window.open("tableOutput.php")
};

Restore Window Size on Redirect from PopUp

There is probably a simple solution for this, but I don't know what it is. I have a pop-up window in which I perform a standard Response.Redirect to a new page, based upon a radio-button selection. Everything works as expected, but the new page is the same size as the pop-window (as it is appearing IN the same pop-up window). How would I go about making the new page appear as a normal page and not in the pop-up window?
function EditOrder(f) {
var orderid_values = document.getElementsByName('OrderIDValues');
var orderid_value;
for(var i = 0; i < orderid_values.length; i++){
if(orderid_values[i].checked){
orderid_value = orderid_values[i].value;
}
}
window.open("/memberlogin/orders/editorderpopup.asp?cert=<%=sCertificate%>&loginid=<%=iSessID%>&cid=<%=iCustomerID%>&oid=" + orderid_value,"dialogCancelOrder","resizable=0,scrollbars=yes,location=yes,toolbar=no,status=no,top=200,left=500,width=900,height=900")
}
</script>
Then, in the EDITORDERPOPUP.ASP page, the following redirect occurs based upon the radio button selected (this is just a snippet out of the page):
' Based upon the radio button value (1,2,3.., etc.), call the EDITORDER.ASP page with the "editmode" = to the same value:
sURL = sRootDomain & "/administration/manualordering/editorder.asp?cert=" & sCertificate & "&loginID=" & iSessID & "&EditMode=" & RadioButtonValue
The new page is then displayed in the popup window. I would like the new page to be a completely new window, or be a full window.
Response.Redirect will always occur in same window/tab, so to redirect to another window/tab you should use client and not server scripting.
Example:
Master page that opens popup using client <script>
<button onclick="popup()">Open popup</button>
<script>
function popup() {
window.open('popup.asp', '', 'height=400,width=400');
}
</script>
popup.asp that has nothing but client <script>
<input type="radio" id="a" name="r1" onclick="win1()" />
<input type="radio" id="b" name="r1" onclick="win2()" />
<script>
function win1() {
window.open('https://stackoverflow.com');
}
function win2() {
window.open('https://microsoft.com');
}
</script>

Use form data to update web page

Before I provide a bunch of code I'd like to first find out if what I'm trying to do is even possible.
I've created a web based version of the dice game called PIG using HTML & JavaScript. The user can change some of the game's settings by clicking on a "Settings" button on the main page. This button brings up a modal window containing an HTML form (). I'd like to use the data that the users enters and submits on this form to update various settings on the game's main page.
I chose to use an HTML5 form because was hoping to use the native HTML5 form validation capabilities rather than try and replicate that validation checking logic myself using JavaScript.
So my approach was to use javascript to get the data off the form on submit. I tried two different approaches to get this to work:
1) Using an "onsubmit=function getSettings()" on the tag
2) Using a submit button for the form with an onclick="getSettings()".
With both of these approaches I was able to successfully get all the values from the form on submit and use those values to successfully populate the main game page using the gettSettings() function however when I exit the getSettings() function the webpage values that I updated don't stick...they revert back to the original values regardless of which of these two approaches I use.
I know the values were successfully updated because when I set a break point on the last statement of the getSettings() method I can see that all of the values on the main page have been updated to reflect what was filled in on the form...so I know I'm grabbing all of the data successfully and updating the main page with those values.
I'm puzzled as to why the values that I successfully change on the web page simply revert back to their original value upon exit of the getSettings() function.
Maybe it's just not possible to do what I'm trying to do? And if not does anyone know why given I can see the values are successfully changed before they revert back to their original value. What am I missing?
Again I'm using a Form and collecting the data on submit so that I can leverage the "native" HTML5 form validation capabilities.
Regards.
***** EDIT TO ADD KEY SEGMENTS OF CODE *******
Here is the code HTML Code for the modal form:
<form name="config-settings" onsubmit="getSettings()">
<!-- <form name="config-settings">-->
<span class="errMsg"></span>
<div class="row clearfix">
<div>
<label>Player 1:</label>
</div>
<div>
<input type="text" name="input-name-0" id="input-name-0" maxlength="10" placeholder="Enter name" pattern="^\S+$">
</div>
</div>
<div class="row clearfix">
<div>
<label>Player 2:</label>
</div>
<div>
<input type="text" name="input-name-1" id="input-name-1" maxlength="6" placeholder="Enter name" pattern="^\S+$">
</div>
</div>
<div class="row clearfix">
<div>
<label>Winning Score:</label>
</div>
<div>
<input type="number" name="winning-score" id="winning-score" default="100" placeholder="Enter winning score">
</div>
</div>
<div class="row clearfix">
<div>
<label>Number of Dice:</label>
</div>
<div>
<select name="diceValues" id="dice-value">
<option value=""> - Select - </option>
<option value="dice-1">One Dice</option>
<option value="dice-2">Two Dice</option>
</select>
</div>
</div>
<!-- Below is alt method I used to submit form..yields same results -->
<!-- <input type="submit" value="Submit" onclick="getSettings()">-->
<input type="submit" value="Submit">
</form>
Here are the global variables defined and used in getSettings() method:
// Global variables
var scores, roundScore, activePlayer, gamePlaying, gamesWonCount, playerNames, winningScore, numOfDice, matchScore, msgs;
var player0, player1, score;
var player0Field = document.getElementById('name-0');
var player1Field = document.getElementById('name-1');
var scoreField = document.getElementById('winScore');
Here is the listener for the Settings button on the main web page that brings up the setting modal window containing the settings form:
//*********************************************************
// Open Settings Modal Windows
//*********************************************************
document.querySelector('.btn-settings').addEventListener('click', function () {
// Settings can't be changed if game is actively underway
if (!gamePlaying || roundScore === 0) {
document.querySelector('#modal-settings').style.display = 'block';
} else {
// Make error message visible
msgs.style = 'block';
// Create message to indicate settings successfully updated
msgs.textContent = "Settings can't be updated during game";
msgs.style.backgroundColor = 'pink';
fadeOut(msgs);
}
});
Here is the getSettings() javaScript function (note: there are no local variables defined in this function...they are all defined as global values (first few lines of javaScript app).
function getSettings() {
// Alternative call if I want this function to be called via eventListner
//document.querySelector('.btn-save').addEventListener('click', function () {
console.log("getSettings method called");
player0 = document.forms["config-settings"]["input-name-0"].value;
player1 = document.forms["config-settings"]["input-name-1"].value;
score = document.forms["config-settings"]["winning-score"].value;
// Reset msgs so they will be displayed each time
msgs.style = 'block';
playerNames[0] = player0;
player0Field.innerHTML = playerNames[0];
playerNames[1] = player1;
player1Field.textContent = playerNames[1];
// Set Winning score on UI to value on form
scoreField.textContent = score;
// numOfDice = document.getElementById('dice-value').value;
// Create message to indicate settings successfully updated
msgs.textContent = "Successfully updated settings";
msgs.style.backgroundColor = 'lightgreen';
fadeOut(msgs);
document.querySelector('#modal-settings').style.display = 'none';
}
I don't know exactly what this getSettings() function of yours is supposed to do, but I can try to give you a piece of advice:
Some of the form validation capabilities of HTML5 are not entirely supported on all of the used browsers(some users don't fancy to update their browser). Therefore relying on the "native" validation of HTML5 isn't exactly best practice.
If you want to manipulate the form values in any way before submitting the form I would rather add a listener to the submit button for click events, prevent any other action, make the checks/ manipulation of the form data and then manually submit the form. Anyways, front-end validation isn't entirely safe, so if you're peddling sensitive data it's mandatory that you'll make checks on serverside(if your app uses a server).
To exemplify what I've explained earlier:
document.getElementById("myBtn").addEventListener("click", function(event){
//Stops the form submitting.
event.stopImmediatePropagation();
//Do the checks here.
//Sends the form.
document.getelementById("myForm").sumbit();
);
If you change local variables inside this getSettings() function, the variables will be changed only within the function scope. You might want to read about scope in javascript. (this was just an educated guess).
I hope you find this useful, good luck!
Okay...I finally figured it out! The problem was not a scoping problem but instead and issue with how "onSubmit" works.
The solution involved making two changes:
1) Adding a return statement to the "onsubmit" attribute when calling the "getSettings()" function;
<form name="config-settings" onsubmit="return getSettings()">
2) Returning false at the end of the gettSettings();
return false;
Note: I had previously tried returning true but not false. I was errantly under the impression that returning false value from getSettings() function would disable HTML5 "native" validation and force me to implement all of the error checking myself...which was not what I wanted. It is now my understanding that returning false merely prevents the form from being submitted..but it doesn't disable the HTML5 native validations.
This solution worked perfectly for me because my goal was not to submit the form to the server (as there is no server component here) but merely to use the "native" HTML5 form checking and then update the values on the local web page.
With all of that said I'm still not entirely sure why when I didn't provide the return statement or when I returned true why all of my changes reverted back to their originally value. If anyone can shed some light on why I'd appreciate it.
Cheers

javascript open() method conflict

i am a newbie to js.
i am trying to grab the value of the textbox and display in new page.
but somehow when i click the button it shows the value for a second then redirects to the same form page.
Please tell me where am i doing it wrong? Thanks.
Here is my code
HTML
<div id="myDiv">
<strong>Enter your name in the box below, then click
the button to see a personalized page!</strong>
<br>
<form id="newp" onsubmit="newpage();">
Name: <input type="text" id="yourname" size="25">
<br><br>
<input type="submit" onclick="pressedbutton()" value="Submit">
</form>
<script type="text/javascript" src="main.js"></script>
</div>
JS
function pressedbutton()
{
var thename = document.getElementById("yourname").value;
document.open();
document.write("<h1>Welcome!</h1>");
document.write("Hello, " + thename + ", and welcome to my page!");
document.close();
}
Thanks.
When you call document.open() and then document.write() on an already loaded document, it will clear the current document and replace it with a new empty document.
If you just want to add some content to the current document, then you should use DOM manipulation. Create new elements and add them to the current document.
For example, you could do this:
function pressedbutton() {
var thename = document.getElementById("yourname").value;
var div = document.createElement("div");
div.innerHTML = "<h1>Welcome!</h1>Hello, " + thename + ", and welcome to my page!";
document.body.appendChild(div);
// prevent form submission
return false;
}
In addition, your form is being submitted back to your server which is causing a page reload. You can prevent that by either changing your button to a regular button, not a submit button or by preventing the default behavior of the submit button.
If you don't intend to submit your form, then just change the button from this:
<input type="submit" onclick="pressedbutton()" value="Submit">
to this:
<input type="button" onclick="pressedbutton()" value="Submit">
Please tell me where am i doing it wrong?
You are not preventing the default action of the submit event. When a form is submitted, the browser will load the URL defined in action, or reload the page if none is provided.
If you don't want the browser to do this, you have to prevent it. There are a couple of ways to do this.
You could return false; from the event handler:
onsubmit="return pressedbutton()"
and
function pressedbutton() {
// ...
return false;
}
Or you could call the preventDefault method of the event object:
onsubmit="pressedbutton(event)"
and
function pressedbutton(event) {
event.preventDefault();
// ...
}
Have a look at the excellent articles at quirksmode.org to learn more about event handling. It also describes the differences between browsers.
There's a few issues I see with your code. The one that stuck out to me the most was:
document.open();
document.write("<h1>Welcome!</h1>");
document.write("Hello, " + thename + ", and welcome to my page!");
document.close();
I personally think that anything involving document. is terrible because it overwrites much of the preset code you already had in place in the HTML file.
Instead, you can use:
location.replace(url)
This keeps everything in place, but instead TRULY loads a new page.
On the page that has url, you could either have the same document.write() script (which I do not recomment), OR you can have preset HTML on that page that would have what you're trying to accomplish, which I think is the better method.
Also, this was kind of bugging me:
Change
</form>
<script type="text/javascript" src="main.js"></script>
</div>
to
</form>
</div>
<script type="text/javascript" src="main.js"></script>
It is good practice to keep your scripts at the end of the document, not inside elements.
Regarding storing the value, I would use the following code:
On the first page:
function pressedbutton(){
var thename = document.getElementById("yourname").value;
localStorage.setItem("Name", thename);
location.replace("Page2.html");
}
In Page2.html (same folder), place similar code to what you had (in the javascript):
<script>
var div = document.createElement("div");
div.innerHTML = "`<h1>`Welcome!`</h1>`Hello, " +
localStorage.getItem("Name") +
", and welcome to my page!";
document.body.appendChild(div);
</script>

observe form submit response targetting an iframe

I have an app which runs in a new window. There are several forms to generate a PDF export. When I submit one of these forms, the window loses its focus and the original window pops up again when the download appears.
I created an iframe, so the forms can target the iframe and the current window doesn't lose its focus. It works great, but I have no idea how to observe the response inside the iframe if everything went right.
Here is how its working so far. I'm using prototypeJS.
<iframe id="pdf_frame" name="pdf_frame" style="display:none;"></iframe>
<form id="PDF_gen" name="PDF_gen" target="pdf_frame" action="pdf.pl">
<input type="hidden" name="size" value="">
<!-- more hidden inputs -->
</form>
<input type="button" id="pdf_submit" value="generate pdf">
JS:
$('pdf_submit').observe('click', function(){
//write stuff to hidden inputs
$('PDF_gen').submit();
});
If something goes wrong, the download dialogue does not appear. When using prototypes form.request() the browser does not know how to handle the response and does not bring up the download dialogue. How can I do it right?
Thanks in advance!
When something goes wrong in the iframe you can try to fire an event from the iframe to its parent window (assuming we're on the same domain; it won't work cross-domain):
parent.document.fire('something:went_wrong')
and have the parent document listen for that event:
document.observe('something:went_wrong', function() {...});

Categories

Resources