Why does the textfields and button disappears after clicking the Go button? - javascript

i have my code(html/javascript) here which allows user to input the size and color of the square.The problem is when i click the go button the textfields disappear including the button and the one that displays is the output.Is there any ways that i could retain the textfields and the button then output the square below it?
<html>
<head>
<script type="text/javascript">
size=0;
function display(form){
size=form.inputbox.value;
color=form.inputbox2.value;
for(i=0;i<size;i++){
for(j=0;j<size;j++){
if(i==0||i==(size-1)){
document.write("<font color="+color+">* ");
}
else if (j == 0||j == (size-1)) {
document.write("* ");
}
else {
document.write(" ");
}
}
document.write("<br>");
}
}
</script>
</head>
<body>
<form name="form1" action="" method="get">
Input size of the square:
<input type="text" name="inputbox" value=""><br>
Input color of the square:
<input type="text" name="inputbox2" value="">
<input type="button" name="button" value="Go" onClick="display(this.form)">
</form>
</body>
</html>

Calling document.write on a page that has completed rendering will destroy the exiting DOM document on the page, replacing it with only the newly written HTML elements.
If you wish to add to existing DOM elements, select an element and write to its innerHTML property instead.
<html>
<head>
<script type="text/javascript">
size=0;
function display(form){
size=form.inputbox.value;
color=form.inputbox2.value;
// A node to write into
writeTo = document.getElementById('writeTo');
for(i=0;i<size;i++){
for(j=0;j<size;j++){
if(i==0||i==(size-1)){
writeTo.innerHTML = writeTo.innerHTML + "<font color="+color+">* ";
}
else if (j == 0||j == (size-1)) {
writeTo.innerHTML = writeTo.innerHTML + "* ";
}
else {
writeTo.innerHTML = writeTo.innerHTML + " ";
}
}
writeTo.innerHTML = writeTo.innerHTML + "<br>";
}
}
</script>
</head>
<body>
<form name="form1" action="" method="get">
Input size of the square:
<input type="text" name="inputbox" value=""><br>
Input color of the square:
<input type="text" name="inputbox2" value="">
<input type="button" name="button" value="Go" onClick="display(this.form)">
</form>
<div id='writeTo'></div>
</body>
</html>
And add an empty node to your HTML something like:
<div id='writeTo'></div>
Here it is in action on jsFiddle.net
To get the square to be all the correct color, it is easiest to change the CSS color property of <div id='writeTo'>
document.getElementById('writeTo').style.color = color;

Related

Javascript innerHTML is automatically overwritten and nullified [duplicate]

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>

TextCounter & Trigger innerHTML in two separate input areas

