Value in "input" filed becomes empty [duplicate] - javascript

This question already has answers here:
Stop input from clearing on innerHTML insert
(4 answers)
Closed 8 months ago.
Hi Folks I'm new to JS World.
I am trying to add A <div> dynamically to my HTML with the help of JavaScript.
var counter = 0;
function add_more_animals() {
counter+=1;
html = `<div id="animal${counter}">
<input type="text" name="animalName${counter}">
<input type="text" name="animalType${counter}">
</div>`;
var form = document.getElementById("animals");
form.innerHTML+=html;
}
<div id="animals">
<div id="animal0">
<input type="text" name="animalName0">
<input type="text" name="animalType0">
</div>
</div>
<button type="button" onclick="add_more_animals()">Add animals (+)</button>
The issue I'm facing:
While I populate the fields of animalName0 and animalType0 on UI. After I click on add button so as to insert more animals data, new div is created as per JS logic written in file. But my earlier inputs to animalName0 & animalType0 becomes empty & I have to insert data there all over again.
Can you please help here?

The problem stems from the line form.innerHTML+=html which is shorthand for form.innerHTML = form.innerHTML + html. When it gets the form.innerHTML it is grabbing the HTML only; The text typed into the inputs are not a part of this HTML. When the innerHTML gets set, think form.innerHTML = form.innerHTML + html, brand new HTML elements are created based off of the HTML only, and any state, including typed in text, is lost. Any event listeners will also be lost in this process.
The proper way of adding a new element while leaving adjacent elements in place is to create the new element with document.createElement, and add it with a function like .appendChild, like so
var counter = 0
function add_more_animals() {
counter+=1;
// Create an empty element
const newEl = document.createElement('div')
newEl.id = `catalogue${counter}`
// Add the first input
const nameInput = document.createElement('input')
nameInput.name = `animalName${counter}`
newEl.appendChild(nameInput)
// Now the second one
const typeInput = document.createElement('input')
typeInput.name = `animalType${counter}`
newEl.appendChild(typeInput)
// And finally attach everything to the animals form
document.getElementById("animals").appendChild(newEl)
}
<div id="animals">
<div id="animal0">
<input type="text" name="animalName0">
<input type="text" name="animalType0">
</div>
</div>
<button type="button" onclick="add_more_animals()">Add animals (+)</button>
As you can imagine, this can become verbose if you have a large amount of HTML to add. To make this process easier they came out with template tags which you may prefer using. Use them either like this or like this.

Related

I try to pass the content of a paragraph element into a field of a contact form using Javascript

