I cant change value of Input - javascript

I want to create Javascript simple calculator, I want to change <input> tag's value on click, I used this
document.getElementById('input').value = "1"
But it types once 1 so I can't type 11 or 111. What is problem? Can you help me?

I don't know if that's the correct answer as OP's code wasn't provided...
var el = document.getElementById('input');
el.value = 1;
var button = document.getElementById('button')
button.onclick = function() {
el.value = parseInt(el.value) + 1;
}
<input id="input" type="text" name="name" value="">
<button id="button">Add 1!</button>
On button click, the function will retrieve the value from the input box, convert it to integer and then add 1.
If that's not the answer you were looking for, let me know.
EDIT: Just to clarify.
I have used parseInt() to convert to integer. This way if el.value = 1
The result will be 2. However if I don't use parseInt() I would get a concatenation instead of an operation and el.value + 1 would do 11, el.value being a string.

First you have to get the value of that field as
var val = document.getElementById('input').value;
Then Add a value and show in it as
document.getElementById('input').value = val + 1;
Here is a complete Running code:
function function_name (argument) {
var val = document.getElementById('input').value;
document.getElementById('input').value = val + 1;
}
<input id="input" type="text" name="name" value="">
<button id="button" onclick="function_name()">Press 1!</button>

Related

How to insert the value of input to another inputs in JS?

Why can't I insert the value of an input into another input? The following example doesn't work:
document.getElementById("input").oninput = () => {
const input = document.getElementById('input');
const output = document.getElementById('output');
// Trying to insert text into 'output'.
output.innerText = input.value;
};
<input id="input" placeholder="enter value of temperature" />
<br>
<input id="output" />
Thank you!
You should use .value instead of .innerText to set the value to an input element, like:
output.value = input.value;
document.getElementById("input").oninput = () => {
const input = document.getElementById('input');
const output = document.getElementById('output');
output.value = input.value;
};
<input id="input" placeholder="enter value of temperature" />
<br>
<input id="output" />
may be this will be helpful. as per my knowledge. your code will not work on IE. because arrow functions are not supported in IE. however error in your code is "value1.innerText" which is not a right property. because in your code you can see.
value1.innerText=currentValue.value
so if you are fetching value using 'value' property of input. you have to assign a same property for another input box.
so function will be something like this.
var convertTemperature = function convertTemperature() {
var currentValue = document.getElementById("currentValue");
var value1 = document.getElementById("value1");
value1.value = currentValue.value;
};
You can get real time value by below code,
jQuery('input#currentValue').change(function(){
var current_value = jQuery('input#currentValue').val();
jQuery('input#value1').val(current_value );
});

How to display rounded values in a form and show on focus the original values?

