Javascript innerHTML is automatically overwritten and nullified [duplicate] - javascript

This question already has answers here:
Clicking a button within a form causes page refresh
(11 answers)
Closed 1 year ago.
I was just practising HTML DOM and Forms, and I wrote a simple code, in which we take values from the form and display them in a <p> tag :
<html>
<head>
<title>Return first</title>
</head>
<body>
<p id="demo">hi</p>
<form id="myForm" name="myForm" onsubmit="getFormvalue()">
First name: <input type="text" name="fname" value="David"><br>
Last name: <input type="text" name="lname" value="Beckham"><br>
<input type="submit" value="Submit">
</form>
<script>
function getFormvalue() {
var x = document.getElementById("myForm");
var text = "";
for (var i = 0; i < x.length; i++) {
if (x.elements[i].value != 'Submit') {
text += x.elements[i].value + " ";
}
}
document.getElementById("demo").innerHTML=text;
}
</script>
</body>
</html>
The problem is that when I press submit, the "hi" is replaced by " David Beckham " just for a millisecond, and is again changed to "hi". So by pressing submit continuously, I can see the text being changed again and again.
I don't understand what is happening, It is working, but it is not working. I don't see any errors in the code. Maybe it's code-related, or browser-related, or machine-related.
function getFormvalue() {
var x = document.getElementById("myForm");
var text = "";
for (var i = 0; i < x.length; i++) {
if (x.elements[i].value != 'Submit') {
text += x.elements[i].value + " ";
}
}
document.getElementById("demo").innerHTML=text;
}
<html>
<head>
<title>Return first</title>
</head>
<body>
<p id="demo">hi</p>
<form id="myForm" name="myForm" onsubmit="getFormvalue()">
First name: <input type="text" name="fname" value="David"><br>
Last name: <input type="text" name="lname" value="Beckham"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
I don't why, but it is working in this snippet, but now in my browsers. I am using Macbook Air. I tried running it on both Safari and Chrome. Any help would be appreciated.

That is because onsubmit it will submit the form and refresh the form. So stop the default behaviour using event.preventDefault
function getFormvalue(e) {
e.preventDefault();
var x = document.getElementById("myForm");
var text = "";
for (var i = 0; i < x.length; i++) {
if (x.elements[i].value != 'Submit') {
text += x.elements[i].value + " ";
}
}
document.getElementById("demo").innerHTML = text;
}
<p id="demo">hi</p>
<form id="myForm" name="myForm" onsubmit="getFormvalue(event)">
First name: <input type="text" name="fname" value="David"><br> Last name: <input type="text" name="lname" value="Beckham"><br>
<input type="submit" value="Submit">
</form>

You need to prevent form submision
function getFormvalue() {
var x = document.getElementById("myForm");
var text = "";
for (var i = 0; i < x.length; i++) {
if (x.elements[i].value != 'Submit') {
text += x.elements[i].value + " ";
}
}
document.getElementById("demo").innerHTML=text;
}
<html>
<head>
<title>Return first</title>
</head>
<body>
<p id="demo">hi</p>
<form id="myForm" name="myForm" onsubmit="event.preventDefault(); getFormvalue()">
First name: <input type="text" name="fname" value="David"><br>
Last name: <input type="text" name="lname" value="Beckham"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Related

Javascript/InnerHTML add and get integer values

I have been trying to get the values from the textView box but it's not displaying in the p field at all, and also I am trying to add the 2 values together into one value and display it.
function() {
var x = document.forms["frm1"];
var text = "";
var i;
for (i = 0; i < x.length ;i++) {
text += x.elements[i].value + x.elements[i].value;
}
document.getElementById("demo").innerHTML = text;
}
<h2>Finding HTML Elements Using document.forms</h2>
<form id="frm1" action="/action_page.php">
First name: <input type="text" name="fname" value="123"><br>
Last name: <input type="text" name="lname" value="123"><br><br>
<input type="submit" value="Submit">
</form>
<p id="demo"></p>
You need to call the function on the document load. And make these changes inside the function
var myValue = 0;
for (i = 0; i < x.length; i++) {
if (x.elements[i].type === "text")
myValue += Number(x.elements[i].value);
}
document.getElementById("demo").innerHTML = myValue;
Try this. In your code.
document.getElementById("demo").innerHTML =
myfunction(document.forms["frm1"]);
should be called outside the function. Also, you should include a name for the function you've created.
function myfunction(input) {
var text = "";
for (var i = 0; i < input.length; i++) {
text += input[i].value;
}
return text;
}
document.getElementById("demo").innerHTML = myfunction(document.forms["frm1"]);
<h2>Finding HTML Elements Using document.forms</h2>
<form id="frm1" action="/action_page.php">
<label>First name:</label> <input type="text" name="fname" value="123" /><br>
<label>Last name:</label> <input type="text" name="lname" value="123" /><br><br>
<input type="submit"/>
</form>
<p id="demo"></p>