I just started to learn Javascript. I have two questions regarding TextCounter & Trigger innerHTML.
My code below, how to separately trigger innerHTML for two inputs?
Why the alert info which is "over!!" still shows while deleting the number of words in the textarea?
Can someone please help? Much appreciated!
HTML
<html>
<head>
</head>
<body>
<form>
<textarea name="line01" rows="3" style="width:340px;"
onKeyUp="textCounter(this.form.01,this.form.countDisplay01,10);"
onKeyDown="textCounter(this.form.01,this.form.countDisplay01,10);">
</textarea>
<br>
<input readonly type="text" name="countDisplay01" width: 25px"
value="10">characters remaining
<p id="go1"></p>
</form>
<form>
<textarea name="line02" rows="3" style="width:340px;"
onKeyUp="textCounter(this.form.02,this.form.countDisplay02,8);"
onKeyDown="textCounter(this.form.02,this.form.countDisplay02,8);">
</textarea>
<br>
<input readonly type="text" name="countDisplay02" width: 25px"
value="8">characters remaining
<p id="go2"></p>
</form>
</body>
</html>
Javascript
<script>
function textCounter(textField, showCountField, maxAmount) {
if (textField.value.length <= maxAmount) {
showCountField.value = maxAmount - textField.value.length;
} else {
document.getElementById("go1").innerHTML = "<span
style='color:red'>Over!!</span>";
document.getElementById("go2").innerHTML = "<span
style='color:red'>Over!!</span>";
textField.value = textField.value.substring(0,maxAmount);
}
</script>
Try with the following code
HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Text Counter</title>
</head>
<body>
<form>
<textarea name="01" rows="3" style="width:340px;"
onKeyUp="textCounter(this.form['01'],this.form.countDisplay01,10,1);"
onKeyDown="textCounter(this.form['01'],this.form.countDisplay01,10,1);">
</textarea>
<br>
<input readonly type="text" name="countDisplay01" style="width: 25px;" value="28"> characters remaining
<p id="go1"></p>
</form>
<form>
<textarea name="02" rows="3" style="width:340px;"
onKeyUp="textCounter(this.form['02'],this.form.countDisplay02,8,2);"
onKeyDown="textCounter(this.form['02'],this.form.countDisplay02,8,2);">
</textarea>
<br>
<input readonly type="text" name="countDisplay02" style="width: 25px" value="15">characters remaining
<p id="go2"></p>
</form>
</body>
</html>
SCRIPT
<script>
function textCounter(textField, showCountField, maxAmount,id) {
if (textField.value.length <= maxAmount) {
showCountField.value = maxAmount - textField.value.length;
document.getElementById('go'+id).innerHTML = '';
} else {
document.getElementById('go'+id).innerHTML = '<span style="color:red">Over!!</span>';
textField.value = textField.value.substring(0,maxAmount);
}
}
</script>
As you have used a name that starts with number, it's not a valid variable. You should access it through dictionary lookup:
textCounter(this.form['01'],this.form.countDisplay01,10);
For the alert text, you should reset the innerHTML in the first if clause:
if (textField.value.length <= maxAmount) {
showCountField.value = maxAmount - textField.value.length;
document.getElementById("go1").innerHTML = "";
document.getElementById("go2").innerHTML = "";
} else {
document.getElementById("go1").innerHTML = "<span style='color:red'>Over!!</span>";
document.getElementById("go2").innerHTML = "<span style='color:red'>Over!!</span>";
textField.value = textField.value.substring(0,maxAmount);
}
This will remove the alert text, on the next keypress. If you want to remove the text immediately, you have two options:
Forget about showing an error.
Show the error for about a fraction of second and then remove it. Using something like a setTimeout. But you should remember, the window won't redraw before returning from your function. So, setting the alert text first, and then removing it at the end of your function, will be the same as doing option 1.

How to get values of multiple textboxes generated dynamically?

I have a button called 'AddTextArea', on clicking, I get new text area, but how can I get the values that I have entered in the new text areas?
I tried like this-
var x= document.getElementById("div_quotes").value;
but it's not working.
Please help, as I am new to JS, thanks in advance.
<html>
<head>
<script type="text/javascript">
function addTextArea(){
var div = document.getElementById('div_quotes');
div.innerHTML += "<textarea name='new_quote[]' />";
div.innerHTML += "\n<br />";
}
</script>
</head>
<body>
<form method="post">
<!--<input type="text" name="text_new_author" /><br />-->
<div id="div_quotes"></div>
<input type="button" value="Add Text Area" onClick="addTextArea();">
<input type="submit" name="submitted">
</form>
</body>
</html>
var x= document.getElementById("div_quotes").value;
Above code will not work as div_quotes is a div and div do not have value property.
You will have to search for textareas in this div.
Sample
function addTextArea() {
var div = document.getElementById('div_quotes');
div.innerHTML += "<textarea name='new_quote[]' />";
div.innerHTML += "\n<br />";
}
function validate(){
var tas = document.querySelectorAll('#div_quotes textarea[name="new_quote[]"]')
for(var i = 0; i< tas.length; i++){
console.log(tas[i].value)
}
}
<form method="post">
<!--<input type="text" name="text_new_author" /><br />-->
<div id="div_quotes"></div>
<input type="button" value="Add Text Area" onClick="addTextArea();">
<input type="button" name="submitted" onclick="validate()" value="Validate">
</form>
Version 2
Now if you notice in above sample, if you type and then add another textarea, it will flush value of previous ones. This is because, you are setting .innerHTML += .... This will destroy and recreate all elements again. You should use document.createElement
function addTextArea() {
var div = document.getElementById('div_quotes');
var wrapper = document.createElement('div')
var ta = document.createElement('textarea');
ta.name = "new_quote[]"
wrapper.append(ta);
div.append(wrapper)
}
function validate(){
var tas = document.querySelectorAll('#div_quotes textarea[name="new_quote[]"]')
for(var i = 0; i< tas.length; i++){
console.log(tas[i].value)
}
}
<form method="post">
<!--<input type="text" name="text_new_author" /><br />-->
<div id="div_quotes"></div>
<input type="button" value="Add Text Area" onClick="addTextArea();">
<input type="button" name="submitted" onclick="validate()" value="Validate">
</form>
You can add a CSS Class to the new text area that is generated and get the data using
var x = document.getElementsByClassName("dynamicTxtArea")
I have added the class to the Text area that is being dynamically generated. Please check the code below.
<html>
<head>
<script type="text/javascript">
function addTextArea(){
div.innerHTML += "<textarea name='new_quote[]' class='dynamicTxtArea'/>";
div.innerHTML += "\n<br />";
}
</script>
</head>
<body>
<form method="post">
<!--<input type="text" name="text_new_author" /><br />-->
<div id="div_quotes"></div>
<input type="button" value="Add Text Area" onClick="addTextArea();">
<input type="submit" name="submitted">
</form>
</body>
</html>

Calling string from one function into another doesent seem to work., why?

So I have this code and it does not seem to work. The thing I want it to do is to call the "together" from the function "go" in the function "second". What am i doing wrong?
The program was initially supposed to take what is in the input-text and add it with the ".com" or the ".no"(depending on what u checked) and redirect to that page. But I only want to call the "together" in the "second" function. Is there any better way to do it?
<!doctype html>
<html>
<head>
<title>A Basic Form</title>
<link rel="stylesheet" type="text/css">
<style type="text/css">
</style>
</head>
<body>
<fieldset>
<legend>Redirection: </legend>
<div>
<label>Where do you want to go?</label>
<input type="text" id="input" name="input" size="7">
<input type="button" id="submit" name="submit" value="Submit" onclick="go()">
</div>
<div>
<input type="radio" id="no" name="end" value=".no">
<label for="no">.no</label><br />
<input type="radio" id="com" name="end" value=".com">
<label for="com">.com</label>
</div>
</fieldset>
<script type="text/javascript">
var end = "";
var input = document.getElementById("input").value;
function go(end, input){
if (document.getElementById("no").checked){
end = document.getElementById("no").value;
}else if (document.getElementById("com").checked){
end = document.getElementById("com").value;
}else{
alert("Please Choose a category!");
}
var together = input + end;
// window.location.replace("http://www." + together);
}
second(together);
function second(together){
alert(together);
}
</script>
</body>
</html>
function go(end, input){
if (document.getElementById("no").checked){
end = document.getElementById("no").value;
}else if (document.getElementById("com").checked){
end = document.getElementById("com").value;
}else{
alert("Please Choose a category!");
}
var together = input + end;
// window.location.replace("http://www." + together);
} // remove this
second(together);
} // add this

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

Categories

Resources