Javascript - How to add form's input into the dom properly? - javascript

I'm just trying to make a simple javascript form where everytime you type and submit something, it shows up in the page.
<form id="myForm">
<input id="text" type="text" name="name" value="">
<input id="submit" type="submit">
</form>
javascript:
document.getElementById("myForm").addEventListener('submit', function(){
var input = document.getElementById("text")
var output = input.value;
var printOutput = document.createElement('h1');
printOutput.innerHTML = output;
document.body.appendChild(printOutput);
});
This shows up for a second then disappears. I understand it's happening because the dom manipulation is happening inside the submit event. But I'm not sure how to go around that.
My first instinct was to use
return output;
then reference the whole function once I appendChild from outside it. But that didn't work either. I'm guessing cause It's an Eventlistener and not a normal function... any ideas on how to go with this?

You are ignoring the form primordial sense that is to send data over a server.
You don't need aform for what you intend. you need only input elements and a handler on the button.
function handler (){
var input = document.getElementById("text")
var output = input.value;
var printOutput = document.createElement('h1');
printOutput.innerHTML = output;
document.body.appendChild(printOutput);
document.getElementById("text").value='';
}
document.getElementById("submit").addEventListener('click', handler);
document.getElementById("text").addEventListener('keypress', function(e){ (e.charCode == 13) && handler();});
<div id="myForm">
<input id="text" type="text" name="name" value="">
<input id="submit" type="submit">
</div>

Add return false; at the end of the event listener. This stops the submit from actually happening which refreshes the page

Try this instead:
document.getElementById("myForm").addEventListener('submit', function(event){
event.preventDefault();
var input = document.getElementById("text")
var output = input.value;
var printOutput = document.createElement('h1');
printOutput.innerHTML = output;
document.body.appendChild(printOutput);
});

the simplest way of getting input and display on the same page is
function display()
{
var input=document.getElementById("text").value;
document.getElementById("display").innerHTML=input;
}
<form id="myForm">
<input id="text" type="text" name="name" value="">
<input id="submit" type="button" onclick=display() value="submit">
<div id="display"></div>
</form>
if you want to display multiple inputs i.e. each input entered by the user.
document.getElementById("display").innerHTML += input+"<br>";
Note: Always try to write easiest and shortest code for the optimized result.

yes it behaves how it should. it's form and what it does it submits all information to new page. you didn't provide action='' parameter and means it sends information on same page. when you click submit what happens is first you append h1 element and then it reloads, that's why it disappears. if you don't have other page to submit information get rid of forms.
<input id="text" type="text" name="name" value="">
<input id="submit" onclick='return getoutup();' type="submit">
<h1 id='output'></h1>
<script type="text/javascript">
function getoutup(){
document.getElementById('output').innerText=document.getElementById('text').value;
return false;
}
</script>
so you see that i have pre-created h1 tag, so you don't need much coding to append as function goes. just pre create with value of none and then change with one line of code. hope it helps. maybe it's not correct answer kind of changed your way.

Related

fill and submit form using javascript from console

Here is my form:
<form id="myForm">
<input id="htmlString" type="text" name="htmlField" ><br>
<input type="Submit" value="Submit" >
</form>
And need to fill it from console.
just to use it in my app,
Will inject javascript with data to local html file.
I tried to make the form without a submit button like so:
<body>
<form id="myForm">
<input id="htmlString" type="text" name="htmlField" ><br>
</form>
<script>
htmlString.oninput = function(){
///do some stuff
}
</script>
</body>
Expecting that :
document.getElementById('htmlString').value="moo" ;
It automatically submit the form, because here oninput used.
But it just stayed filled with inputs and not proceed further.
Tried with other solution:
form = document.getElementById("myForm")
form.submit()
But it just refreshed the page and not submitted the form.
The need is just one filed without else, and inject my string to it with javascript to run functions embedded in the html.
Try making the input button hidden.
<body>
<form id="myForm">
<input id="htmlString" type="text" name="htmlField" ><br>
<input type="Submit" value="Submit" style="display: none" >
</form>
<button onclick="simulateConsole()">Try it</button>
<script>
htmlString.oninput = function(){
if(this.value === "moo") {
myForm.submit();
}
}
// This event will be triggered even if you use console
htmlString.onsubmit = function(){
if(this.value === "moo") {
// do something onSubmit
}
}
function simulateConsole() {
// you can simulate this in console
htmlString.value = "moo";
myForm.submit();
}
</script>
</body>
I hope it helps.
You need to supply an action to the form, otherwise it will just reload the page.
See more here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form

Display input by clicking submit button