So the problem is this:
I try to get the text that is inside a specific paragraph with a specific id name and pass it inside a contact form .
i tried this
var src = document.getElementById("ptext"),
dest = document.getElementById("inform");
src.addEventListener('input', function() {
dest.value = src.value;
}};
Where "ptext" is the id of the element with the text of the paragraph and the "inform" is the id of the field in contact form.
The above code will trigger when the user clicks a button.
I am new in Javascript so the code above is probably wrong or faulty.
UPDATE: The HTML Code is this :
<p id="pext">Hello this is the text that is to be imported inside the form field</p>
form field:
<input type="text" name="your-subject" value="" size="40" id="inform" aria-required="true" aria-invalid="false" placeholder="Subjext">
I'm not sure if this is what you were trying to do, but if you're trying to get the text of a paragraph into a form field on a button click (useful a lot of the time with hidden form fields), then here is a code snippet to help you:
var src = document.getElementById("ptext");
var dest = document.getElementById("inform");
var getText = function () {
dest.value = src.innerText;
event.preventDefault();
return false;
}
<p id="ptext">This is some fake text that we'll put into the form.</p>
<form onsubmit="getText()">
<label for="text">Info from paragraph:</label><br>
<input type="text" id="inform" name="text"><br><br>
<input type="submit" >
</form>
Hello and welcome to Stack Overflow :)
To get the text that is inside specific paragraph, use
var src = document.getElementById("ptext").innerText;
To assign the value to an input field (which is what I'm assuming you are trying to do), use
document.getElementById("inform").value = src;
If you supply us with HTML element we could be even more precise.

Using Input Number to Update Number of Paragraphs Displayed - HTML Javascript

I'm trying to use a input number type to update how many times a particular amount of content is added to the page. In the example I'm doing it with a p tag but in my main model I'm using it on a larger scale with multiple divs. However, I can't seem to be able to get this to work. If someone can see where I'm going wrong that would be very helpful.
function updatePage() {
var i = document.getElementById("numerInput").value;
document.getElementById("content").innerHTML =
while (i > 1) {
"<p>Content<p/><br>";
i--;
};
}
<input type="number" value="1" id="numberInput">
<br>
<input type="button" value="Update" onclick="updatePage()">
<div id="content">
<p>Content
<p>
<br>
</div>
First, you have quite a few problems that need addressing:
You are setting the .innerHTML to a while loop, which is invalid because a loop doesn't have a return value. And, inside your loop, you just have a string of HTML. It isn't being returned or assigned to anything, so nothing will happen with it.
You've also mis-spelled the id of your input:
document.getElementById("numerInput")
Also, don't use inline HTML event attributes (i.e. onclick) as there are many reasons not to use this 20+ year old antiquated technique that just will not die. Separate all your JavaScript work from your HTML.
Lastly, your HTML is invalid:
"<p>Content<p/><br>"
Should be:
"<p>Content</p>"
Notice that in addition to fixing the syntax for the closing p, the <br> has been removed. Don't use <br> simply to add spacing to a document - do that with CSS. <br> should be used only to insert a line feed into some content because that content should be broken up, but not into new sections.
Now, to solve your overall issue, what you should do is set the .innerHTML to the return value from a function or, more simply just the end result of what the loop creates as I'm showing below.
// Get DOM references just once in JavaScript
let input = document.getElementById("numberInput");
let btn = document.querySelector("input[type='button']");
// Set up event handlers in JavaScript, not HTML with standards-based code:
btn.addEventListener("click", updatePage);
function updatePage() {
var output = ""; // Will hold result
// Instead of a while loop, just a for loop that counts to the value entered into the input
for (var i = 0; i < input.value; i++) {
// Don't modify the DOM more than necessary (especially in a loop) for performance reasons
// Just build up a string with the desired output
output += "<p>Content</p>"; // Concatenate more data
};
// After the string has been built, update the DOM
document.getElementById("content").innerHTML = output;
}
<input type="number" value="1" id="numberInput">
<br>
<input type="button" value="Update">
<div id="content">
<p>Content</p>
</div>
And, if you truly do want the same string repeated the number of times that is entered into the input, then this can be a lot simpler with string.repeat().
// Get DOM references just once in JavaScript
let input = document.getElementById("numberInput");
let btn = document.querySelector("input[type='button']");
// Set up event handlers in JavaScript, not HTML with standards-based code:
btn.addEventListener("click", updatePage);
function updatePage() {
// Just use string.repeat()
document.getElementById("content").innerHTML = "<p>Content</p>".repeat(input.value);
}
<input type="number" value="1" id="numberInput">
<br>
<input type="button" value="Update">
<div id="content">
<p>Content</p>
</div>
As #ScottMarcus pointed out you had the following issues:
While Loops do not need a ; at the end of while(args) {}
Your .innerHTML code was in the wrong place
You had a typo in getElementById("numerInput") which I changed to getElementById("numberInput")
Code
function updatePage() {
// Get input value
var numberInput = document.getElementById("numberInput").value;
// Will be used to store all <p> contents
var template = "";
while (numberInput > 0) {
// Add all contents into template
template += "<p>Content<p/><br>";
numberInput--;
}
// Append upon clicking
document.getElementById("content").innerHTML = template;
}
<input type="number" value="1" id="numberInput">
<br>
<input type="button" value="Update" onclick="updatePage()">
<div id="content">
</div>

JavaScript- dynamically adding input to a page

i am using JavaScript to add a div on the fly. The div should contain a form input whose 'name' attribute WILL changes in value incrementally.
I have managed to do this- I however have two problems.
First Problem:
The first div that i created is cancelled out by the next dynamically created div.
thus, when i submit the form, the first dynamically created imput form is blank-
but subsequent ones have values on them.
MY CODE :
html
<div id="dynamicDivSection"></div>
<button id="addbutton">add box</button>
<div id="boxes">
<div class="box">
<input type="text" id='dynamic-imput' name="">
</div>
</div>
javascript
var addbutton = document.getElementById("addbutton");
var key = 1;
addbutton.addEventListener("click", function() {
key++;
document.getElementById('dynamic-imput').name = 'ser['+key+'][\'name\']';
var boxes = document.getElementById("boxes");
var head = document.getElementById("dynamicDivSection");
var clone = boxes.firstElementChild.cloneNode(true);
head.appendChild(clone);
});
i suspect that the problem is causing by this:
document.getElementById('dynamic-imput').name =
'ser['+key+'][\'name\']';
i.e when i create the dynamic div it creates several inputs on the page that contain the same Id. if i am correct, then perhaps teh solution is to change the Id of the newly created imput - however, i am not sure how to change the Id of a dynamically created Imput.
Second problem.
i want each dynamically created div to go to the top of the page; i.e to be placed before the earlier created dynamic div- however, at the moment each dynamically created div go directly under the first dynamically created div.
You can insert as the first child with:
parent.insertAdjacentElement('afterbegin', nodeToInsert);
You can get and set attributes such as id with setAttribute and getAttribute. Though I'm not sure why you even need an ID here, it would be simpler not to have one and select the element with a class.
var addbutton = document.getElementById("addbutton");
var key = 1;
addbutton.addEventListener("click", function() {
key++;
document.getElementById('dynamic-imput').name = 'ser['+key+'][\'name\']';
var boxes = document.getElementById("boxes");
var head = document.getElementById("dynamicDivSection");
var clone = boxes.firstElementChild.cloneNode(true);
var clonedInput = clone.firstElementChild;
clonedInput.setAttribute('id', clonedInput.getAttribute('id') + '-' + head.children.length);
head.insertAdjacentElement('afterbegin', clone);
});
<div id="dynamicDivSection"></div>
<button id="addbutton">add box</button>
<div id="boxes">
<div class="box">
<input type="text" id='dynamic-imput' name="">
</div>
</div>

Create and email PDF in Javascript Apache Cordova

I am using JavaScript and HTML to built an Apache Cordova app for Android. I would like the user to click/tap a button that will then generate a PDF with the string that they just entered into a text field, then open an email to send the PDF attachment. The attachment does not need to be saved to the device, but can do if it is required before sending. Is this possible and if so is there any documentation or tutorials on how to do this?
Thank you
Okay, to achieve that we need to add some inputs and get it's values, and a button that will fire the js. Which is pretty easy.
HTML:
<input type="text" id="name" placeHolder="Enter Your name" />
<input type="text" id="lname" placeHolder="Enter Your last name" />
<input type="text" id="hobby" placeHolder="Enter Your hobby" />
<input type="text" id="skills" placeHolder="Enter Your skills" />
<button id="btn">
Get results
</button>
<!--values will be shown inside the div#content-->
<div id="content"></div>
Next is the JavaScript part where you will be displaying all of the input values inside the div#content with a <p></p> tag.
JavaScript:
function onload() {
var input, btn, p, content, input_array;
//grab the button by ID
btn = document.getElementById("btn");
//grab all inputs
input = document.getElementsByTagName("INPUT");
//grab the div by ID
content = document.getElementById("content");
// Add some 'Data' inside the variable so that you show
// the user what he answered
input_array = [
"Name:",
"Last name:",
"Hobby:",
"Skills:"
];
//attach the click event listener to the button
btn.addEventListener("click", function() {
//Using the for loop, we basically create 4 <p> elements inside
//the div#content
for (var i = 0; i <= 3; i++) {
p = content;
// we display all of the input values within a <p> tag
// with a class of 'testing' so that you cn change it later
// on for styling it etc..
// Then we add the array and input values inside the <p> tag
p.innerHTML += "<p class='testing'>" + input_array[i] + " " + input[i].value + "</p>";
}
}, false);
}
//call the function
onload();
Now that you have displayed the values, you can do a lot of stuff. You can store all of what the user wrote into an array, do some cool animations and fade in the result.
To generate the results into a PDF format, you need to use this plugin that I have found on GitHub that supposedly says users can save the generated PDF.
(Please note that I personally have not worked with this plug-in before so I give you no guarantees.)
Link: cordova-plugin-html2pdf
Follow the documentation there and everything should work well.
Demo: Jsfiddle

Editing html input element from javascript bugs out

I have this input field in html:
<input id="title" type="text" class="" />
A button will allow the user to randomize the value of the input field by calling a js function.
var title = document.getElementById("title");
title.removeAttribute("value");
title.setAttribute("value",random_name);
If the user wants to change the value auto-asigned by my function (aka random_name), he can simply type something else in the input field.
All works fine until now, however if the user changes his mind and clicks the randomize button again, the function is called and "value" attribute is modified, but the user still sees the last thing he typed and not the new random value.
Is there a way to fix this or maybe a workaround?
Just do title.value = random_name
You can set an input's value by element.value = "desired_value". If you use that, it works.
http://jsfiddle.net/f4gVR/2/
<input id="title" type="text" class="" />
<input type="button" class="" onclick="randomValue()" value="Random" />
function randomValue() {
var title = document.getElementById("title");
title.value = Math.random(); // assign random_name to title.value here
}
if it's your random_name bugging out, you should post the code. Try this first. Just replace Math.random() with random_name.
you need to use title.value = random_name; instead of title.setAttribute("value",random_name);
Fiddle: http://jsfiddle.net/4dhKa/

Categories