I cant change text using javascript? - javascript

Im working on a simple commenting system for a website using the postmail API. The thing is that i want to give the user a better error when something goes wrong because postmail only changes the URL. For this is i check the URL of the page when the page loads and if that contains an error i want to change a element to that error. The only problem is that detecting it works fine and i can also create a alert with the error but the text wont change... Can anyone help me with this?
js:
<script>
function sending(){
document.getElementById("submit_form").value = 'Sending...';
};
if (window.location.href.indexOf("err") != -1){
alert("An error occured! Please make sure to check your input fields."); //this works fine
document.getElementById("ertext").innerHTML = 'Error!'; //this doesnt
};
</script>
HTML:
<form action="https://postmail.invotes.com/send"
method="post" id="email_form">
<h2>Feedback</h2>
<h4>Your Email:</h4>
<input type="text" name="subject" placeholder="aa#aa.aa" style="width: 80%;"/><br>
<h6>Your Message:</h6>
<textarea name="text" placeholder="Give some feedback" style="resize: none; width: 80%;"></textarea>
<input type="hidden" name="access_token" value="--" />
<input type="hidden" name="success_url" value="./comments.html" />
<input type="hidden" name="error_url" value="./comments.html?err=1" /><br><br>
<input id="submit_form" type="submit" value="Send" onclick="sending();" />
</form>
<p id="ertext"></p>
<br> <br>```

The Javascript code needs to be executed after the html document is loaded. As mentioned before you can achieve this by putting the script tag somewhere below all referenced elements in your DOM.
Another possibility is to put your JavaScript into a separate file "test.js" and then include it in the head of your document:
<script type="text/javascript" src="test.js" defer></script>
Using the defer attribute makes sure the script will be executed after the page finished parsing.

It depends on where you put the script. If you put it before the DOM element, document.getElementById("ertext") wouldn't find the element.
<script>
// before the DOM element
// Below line would raise TypeError: Cannot set property 'innerHTML' of null
document.getElementById('ertext').innerHTML = location.href;
</script>
<h1 id="ertext">the element</h1>
<script>
// after the DOM element
// You'd see `the element after` which indicates
// the script that is after the DOM element can find the element.
document.getElementById('ertext').innerHTML += ' after';
</script>

Related

html onclick keeps redirecting to a function of javascript

Im calling a function from onclick of a button. When i press the button it executes my function deletes everything from the screen and displays the button inside my function. Everything works ok but why does it delete everything from screen. How to make it for it to only run the function but keep previous html elements prior to clicking the function?
<div id="form-container">
<form id="dim_form" action="">
<div class="bg">
<label class="form-label-a" for="dimm">Dimension</label>
<input id="dimm" type="text" />
</div>
<div class="bg">
<label class="form-label-b" for="dimm_upper">Upper tolerance</label>
<input id="dimm_upper" type="text" required />
</div>
<div class="bg">
<label class="form-label-c" for="dimm_lower">Lower tolerence</label>
<input id="dimm_lower" type="text" required />
</div>
<div class="bg">
<input class="form-button" type="submit" onclick="data_table();" value="Calculate" />
</div>
</form>
</div>
data_table()
document.write("<input class='download' type='button' id='button-a' value='download xls' />");
I tried with "button" instead of submit. return false, basically everything i found on google and nothing works for me.
The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML.
When this method is not used for testing, it is often used to write some text to an output stream opened by the document.open() method. See "More Examples" below
see the full documentation here: https://www.w3schools.com/jsref/met_doc_write.asp
if you want to add some nodes without cleaning the whole HTML try append
https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/append
document.write will erase everything you had earlier. Instead use append.
function data_table() {
const input = document.createElement('input');
input.type = "submit";
input.id = "button-a";
input.value = "download xls";
document.querySelector('.bg').appendChild(input);
}
<div class="bg">
<input class="form-button" type="submit" onclick="data_table();" value="Calculate" />
</div>
Document is referred to the entire html page when you are trying to do document.write it will write on the entire page....
There can be couple of work arounds but i will suggest this one
Give class to the element you want to add element to.
Get element by the class you assign to the element in first step
var x = document.getElementsByClassName("example");
if you want to keep whats already there
x.appendChild("whatever you want to add goes here");
if you want to add only new element and discard everything previously present
x.innerHtml="whatever you want to add goes here";

Cannot see any output on console on using onclick property?

When I type anything and then click on submit button it doesn't show anything in my console what am I missing.
<body>
<form name="fetch-movie-title" id="fetch">
<input type="text" placeholder="Enter a movie title" id="term" />
<input type="submit" onclick="showdata()" id="search" value="Find me a poster" />
</form>
<script type="text/javascript">
function showdata() {
var film = document.getElementById('term').value;
console.log(film);
}
</script>
</body>
When I run that code I get this error displayed in the console:
Uncaught SyntaxError: Unexpected token <
… because you swapped the position of the </script> and </body> tags.
Since you say you see nothing, the problem is most likely because you run the code when the submit button is clicked.
The JS will run then the form will submit and a new page will load.
Unless you configure your console to Preserve log, this will clear the console and erase any messages displayed there.
Change the configuration.
if the body tag is inside the script tag you will be getting a parser error so the function won't be defined when the click happens.
Alternatively, you aren't preventing the form submission so the page might be reloading before you get a chance to see the output.

How do I use the <form> tag to send data to a javascript function?

I was testing and trying to make an little form that when the user entered their name, it would take that name and display it on to the screen.
<html>
<head>
<center><h1>Test-Page</h1></center>
</head>
<body>
<div class="someRandomStuff">
<h2 id="testingID">What is your first name?</h2>
<form name="input" action="login.js" method="post">
Name: <input type="text" name="userID"/>
<input type="submit" value="Submit"/>
</form>
</div>
</body>
Here is the js file
function displaySystem(name) {
document.getElementById("testingID").innerHTML("Ah, hello there" + name)
}
I know that I could probably do this in one HTML file, however I want to try and make the js and HTML separate. ANY help is appreciated.
You don't send data to a JavaScript function, but a JavaScript function can retrieve form data.
For example, and input of type text can be retrieved using its value property:
var input = document.getElementById("userID");
var value = input.value;
I know that I could probably do this in one HTML file, however I want
to try and make the js and HTML separate.
Nice step. In fact, there's no practical difference in terms of retrieving form data or manipulating the document from an inline script or a script that's included using a <script src=... element. The main difference is a script embedded in the HTML document won't be cached, while a one included as a separate file will be cached (obviously, there're other reasons if we talk about good separation of concerns!).
use onkeypress event on textbox and pass this to display that value and use that parameter in function to display it
<div class="someRandomStuff">
<h2 id="testingID">What is your first name?</h2>
<form name="input" action="login.js" method="post">
Name: <input type="text" name="userID" onkeypress="displaySystem(this)"/>
<input type="submit" value="Submit"/>
</form>
</div>
//javascript function
function displaySystem(name) {
document.getElementById("testingID").innerHTML("Ah, hello there" + name.value)
}

Javascript Form Input Retrieval

Why is it that in a form that contains a Text Box and a Submit Button, I can Alert what has been typed in the text box by the user, but can't print it on the page? What am I doing wrong?
Here's the code
<form name="Serb" action="" method="get">
<input name="Name" type="text" size="15" maxlength="20" />
<input name="Join" type="submit" value="Join" onClick="serb(this.form)" />
<script type="text/javascript">
function serb(form){
var x = document.Serb.Name.value;
alert(x); \\this alerts
document.write(x); \\this should print on page
}
</script>
For some reason, the alert works fine and displays exactly what the user typed in the username box after pressing 'Join'. However, it won't print the information on the page. Why is that?
It does work. The value in the textbox is printed on the page.
BUT:
\\ do not mean anything in Javascript. Comments begin with //. This is most likely the reason why you are not seeing the value being written
document.write replaces whatever is in the HTML page with its argument. (If it is called after the document is loaded). So unless you are trying to learn Javascript this is not a very good idea.
Actually it is not a very good idea to use it even when learning Javascript, unless you are trying to learn how document.write works.
There are flexible (and better) ways to manipulate the content of a page, starting from the humble getElementById to complex DOM manipulation
It is not a good idea to use document.write() after the page has been loaded/parsed. At that point, it will overwrite the page HTML with new content. document.write() is generally used while the page is being loaded to insert content at a particular point into the page as it's being loaded.
If you want to put the value into some item on the page, then you need to use appropriate DOM methods for that, putting the value into an input field, setting the innerHTML on a div, etc...
You can read about document.write here: https://developer.mozilla.org/en/document.write.
Here's an example of fetching the value from the field and putting it in another object on the page without using document.write(): http://jsfiddle.net/jfriend00/dU8Sr/.
HTML:
<form name="Serb" action="" method="get">
<input name="Name" type="text" size="15" maxlength="20" />
<input name="Join" type="button" value="Join" onClick="serb(this.form)" />
</form>
<br>
<br>Output: <span id="output"></span>
Javascript:
function serb(form) {
var x = document.Serb.Name.value;
document.getElementById("output").innerHTML = x;
}

How to run Javascript codes that are put in a textbox (in HTML5)

I have a textbox on my html page, I'd like to run the javascript code that people put it the textbox. How can I do that?
You can create a new script dynamically like found here
Here's a quick example you can copy and paste into an html file and see it work. You'll notice that once called, the page reloads and stalls out. This could be solved by using ajax and a seperate page the executes the code and returns a value or string or whatever it is your code should return.
<html>
<head>
</head>
<body>
<script>
function doIt() {
var headID = document.getElementsByTagName("head")[0];
var newScript = document.createElement("script");
newScript.type = "text/javascript";
newScript.innerHTML = document.getElementById("textarea").value;
headID.appendChild(newScript);
}
</script>
<textarea name="textarea" id="textarea">
alert("Alert");
</textarea>
<input type="button" value="Do It" onclick="doIt();" />
</body>
<html>
You can use document.getElementsByName
<input name="textbox" type="text" />
<input name="buttonExecute" onclick="execute(document.getElementsByName('textbox')[0].value)" type="button" value="Execute" />
something similar i found here
You could also create a JavaScript function to get the content using jQuery and execute the code you wanted but you must set an id to the textbox
<script>
$("#run").click(function () {
var element = $("input#textbox").val();
//code to execute
}
</script>
<input type="textbox" value="Type something" id="textbox"></input>
<button id="run">Run Code</button>
I think the easiest native JS way to do it is to use a textbox's value attribute and eval() its content, as it doesn't require to create any script elements (that would be sitting there until the page is reloaded) or big constructs:
function runIt() {
eval(document.getElementById('code-input').value);
console.log('Ran code from textbox!');
}
<textarea id="code-input" placeholder="Input any JS code here"></textarea>
<button onclick="runIt()">Run it!</button>
This example is a text box and with every click on the button "Run it!" the text that's inside of it is executed as JavaScript.
In fact this answer is just a complicated way to say: "Just eval() a textbox's value."

Categories