Setting innerText with Javascript only applies momentarily - javascript

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;
}

Related

Chrome Extension Append Input to URL.

I'm currently creating a Chrome Extension that has a popup.html and in that pop up is 2 things. An input field and Submit button.
The Input field takes a EXTN number from a user and when submitted is pressed I need to then navigate the user to a new tab appending the Input from the user to the end.
Input = 9999 when submit is pressed user is taken to: Submit = http://name.com/9999
I have this working with when just use the HTML file but it doesn't seem to do anything when loaded into Chrome as an Extension.
Here is my code for the input and onClick:
Popup.HTML
<script src="popup.js"></script>
<input type="text" id="page" />
<input type="submit" value="submit" onclick="goToPage();" />
popup.js
function goToPage() {
var page = document.getElementById('page').value;
window.location = "http://name.com/" + page; }
I understand that you can't run in line JS so I've called it out from the popup.js file but its still not working.
You can't use inline JS in Chrome extension (the onclick="goToPage();" in the input element is considered inline Javascript) . You have to put all your Javascript code in a separate file.
You will need to use chrome.tabs API to open a new tab. For example:
popup.html
<input type="text" id="page" />
<button id="submit">Submit</button>
<script src="popup.js"></script>
popup.js
document.getElementById('submit').onclick = function(){
var page = document.getElementById('page').value;
chrome.tabs.create({url:'http://name.com/' + page});
}

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>

Strange issue with jQuery.get()

I'm having a strange behaviour with this code:
<script type="text/javascript">
function get()
{
alert("gggg");
jQuery.get (
"http://localhost:8080/c/portal/json_service",
{
serviceClassName: "com.liferay.test.service.TrabajadorServiceUtil",
serviceMethodName: "findByName",
servletContextName: "TrabajadorPlugin-portlet",
serviceParameters: "[param]",
param : document.getElementById("nombre")
}
);
}
</script>
<div>
<form>
<input type="text" id="nombre" value="<%=searching%>"/>
<input type="button" value="Submit" onClick="javascript:get()"/>
</form>
</div>
Liferay portal gets blocked when the button "Submit" is pressed. The pop-up with the message "gggg" is showed, but after click ok on it, the page becomes blocked.
If I remove the line 'param : document.getElementById("nombre")', it doesn't block.
Can anyone explain me where is the error, or the reason of this behaviour?
Thanks in advance,
Rafa
The problem is that you're trying to pass an entire DOM element as the value for param, which jQuery isn't going to like. What type of element has ID nombre, and what property from that element do you want? If it's some kind of input, you likely want the value property, so you'd do:
param : document.getElementById("nombre").value
Updated Answer:
Thinking this through a little more, you should probably do this in a different way altogether. You're sending the data when the user clicks on the submit button, but remember if a user hits enter while typing in the input text box the form will submit but your code will not catch that.
A more robust solution would be to do it this way instead:
<div>
<form id="nombre_search">
<input type="text" id="nombre" value="<%=searching%>"/>
<input type="submit" value="Submit"/>
</form>
</div>​
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$("#nombre_search").submit(function(){
$.get("http://localhost:8080/c/portal/json_service", {
serviceClassName: "com.liferay.test.service.TrabajadorServiceUtil",
serviceMethodName: "findByName",
servletContextName: "TrabajadorPlugin-portlet",
serviceParameters: "[param]",
param : $("#nombre").val()
});
return false;
});
});
</script>
Changes to your code:
Added an id to the form.
Made the submit button a submit button instead of just a button.
Placed code inside $(document).ready block.
Code runs when form is submitted not when button is clicked.
Hope this helps,
Sandro

How do I dynamically update an iframe using Javascript or jQuery

I am developing a page in with a text box, a submit button, and an iframe.
The URL should be put in the text box. Upon hitting the button, the result should appear in the iframe.
How do I do this?
You should not need JavaScript at all. Set the target attribute of your form to the name of the frame, and it will load there.
See also the duplicate How do you post to an iframe?.
Here is a quick solution for now using js
<form target="#" name="iframeform" action="post">
<input type="text" value="http://" name="framefood" id="framefood" /><br />
<button id="feedframe" onclick="completeFrame(); return false;">Send</button><br /><br />
<iframe id="feedme" width="600" height="400"></iframe>
</form>
<script>
var completeFrame = function(e){
var feidlId = document.getElementById("framefood");
var frameSrc = feidlId.value;
var frameId = document.getElementById("feedme");
frameId.src = frameSrc;
}
</script>

