javascript open() method conflict - javascript

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>

Related

Link user input with login button

I would like to create a sort of login page. Which links to a href depending on the input of the user.
So i have a text input part and a login button.
Then it should go to the website depending on the text input.
Example: users fills in 1234 and clicks on the login button, then the website:
example.com/1234 opens up.
I tried but i cant get it worked.
<input type=text id='token' name="token"/>
<input type=button name=login value="login" onClick=changeQuery()/>
changeQuery(){
var input_query=document.getElementById('sq').value;
window.location="http://www.google.com/"+input_query+"myString";
}
There are many issues with your code...
HTML attribute should be in quotes (so change things like onclick=changeQuery() to onclick="changeQuery()")
Your function does not start with the keyword function
Your textbox control has an id of token... so in the example you have, there is no sq for the getElementById to find
And I'm not sure why you're adding "MyString" at the end of the URL, but that might be part of your intended code
The result should be something like this...
function changeQuery(){
var input_query = document.getElementById('token').value;
//window.location = "http://www.google.com/" + input_query + "myString";
console.log("http://www.google.com/" + input_query + "myString");
}
<input type="text" id="token" name="token"/>
<input type="button" name="login" value="login" onClick="changeQuery()"/>
(Please note, I've commented out the window.location and instead put a console.log so you can see what is produced without it actually navigating to another page)
function changeQuery() {
var input_query =
document.getElementById('token').value;
window.location = "https://www.google.com/search?
q=" + input_query;
}
Above is the correct code for what you want, but google doesn't allow some different origin to make search request.
Refused to display 'https://www.google.com/search?q=somequery' in a frame because it set 'X-Frame-Options' to 'sameorigin'.If you try to redirect some other origin it will work.

Using an input to search a local webpage in HTML

I'm stuck on this problem for now a couple of days and I have no idea what to do. I want to navigate directly to another page from my own website only by writing the page name(without the ".html" or ".php" in the input.
Example: you write "index" in the textbox and once you click on the submit button it sends you to "http://www.website.com/index.html". Instead of doing that, it sends me to "http://www.website.com/?2016=index&.=html"
I got it totally wrong because it sends the input names and some symbols around them.
This is my HTML code:
<form id="newsearch" method="get" action="http://www.website.com/">
<p>Enter your confirmation number:</p>
<input type="text" id="searchvalue" class="textbox1" name="2016" size="50" maxlength="120"><input type="submit" class="button1" value=">">
<input type="hidden" id="hiddenvalue1" name="." value="html">
</form>
Your current code simply submits a form, so it is quite correctly adding the entered value as part of the query string ?2016=index&.=html".
To navigate to the location, add a submit handler to the form that cancels the default form navigation and instead sets window.location to the relevant value, perhaps something like this:
document.getElementById("newsearch").addEventListener("submit", function(e) {
e.preventDefault();
var searchText = document.getElementById("searchvalue").value;
var extension = document.getElementById("hiddenvalue1").value;
window.location = this.action + searchText + "." + extension;
// or if you don't want to use the form's action attribute to specify
// the domain you could hardcode it in the function:
// window.location = "http://www.website.com/" + searchText + "." + extension;
});
(Update: the above code would need to be in a script element that is after the form element, and/or in a DOMContentLoaded or window.onload handler.)

assist with js function/alert erasing form input

I came across something weird that is making me realize I do not know JS stuff as well as i should. And so I thought I would ask a question about what is going on to see if that will help. I have a simple form with three "textarea" inputs and i have a "save" button. the save button triggers a js function that gathers the what is on the inputs and the does an alert showing them...
very simple application but what I was not expecting was that when you "close" the alert box; all the data entered on the form is erased...
here is my code:
<form>
<strong>Make</strong><br/>
<textarea id="make_notes" rows="4" cols="50">
</textarea><br/><br/>
<strong>Model</strong><br/>
<textarea id="model_notes" rows="4" cols="50">
</textarea><br/><br/>
<strong>Features</strong><br/>
<textarea id="features_notes" rows="4" cols="50">
</textarea>
<br/><br/>
<button onclick="side_form_js2()">Save2</button>
</form>
<script>
function side_form_js2() {
var element1 = document.getElementById("make_notes");
var make_notes_var = element1.value;
var element2 = document.getElementById("model_notes");
var model_notes_var = element2.value;
var element3 = document.getElementById("features_notes");
var features_notes_var = element3.value;
alert(make_notes_var + "I am an alert box!22222" + model_notes_var + features_notes_var);
}
</script>
So I am really uncertain what is making the form input be erased. It is almost like the page is being reloaded but I dont think that is the case. Can anyone shed any light on this? Thanks...
P.S. dont know if this makes any difference but just running this locally using Xampp on my PC...
the default is reload, change your code to this and it should work
<button onclick="return side_form_js2()">Save2</button>
and then in your function add return false after the alert like this:
alert(make_notes_var + "I am an alert box!22222" + model_notes_var + features_notes_var);
return false;
A button element with no type attribute specified represents the same thing as a button element with its type attribute set to "submit".
If you want to use a button in a form without it submitting use type="button".

Setting innerText with Javascript only applies momentarily

So I am learning Javascript, and I'm having a problem:
I can set the innerText of a paragraph element. But immediately the web-browser undo's my work!! Meaning the web-page completely reverts back to the state it was in as if I had loaded the page afresh.
<html>
<body>
<form>
<input type="submit" onclick="GetCurrentLocation()" value="Get Current URL" />
</form>
<p id="CurrentURL">Current URL:</p>
<script>
function GetCurrentLocation()
{
var myCurrentLocation = window.location.href;
var curLocP = document.getElementById("CurrentURL");
curLocP.innerText = "Current URL: " + myCurrentLocation;
}
</script>
</body>
</html>
So above I set the innertext in the last line of the function, and in the UI I can see the correct, expected text:
Current URL: C:\Users...\Projects\test.html
flash and then disappear simply leaving me with:
Current URL:
I'm running this on Google Chrome.
Browser submits the form and refreshes the page. That's why you loose changes. Change your input type from submit to button
<input type="button" onclick="GetCurrentLocation()" value="Get Current URL" />
Add a return:false to your JavaScript to prevent the form from being submitted and reloading the page (and making it look like the change disappears when in reality it's just reloading):
<input type="submit" onclick="GetCurrentLocation();return false" value="Get Current URL" />
jsFiddle example
The browser submits the form that's why the refresh happens.
If you need to use a submit button you can use event.preventDefault()
function GetCurrentLocation(event)
{
event.preventDefault();
var myCurrentLocation = window.location.href;
var curLocP = document.getElementById("CurrentURL");
curLocP.innerText = "Current URL: " + myCurrentLocation;
}

Javascript/HTML > Form/Input > automatic firing every time a page loads

I had to take my working example here. For some reason, it does not work as easily as the initial example.
New Example
Suppose I want to see M5s every time the page loads. So how can I fire the same query for M5 every time the page load?
I copied the critical part here:
<body>
<div id="search">
<form onSubmit="makeRequest(1); return false;" style="margin: 2px; padding: 2px; font-size: 1.2em;">
<input id="searchinput" type="text" name="tags" size="20" value="">
<input id="searchbutton" type="button" onClick="makeRequest(1);" value="Create VideoWall"><br />
...
</form>
</div>
Response to the idea in MiffTheFox's and Tom's reply
So I added the command before the form above:
<body onload="document.getElementById('myform').submit();">
However, the wall stays black. It should be full of M5s.
Emerged problem to the initial Question: Why does it not work? Why does the wall stay black?
makeRequest asked by Tom
function makeRequest(page){
startrequest = 0;
for(i =1; i < 4; i++){
clearList('ul'+i);
var tags = encodeURI(document.getElementById('searchinput').value);
if(i == 1 || i == 2){
quantity = 45;
}
if(i == 3){
quantity = 36;
}
insertVideos('ul'+i,'search',tags,quantity,startrequest);
startrequest = startrequest + quantity;
}
}
Please, see the url at the top and press CTRL+U to see the code.
Well, thereĀ“s on load attribute inside the body element
<body onload = "javascript:doSubmit()">
...
</body>
<script>
function doSubmit(){
var form = document.getElementById("myform");
if (form !=null)
form.submit();
}
</script>
Also, you could add javascript at the end of your html page. This is not as portable as the first option
<html>
<body>
<form id="myForm" ...>
...
</form>
<script>
//this executes when the page finishes loading
var form = document.getElementById("myForm");
if (form!=null) form.submit();
</script>
</body>
</html>
First add an ID to the form, then add an onLoad handler that submits it.
<body onload="myForm.submit();">
<form id="myForm" name="input" action="form_action.asp" method="get">
...
Not sure what you're trying to accomplish, but you can certainly use jQuery to do
$(document).ready( function() {
$("#submitButton").click();
});
The problem is ensuring that this only happens the first time the document is submitted; you will need to keep track of that on the server-side and remove the submission code after the first time.
A better approach is probably to compose your HTML on the server side so that whatever initial state you want to display is displayed. Many web applications have a form to submit a query of some kind (say, a search) but start with some initial sample result below the form. This is just created on the server side before loading, not by "pre-submitting".

Categories

Resources