For example when i give an input saying "Good Morning" in the submit button. I should be able to view my input on the Html web page.
<input id="a"/>
<button type="submit" onclick="e()">Submit<button
<p id="k"></p>
Call a function on click of submit and fetch the value of the input box. Using .innerHTML append the value to the paragraph or a div
function e()
{
document.querySelector('#k').innerHTML=document.querySelector('#a').value
}
<input id="a"/>
<input type="submit" onclick="e()" value="Submit">
<p id="k"></p>
It's not quite clear what you're trying to do, but assuming I undertood correctly. You want to take an input's value & output it in the DOM when submitting the form.
You can check a code working sample here. Notice kindly that you can reuse this function again in another input by changing the parameters.
const submitForm = (value, displayer) => {
let input = document.getElementById(value);
let valueHolder = document.getElementById(displayer);
let inputValue = input.value;
valueHolder.innerHTML = inputValue;
input.value = '';
};
const form = document.getElementById('formSubmission');
form.addEventListener('submit', (e) => {
e.preventDefault();
submitForm('inputData', 'valueHolder');
});
<form id="formSubmission">
<input type="text" placeholder="Enter something..." id="inputData" />
<input type="submit" />
</form>
<h1 id="valueHolder"></h1>

JS input validation submit disabled for separate instances

I need each instance of input and submit to operate independently. What is the best way to handle multiple instances where each submit is connected to it's own set of inputs?
Since they are unrelated, would data-attributes be the best solution?
$(document).ready(function() {
validate();
$('input').on('keyup', validate);
});
function validate() {
var inputsWithValues = 0;
var myInputs = $("input:not([type='submit'])");
myInputs.each(function(e) {
if ($(this).val()) {
inputsWithValues += 1;
}
});
if (inputsWithValues == myInputs.length) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item1">
<div><input type="text" name="name" autocomplete="off" required/></div>
<input type="submit" value="Submit 1" />
</div>
<div class="item2">
<div><input type="text" name="name" autocomplete="off" required/></div>
<div><input type="text" name="name" autocomplete="off" required/></div>
<input type="submit" value="Submit 2" />
</div>
I think your intuition about using data attributes works great here.
var allButtons = document.querySelectorAll("input[type=submit]");
allButtons.forEach(button => {
button.addEventListener("click", () => {
var inputSet = button.getAttribute("data-input-set");
var inputs = document.querySelectorAll("input[type='text'][data-input-set='" + inputSet + "']");
});
});
In the following code, when an input button is pressed, it will fetch all the inputs with the corresponding "input-set" tag.
Preferred way
I think best solution would be use form -tag as it is created for just this use case HTML Forms.
<form id="form-1">
<input type="text"/>
<input type="submit>
</form>
<form id="form-2">
<input type="text"/>
<input type="submit>
</form>
You can also bind custom Form on submit event handlers and collect form data this way.
$('#form-1').on('submit', function(event){
event.preventDefault(); // Prevent sending form as defaulted by browser
/* Do something with form */
});
Possible but more bolt on method
Alternative methods to this would be to create your own function's for collecting all relevant data from inputs and merge some resonable data object.
I would most likely do this with giving desired class -attribute all inputs I would like to collect at once eg. <input type="text" class="submit-1" /> and so on. Get all elements with given class, loop through all them and save values into object.
This requires much more work tho and form -tag gives you some nice validation out of the box which you this way have to do yourself.

Changing div content with Javascript onClick

I'm trying to use a textbox and a submit button to change a div on the page. I want to take the text that has been typed in the textbox and put it in the div when the button is clicked. I have this code:
function myfunction() {
var myText = document.getElementById("textbox").value;
document.getElementById('myDiv').innerHTML = myText;
}
<form>
<input type="text" name="textbox" id="textbox" />
<input type="submit" name="button" id="button" onclick="myfunction()" />
</form>
<br/>
<div id="myDiv"></div>
But nothing happens. When I try it in the browser it just refreshes the page and adds ?textbox=someValueHere to the end of the URL. How can I get the div to display the textbox value?
The problem is that the submit button is posting the form, so you are not seeing the change - If you change your submit button to a normal button it will work
<input type="button"name="button" id="button" onclick="myfunction()" />
The form is submitting. You need to stop that by adding return false; (if you are using Jquery) Or remove the form entirely it is not required.
function myfunction() {
var myText = document.getElementById("textbox").value;
document.getElementById('myDiv').innerHTML = myText;
return false;
}
Nothing happens because the form is being submitted. You need to prevent the default action from happening, which is the form submission. See preventDefault() or return false in the MDN for more details on how to prevent an events default action from occurring.
Call event.preventDefault() to prevent the normal form submission.
function myfunction(e) {
e.preventDefault();
var myText = document.getElementById("textbox").value;
document.getElementById('myDiv').innerHTML = myText;
}
<form>
<input type="text" name="textbox" id="textbox" />
<input type="submit" name="button" id="button" onclick="myfunction(event)" />
</form>
<br/>
<div id="myDiv"></div>

When working with a form element how would you access what was input into the element to display a message?

I have a form
<form>
<input id="input" type="number">
<input type="submit">
</form>
I want to be able to input a number into the number and click the submit button and javascript displays a number based on the number submitted.
(My Guess is that this question is very basic but I am pretty knew to javascript.)
Here is a very simple (jquery-less) example of what you might be after:
<script type="text/javascript">
function ShowANumber() {
var currentNumber = document.getElementById("input").value;
var newNumber = currentNumber * 10 // Do something with input
document.getElementById("result").innerHTML = newNumber;
return false; // Stop form submit
}
</script>
<form onsubmit="return ShowANumber();">
<input id="input" type="text"/>
<input type="submit"/>
</form>
<div>Result: <span id="result"></span></div>

Categories