Keeping value of search box Javascript/HTML

I made a tool which make my work a little easier by inserting a value into a url in a new window on multiple sites. It was working quite well but now I am having the problem of the search value being cleared onsubmit.
Javascript:
<script language="JAVASCRIPT">
function run() {
var request = document.text.query.value;
var req = "";
var endofurl = "endofurl.html";
for(var i = 0; i < request.length; i++) {
var ch;
if((ch = request.substring(i, i + 1)) == " ") req += " ";
else req += ch;
}
if(document.search.website.checked) {
var website = open( "https://www.website.com/" + req, "website");
}
//--></script>
HTML:
<form name="search">
Please select the networks you want to use.
<p>
</center>
</p>
<div class="row">
<div class="column">
<br>
<input name="website" type="checkbox">Website to Search
<form name="text" onsubmit="run(); return false;">
<center>And enter your Query.</center>
<center>
<input name="query" placeholder="Steropodon" value="" size="50" type="TEXT">
<input value="Search" onclick="run()" type="BUTTON">
</center>
So far, return false had been working to keep the value of the input in the form="text" input name="query" but now it seems to clear it and reload the page. I'm not sure what changed.
You have errors in your code opening and closing the tags.
Try this code. It works:
<html>
<head></head>
<body>
Please select the networks you want to use
<div class="row">
<div class="column">
<br>
<input name="website" type="checkbox">Website to Search
<form name="text" onsubmit="run(); return false;">
<center>And enter your Query.</center>
<center>
<input name="query" placeholder="Steropodon" value="" size="50" type="TEXT">
<input value="Search" onclick="run()" type="BUTTON">
</center>
</form>
</div>
</div>
<script language="JAVASCRIPT">
function run() {
var request = document.text.query.value;
var req = "";
var endofurl = "endofurl.html";
for(var i = 0; i < request.length; i++) {
var ch;
if((ch = request.substring(i, i + 1)) == " ") req += " ";
else req += ch;
}
var checkbox = document.getElementsByName("website");
if(checkbox[0].checked) {
var website = open("https://www.website.com/" + req,
"website");
}
}
</script>
</body>
</html>
Hope it helps.
I fixed it. It was not the tags. I had only pasted a small amount of the total code to make it easier to read but I failed at making it easier to read. The problem was undefined inputs. I have been adding many if statements but didn't have a corrosponding checkbox. Oops.
Thanks for the help.

Loading Values into auto generated HTML input elements using javascript

I am using a javascript function to populate html element generated automatically after submitting a form from a different div.
Here is the html:
<html >
<body>
<div class="wrapper">
<div id="one">
<form name="form">
<fieldset>
<legend>BILLING</legend>
<div> <label for="ex1">Procedure/Drug</label>
<input type="text" name="procdrug" id="procdrug"/><br><br>
<label>Amount</label>
<input type="text" name="amount" id="amount"/><br><br>
<input type="button" onclick="addInput()" name="add" value="Add input field" style="margin-left:150px" />
</div>
</fieldset>
</form>
</div>
<div id="two">
<fieldset>
<legend>TN QUEUE</legend>
<label><B>Procedure/Drug</b></label><label><b>Amount</b></label><br>
<div id="text">
</div>
<label><b>Total</b></label>
<input type="text" name="total" id="total"/>
</fieldset>
</div>
</body>
</html>
Here is the javascript function
<script language="javascript">
fields = 0;
function addInput() {
var amount=document.getElementById('amount').value;
var pd=document.getElementById('procdrug').value;
if (fields != 10)
{
document.getElementById('text').innerHTML += "<input id='pdgen' type='text'/>";
document.getElementById('text').innerHTML += "<input id='amtgen' type='text'/><br />";
document.getElementById('pdgen').value=pd;
document.getElementById('amtgen').value=amount;
fields += 1;
}
else
{
document.getElementById('text').innerHTML += "<br />Only A Maximum of 10 is allowed.";
document.form.add.disabled=true;
}
}
</script>
The generated elements values are posted from the form and increment on every submit. My problem is the only on submit first element is updated with the new value:
Sample results
Procedure/Drug Amount
Amoxyl 200
blank element blank element
blank element blank element
blank element blank element
Total
The problem is you are adding your elements with the .innerHtml += method which is avoiding the values entered before. You need to use appendChild method to add new elements. Here is your new code :
fields = 0;
function addInput() {
var amount=document.getElementById('amount').value;
var pd=document.getElementById('procdrug').value;
var br = document.createElement('br');
if (fields != 10)
{
var input1 = document.createElement('input');
input1.setAttribute('id','pdgen' + fields);
input1.value = pd;
var input2 = document.createElement('input');
input2.setAttribute('id','amtgen' + fields);
input2.value = amount;
document.getElementById('text').appendChild(input1);
document.getElementById('text').appendChild(input2);
document.getElementById('text').appendChild(br);
fields++;
}
else
{
document.getElementById('text').innerHTML += "<br />Only A Maximum of 10 is allowed.";
document.form.add.disabled=true;
}
}
FIDDLE

DOM event clearing text values

I'm writing a JS code to calculate a final grade given some individual grades and output the result in the html page but when I trigger the event and function it outputs a wrong answer for a split second then immediately disappears along with the values entered into the text box.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Problem 2</title>
<script src="grades.js" type="text/javascript"></script>
</head>
<body>
<h1>Grade Calculator</h1>
<form id ="myForm">
<div id="assignments">
HW <input type="text" size="1"/> / <input type="text" size="1"/><br/>
HW <input type="text" size="1"/> / <input type="text" size="1"/><br/>
HW <input type="text" size="1"/> / <input type="text" size="1"/>
</div>
<div>
<input type="checkbox" /> Curve +5?
</div>
<div id="resultsarea">
<p>
<!--add buttons here -->
<button id="comp">Compute</button>
<button id="clr">Clear</button>
</p>
<!-- add results here -->
</div>
</form>
</body>
</html>
JS:
window.onload = pageLoad;
function pageLoad()
{
var cbutton = document.getElementById("comp");
cbutton.onclick = compute;
}
function compute()
{
var values = document.getElementsByTagName("input");
var marks = 0;
var total = 0;
for (var i=0; i < values.length; i++)
{
if(values[i].type == "text")
{
if (i%2 == 0)
marks += parseInt(values[i].value);
else
total += parseInt(values[i].value);
}
}
var result = Math.round(marks/total);
document.writeln(result);
}

Javascript dynamically created form field validation

I have created a form with a dynamically created field and i am trying to find a way to validate all the fields with javascript. I just want to alert the user that a field is null. Here is my code:
<script>
var counter = 0;
function addInput(divName){
counter++;
var Ai8ousa = document.createElement('div');
Ai8ousa.innerHTML = "Field: "+(counter +1) + "<input type='text' name='field[]'>";
document.getElementById(divName).appendChild(Ai8ousa);
}
function validations(form){
var field;
var i=0;
do{
field=form['field[]'];
if (field.value=='')
{
alert('The field is null!!!');
return false;
}
i++;
}while(i<counter);
}
</script>
<form action="" method="post" onsubmit="return validations(this)" >
<div id="dynamicInput">
Field : <input type="text" name="field[]" /> <br />
</div>
<input type="button" value="New field" onClick="addInput('dynamicInput');">
<input type="submit" value="Submit" />
</form>
I was expecting that will work but i was obviously wrong:(
With this code if i haven't pressed the "New field" button and press submit i will get the alert as expected. But on all other cases i am not getting anything!
Thanks for your time anyway, and sorry if i have made grammar mistakes!
<script type="text/javascript">
var counter = 0;
function addInput(divName){
counter++;
var Ai8ousa = document.createElement('div');
Ai8ousa.innerHTML = "Field: "+(counter +1) + "<input type='text' name='field[]'>";
document.getElementById(divName).appendChild(Ai8ousa);
}
function validations(form){
var field;
var i=0;
do{
field=form[i];
if (field.value=='')
{
alert('The field is null!!!');
return false;
}
i++;
}while(i<counter);
}
</script>
<form action="" method="post" onsubmit="return validations(this)" >
<div id="dynamicInput">
Field : <input type="text" name="field[]" /> <br />
</div>
<input type="button" value="New field" onClick="addInput('dynamicInput');">
<input type="submit" value="Submit" />
</form>
I don't understand this line: field=form['field[]'];, so I changed it to field=form[i];
http://jsfiddle.net/sZ4sd/

Categories

Resources