document.write to current HTML page

I am a noob to programming, so I'd appreciate any advice from you more knowledgeable folks out there. I am working on a bit of javascript for a web page and I need the javascript to print to that current HTML page, preferably in the div tag I have set up for that purpose. Here's what I have so far:
<html>
<head>
<title>Tardy Reporting</title>
<script src="students.js" type="text/javascript">
</script>
</head>
<body>
<h1>Scan in Student ID</h1>
<form method="POST" name="idForm" onSubmit="getId(parseInt(document.idForm.studentId.value));">
<input type="text" name="studentId" id="studentId"/>
<input type="Submit" name="Submit" />
</form>
<div id="div1"></div>
<p>
</body>
</html>
and my JS file:
var studentNumberArray = [50011234, 50012345, 50013456];
var studentNameArray = ["Mike Simpson", "Greg Pollard", "Jason Vigil"];
var studentLastPeriodArray = ["George Washington", "Darth Vadar", "Obi Wan Kenobi"];
var tardyArray = [0, 0, 0];
function getId(studentId) {
for (i = 0; i < studentNumberArray.length; i++){
if(studentId === studentNumberArray[i]){
tardyArray[i] += tardyArray[i] + 1;
document.getElementById('div1').innerHTML='test';
}
}
}
Mind you, this is just the basic framework, so it's not nearly done yet, but the thing that is bugging me is that it'll go through the code correctly and print it out, but the result only lasts a fraction of a second on my browsers (chromium and firefox). Any help would be appreciated.
Here is an easier/better way to accomplish what you are trying to do
var students = {};
// Add students to object
students[50011234] = { 'id': '50011234', 'name':"Mike Simpson", 'lastPeriod':"George Washington", 'tardy':0 };
students[50012345] = { 'id': '50012345', 'name':"Greg Pollard", 'lastPeriod':"Darth Vadar", 'tardy':0 };
students[50013456] = { 'id': '50013456', 'name':"Jason Vigil", 'lastPeriod':"Obi Wan Kenobi", 'tardy':0 };
function getId(studentId) {
students[ studentId ].tardy += 1;
document.getElementById('div1').innerHTML='test';
}
Also, as pointed out below, you should change your button to not submit if that is not what you are intending to happen:
<form method="POST" name="idForm">
<input type="text" name="studentId" id="studentId"/>
<input type="button" onclick="getId(parseInt(document.idForm.studentId.value));" name="Mark Tardy" />
</form>
The reason why you see it only for a fraction of a second is that you are actually causing a submit. A submit is a full call back to the server which returns the page to its initial status.
To fix this simply make the function call on the onclick event of the button:
<html>
<head><title>Tardy Reporting</title>
<script src="students.js" type="text/javascript"> </script>
</head>
<body>
<h1>Scan in Student ID</h1>
<form method="POST" name="idForm" >
<input type="text" name="studentId" id="studentId" />
<input type="button" onclick="getId(parseInt(document.idForm.studentId.value));" value="submit" />
</form>
<div id="div1"></div>
<p>
</body>
</html>
What do you mean by "result"? It appears that you are setting the innerHTML of div1 to "test" over and over again.
Perhaps you mean to write
document.getElementById('div1').innerHTML += 'test';
Doing this is not efficient and it is preferable you concatenate on a string, or even better, join an array, before assigning the innerHTML.
but the result only lasts a fraction of a second on my browsers (chromium and firefox).
That is because you are submitting the page, so the page gets refreshed. You need to change the button type to button from submit. Also add a onclick to the button and call the js function getId
Forms are a special construct that allows communication with a server:
When a form is submitted, the form data is "POSTED" to a server via an HTTP request.
Typically, the browser displays the server's response as a new web page.
Forms use the action attribute to specify which server page should process the request
In your case, no action is specified, so the form POSTS to the current page, which is equivalent to refreshing the page. This means that all client-side (JavaScript) changes are wiped out, which is why you only see them for a split-second.
To achieve your desired result, change the input type from submit to button:
<input type="button" onclick=".." value="submit" />
Ideally, the student data exists in a database that is manipulated by code on a server. Your form would POST a request that returns an HTML page containing the desired data.
References
HTTP
Forms

Categories

Resources