I have numeric values with many decimal places and the precision is required for other functions. I want to present the values in a form, so the user can change the values if necessary.
To increase the readability, I want to display the values rounded to 2 decimal places, but if the user clicks on an input field, the complete value should be presented. By doing this, the user can see the real value and adjust them better.
Example:
HTML
<button id="myBtn" onclick="fillForm()">Try it</button>
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" onchange="myFunction()" >
</fieldset>
</form>
JavasSript
<script>
//Example values that should be presented
var x = 3.14159265359;
function fillForm(){
document.getElementbyId("myInput1").value = x;
}
function myFunction(){
x = document.getElementbyId("myInput1");
}
</script>
The form input value should be " 3.14 " and if the user clicks in the field, the displayed value should be 3.14159265359.
Now the user can change the value and the new value has to be saved.
Because this is for a local 1 page website with no guaranty of internet connection, it would be an asset but not a requirement, to do it without an external script (jquery …).
you can use focus and blur event to mask/unmask you float, then simply store the original value in a data param, so you can use the same function to all input in your form ;)
function fillForm(inputId, val)
{
var element = document.querySelector('#'+inputId);
element.value = val;
mask(element);
}
function mask(element) {
element.setAttribute('data-unmasked',element.value);
element.value = parseFloat(element.value).toFixed(2);
}
function unmask(element) {
element.value = element.getAttribute('data-unmasked') || '';
}
<button onclick="fillForm('myInput1',3.156788)">Fill!</button>
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" onblur="mask(this)" onfocus="unmask(this)" >
</fieldset>
</form>
Edit: added "fillForm()" :)
Just use .toFixed(). It accepts one argument, an integer, and will display that many decimal points. Since Javascript primitives are immutable, your x variable will remain the same value. (also when getting/setting the value of an input use the .value property
function fillForm(){
document.getElementbyId("myInput1").value = x.toFixed(2);
}
If you need to save it you can store it in a new value
var displayX = x.toFixed(2)
Here is my solution. I hope you have other suggestions.
HTML
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" >
</fieldset>
</form>
<button id="myBtn" onclick="fill_form()">fill form</button>
JavasSript
<script>
var apple_pi = 10.574148541;
var id_form = document.getElementById("myForm");
//Event listener for form
id _form.addEventListener("focus", copy_input_placeh_to_val, true);
id _form.addEventListener("blur", round_input_2decimal, true);
id _form.addEventListener("change", copy_input_val_to_placeh, true);
// Replace input value with input placeholder value
function copy_input_placeh_to_val(event) {
event.target.value = event.target.placeholder;
}
// Rounds calling elemet value to 2 decimal places
function round_input_2decimal(event) {
var val = event.target.value
event.target.value = Number(val).toFixed(2);
}
// Replace input placeholder value with input value
function copy_input_val_to_placeh(event) {
event.target.placeholder = event.target.value;
}
// Fills input elements with value and placeholder value.
// While call of function input_id_str has to be a string ->
//fill_input_val_placeh("id", value) ;
function fill_input_val_placeh (input_id_str, val) {
var element_id = document.getElementById(input_id_str);
element_id.placeholder = val;
element_id.value = val.toFixed(2);
}
// Writes a value to a form input
function fill_form(){
fill_input_val_placeh("myInput1", apple_pi);
}
</script>
Here is an running example
https://www.w3schools.com/code/tryit.asp?filename=FLDAGSRT113G
Here is solution, I used focus and blur listeners without using jQuery.
I added an attribute to input named realData
document.getElementById("myInput1").addEventListener("focus", function() {
var realData = document.getElementById("myInput1").getAttribute("realData");
document.getElementById("myInput1").value = realData;
});
document.getElementById("myInput1").addEventListener("blur", function() {
var realData = Number(document.getElementById("myInput1").getAttribute("realData"));
document.getElementById("myInput1").value = realData.toFixed(2);
});
function fillForm(value) {
document.getElementById("myInput1").value = value.toFixed(2);
document.getElementById("myInput1").setAttribute("realData", value);
}
var x = 3.14159265359;
fillForm(x);
<button id="myBtn" onclick="fillForm()">Try it</button>
<form id="myForm" >
<fieldset>
<input type="text" id="myInput1" realData="" onchange="myFunction()" >
</fieldset>
</form>
jsfiddle : https://jsfiddle.net/mns0gp6L/1/
Actually there are some problems that needs to be fixed in your code:
You are redeclaring the x variable inside your myFunction function with var x =..., you just need to refer the already declared x without the var keyword.
Instead of using document.getElementById() in myFunction, pass this as a param in onchange="myFunction(this)" and get its value in the function.
Use parseFloat() to parse the value of your input to a float, and use .toFixed(2) to display it as 3.14.
This is the working code:
var x = 3.14159265359;
function fillForm() {
document.getElementById("myInput1").value = x.toFixed(2);
}
function myFunction(input) {
x = parseFloat(input.value);
}
To display the original number when you click on the input you need to use the onfocus event, take a look at the Demo.
Demo:
var x = 3.14159265359;
function fillForm() {
document.getElementById("myInput1").value = x.toFixed(2);
}
function focusIt(input){
input.value = x;
}
function myFunction(input) {
x = parseFloat(input.value);
}
<button id="myBtn" onclick="fillForm()">Try it</button>
<form id="myForm">
<fieldset>
<input type="text" id="myInput1" onchange="myFunction(this)" onfocus="focusIt(this)">
</fieldset>
</form>

Javascript Replace onKeyUp event with a string

Im not very good at JavaScript and need a hand with what I think is an easy script. Basically I have an input box that when the user types in a key it will disappear and change to whatever string I have. I could only get the one letter to change, so that I have something to show what i mean. So whenever a user types a message it gets replaced with an "h", what I want though is to have "hello" typed out letter by letter and not just "h" all the time and not "hello" all at once.
Here is the code.
<form action=# name=f1 id=f1 onsubmit="return false">
<input type=text name=t1 id=t1 value="" size=25 style="width:300px;"
onkeypress="if(this.value.match(/\D/))"
onkeyup ="this.value=this.value.replace(/\D/g,'h')">
</form>
JUST EDITED AS IT IS GIVING JS ERROR HOPE YOU WONT MIND:Are you trying something like this:
function replaceString(el){
var sampleText = "hello".split("");
var value = "";
console.log(el)
el.value.split("").forEach(function(str, index){
value += sampleText[index%sampleText.length];
});
el.value = value;
}
<form action=# name=f1 id=f1 onsubmit="return false">
<input type=text name=t1 id=t1 value="" size=25 style="width:300px;"
onkeypress="if(this.value.match(/\D/));"
onkeyup ="replaceString(this);"/>
</form>
If you want to simulate typing text into the textbox then you will need to use a timeout. The following function should suffice:
function simulateTyping(str, el)
{
(function typeWriter(len)
{
var rand = Math.floor(Math.random() * (100)) + 150;
if (str.length <= len++)
{
el.value = str;
return;
}
el.value = str.substring(0,len);
if (el.value[el.value.length-1] != ' ')
el.focus();
setTimeout(
function()
{
typeWriter(len);
},
rand);
})(0);
}
You'll need to pass it two parameters : the string to type e.g. "hello" and the element into which to type the string. Here's a simple wrapper function:
function typeHello() {
var el = document.getElementById('t1');
var str = 'hello';
simulateTyping(str, el);
}
When you call the typeHello function it will find the element with the "t1" id and type the "hello" text.

How can I convert text typed in an input box to lower case?

I can't figure out how to convert the text typed into a text input box (txtQuestion) into all lower case, i.e. typing "input" or "INpUt" will be read the same and output the same result.
Use toLowerCase() function. Eg: "INPuT".toLowerCase();
exampleFunction = function(){
//First we get the value of input
var oldValue = document.getElementById('input').value;
//Second transform into lowered case
var loweredCase = oldValue.toLowerCase();
//Set the new value of input
document.getElementById('input').value = loweredCase;
}
<input id="input" type="text" onkeyup="exampleFunction()" />
You have to choose the events that you want to watch and then return to the input the same value but lowercase:
function InputLowerCaseCtrl(element, event) {
console.log(element.value)
return element.value = (element.value || '').toLowerCase();
};
InputLowerCaseCtrl.bindTo = ['blur'].join(' ');
document.addEventListener('DOMContentLoaded', function() {
var input = document.querySelector('.input-lowercase');
return input.addEventListener(InputLowerCaseCtrl.bindTo, InputLowerCaseCtrl.bind(this, input));
});
<input class="input-lowercase" type="text" />
You can convert any string input to lowercase using the String.prototype.toLowerCase function
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase
For you example with an input for txtQuestion.
var inputStringLowerCase = inputTxtQuestion.value.toLowerCase();
https://jsfiddle.net/fbkq2po4/

Dynamically adding HTML form fields based on a number specified by the user [duplicate]

This question already has answers here:
Dynamically creating a specific number of input form elements
(2 answers)
Closed 1 year ago.
I've a form field named Number of messages, and based on what number the user specifies, I want the exact number of text fields to be dynamically generated below to allow users to enter specified number of messages.
I have browsed through some examples where JQuery is used to generate dynamic form fields, but since I'm not acquainted with JQuery, those examples are a bit too complex for me to grasp. I do know the basics of JavaScript, and would really appreciate if I could find a solution to my query using JavaScript.
function addinputFields(){
var number = document.getElementById("member").value;
for (i=0;i<number;i++){
var input = document.createElement("input");
input.type = "text";
container.appendChild(input);
container.appendChild(document.createElement("br"));
}
}
and html code will be
Number of members:<input type="text" id="member" name="member" value=""><br />
<button id="btn" onclick="addinputFields()">Button</button>
<div id="container"/>
fiddle here
You can try something similar to this...
var wrapper_div = document.getElementById('input_set');
var btn = document.getElementById('btn');
btn.addEventListener('click', function() {
var n = document.getElementById("no_of_fields").value;
var fieldset = document.createElement('div'),
newInput;
for (var k = 0; k < n; k++) {
newInput = document.createElement('input');
newInput.value = '';
newInput.type = 'text';
newInput.placeholder = "Textfield no. " + k;
fieldset.appendChild(newInput);
fieldset.appendChild(document.createElement('br'));
}
wrapper_div.insertBefore(fieldset, this);
}, false);
No. of textfields :
<input id="no_of_fields" type="text" />
<div id="input_set">
<p>
<label for="my_input"></label>
</p>
<button id="btn" href="#">Add</button>
</div>
It is a simple task which is made simpler with jQuery. You need to first get the value from the input field for which you can use .val() or .value. Once you get the value, check if it is an integer. Now, simply use .append() function to dynamically add the elements.
HTML
<form id="myForm">
Number of Messages: <input id="msgs" type="text"> </input>
<div id="addmsg">
</div>
</form>
JAVASCRIPT
$("#msgs").on('change', function()
{
var num = this.value;
if(Math.floor(num) == num && $.isNumeric(num))
{
$("#addmsg").text('');
for(var i = 0; i < num; i++)
{
$("#addmsg").append("<input type='text'/><br/>");
}
}
});
Fiddle
Note, everytime the value in the input changes, I am first clearing the div by:
$("#addmsg").text('');
And then I loop and keep adding the input field. I hope this helps!

Categories

Resources