Refresh html input element value - javascript

I'm trying to change the value of a html input element and I want to see the value change on screen. This seems to be a very simple task but it is not working using javascript (but it work with jQuery).
$("#btn1").click(function () {
$("#test1").val("10");
});
function bt() {
document.getElementById("test1").value = "3333";
document.getElementById("test1").setAttribute("value","4444");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Formula 1:
<input type="text" id="test1" value="1111">
</p>
<p>What the answers to these formulas?</p>
<br>
<button id="btn1">Hint</button>
<button id="btn2" onclick="bt()">Hint2</button>
Any suggestion with the javascript function bt() ?

You can just use the value property of the input element after being selected/referenced in JavaScript.
In the next example, every time you click on the button with change value text the input value will change to New value: followed by a random number.
/** selecting the button and the input **/
const btn = document.getElementById('btn2'),
inp = document.getElementById('test1');
/** adding click listener **/
btn.addEventListener('click', () => inp.value = 'New value: ' + Math.ceil(Math.random() * 100)); /** for demo purposes a random number is generated every time the button is clicked. Change the affected value per your requirements **/
<input type="text" id="test1" value="1111">
<p>What the answers to these formulas?</p>
<br>
<button id="btn1">Hint</button>
<button id="btn2">change value</button>
Learn more on input element in JavaScript.
Hope I pushed you further.

Related

Append to value attribute on button click

I am trying to make an input modify each time I click on a button. Kind of like a calculator. The will start at 0. When I click on the button "7" it will change its value to 7, when I click on "4" it will change to 74. Basically like a calculator.
I made this code that does modify the value of the input, however I can't seem to find how I can append more values to that values. Here is my code. Could someone help me?
<input class="normal-input" type="number" step="0.01"> <!-- Value is NULL-->
<button value="7" class="my-buttons" type="button"> 7 </button> <!--Button to change the value of the input-->
$('.my-buttons').click(function(){
$(".normal-input").attr("value", $(this).attr('value'));
}); <!-- The actual function. -->
As you can see the function completely replaces the previous value for the new one. I want it to append the values like in a calculator.
I would suggest you to try doing this:
Initialize value to zero
whenever click is called, multiply the current value by 10, and add the button value to it.
and you can remove the step attribute as per the use case.
In this function:
$(".normal-input").attr("value", $(this).attr('value'));
The second parameter is the value to set:
$(this).attr('value')
You need to have this as a combination of the previous value and the new value:
$(".normal-input").attr('value') + '' + $(this).attr('value')
The blank string is to make sure the final result is a string, not the addition of 2 numbers.
If you would like to convert it to a number, you can use parseInt():
const combinedNumber = $(".normal-input").attr('value') + '' + $(this).attr('value')
const intNumber = parseInt(combinedNumber)
The final code could look something like:
<input class="normal-input" type="number" step="0.01"> <!-- Value is NULL-->
<button value="7" class="my-buttons" type="button"> 7 </button> <!--Button to change the value of the input-->
$('.my-buttons').click(function(){
const existingValue = $(".normal-input").attr('value')
const newValue = $(this).attr('value'
const combinedValue = parseInt(existingValue + '' + newValue)
$(".normal-input").attr("value", combinedValue);
}); <!-- The actual function. -->
You just need to concat both the actual value and the value of button which is clicked to get required values .
Demo Code :
$('.my-buttons').click(function() {
var value = $(".normal-input").val()
var clicked_button = $(this).attr('value')
//use val and combined both value
$(".normal-input").val(value + "" + clicked_button);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="normal-input" type="number">
<button value="7" class="my-buttons" type="button"> 7 </button>
<button value="10" class="my-buttons" type="button"> 10 </button>
<button value="6" class="my-buttons" type="button"> 6 </button>

fetch lookup fields value on div and set a input value

I managed to grab all calculated values on group of div and set the total, but they want to only show the lookup value to be showed. currently I showing the calculation on SPAN.
The var "multiplier"
I try to get all input values and set them using below code.
function getInputs(selector) {
var inputs = 0;
$(selector).each(function() {
$(this).find("input").each(function() {
sum += parseInt($(this).html());
$('#').val(parseInt($(this).html()));
var multiplier = $(`table#${tableToUse} tbody > tr[product='${currentProductId}'] > td[volume='${volume}']`).text();
// $('#GrandTotal').val(sum); // give the final sum from Log
});
});
return sum;
}
On the below codepen: https://codepen.io/dunya/pen/mojKNz
I am writing the final sum without any issues.
I would like to show the variable multiplier only.
I need hide the value=10 from user but show the variable multiplier.
My formula is like this:
the lookup value based on Product Origin, Geographical and Volume get the multiplier(as Var) I am getting that value:
sum for single input =multiplier * input value(example for apple it is 10)
I just need to overwrite the input value with multiplier(as Var) for all 10 input fields, I tried using function still not get to far,
any suggestion or how to do it.
thanks.
<div>
<label class="description" for="Apple">Apple</label>
<input id="Apple" name="Apple" class="element text medium" type="text" maxlength="255" value="10" readonly="true"/>
</div>
As you can see on above codepen link, I have ten ID's such as Apple,Apricot .. so on, I make it read only. each has default value for Apple it is 10 and Apricot is 20 it is changing value, I also make it read only to proven end user to change it. my requirement change changed I will need show the value multiplier variable there instead of the attribute value such 10 or 20 so on, problem is I am using value attribute to make the calculation work otherwise my final Grand Total calculation will be wrong. How can I resolve this.
for example I selected Product Origin: Europe, Location: blank and Volume= 10, this 3 drop down gets me the look up table id called "Europe". the Volume will match to the columns to calculate for apple it will 0.1 * 10 (default value for id=Apple is 10) so it gets me 1 so on, Grand Total is Sums all calculated results on SPAN to give final value.
How can still use or store the default value for each input such as 10 so on but replace with multiplier(as Var) such the 10 input will display Apple 0.1, Apricot 0, ... and Coconut 0.1, also remember the default value?
the mock-up shows on image below:
Many thanks
I'm using this answer to check if I got your question right so it will likely not be final!
Setting the Value of an input
If your problem is actually changing the input here are some simple examples:
// ****
// ** WITH JAVASCRIPT ** //
// ****
// Get DOM Elements
const js_input_foo = document.getElementById('js_input_foo');
const js_btn_change = document.getElementById('js_btn_change');
// Add event listener
js_btn_change.addEventListener('click', () => {
js_input_foo.value = 'New Value';
});
// ****
// ** WITH JQuery ** //
// ****
// Get DOM Elements
const jq_input_foo = $('#jq_input_foo');
const jq_btn_change = $('#jq_btn_change');
// Add event listener
jq_btn_change.click(() => {
jq_input_foo.val('New Value');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!--
** WITH JAVASCRIPT **
-->
<h2>JavaScript</h2>
<!-- Input which displays a value -->
<input id="js_input_foo" type="text" value="100" />
<!-- Button which changes the input -->
<button id="js_btn_change">Change!</button>
<!--
** WITH JAVASCRIPT **
-->
<h2>JQuery</h2>
<!-- Input which displays a value -->
<input id="jq_input_foo" type="text" value="100" />
<!-- Button which changes the input -->
<button id="jq_btn_change">Change!</button>
Setting the value of an input according to dataset
If you want to set your inputs with looping through them this could help:
// Constants
const dataset = {
one: "new date one",
two: "new date two",
three: "new date three",
four: "new date four",
five: "new date five"
};
// Dom elements
const container_inputs = document.getElementById('container_inputs');
const btn_changeInputs = document.getElementById('btn_changeInputs');
// Add Event Listener
btn_changeInputs.addEventListener('click', () => {
Array.from(container_inputs.children).forEach(child => {
let key = child.getAttribute('key'); // Get the Key Attribute
// If key attribute exists fill the corresponding entry
if(key) child.value = dataset[key];
});
});
<h2>Setting the corresponding values</h2>
<div id="container_inputs">
Input One <input type="text" id="input_one" key="one"> <br>
Input Two <input type="text" id="input_two" key="two"> <br>
Input Three <input type="text" id="input_three" key="three"> <br>
Input Four <input type="text" id="input_four" key="four"> <br>
Input Five <input type="text" id="input_five" key="five">
</div>
<button id="btn_changeInputs">Change!</button>
Getting an attribute and use it in calculations for value
So setting the value of an element dependent of an attribute and multiplier would then be:
// **
// JavaScript
// **
element.value = element.getAttribute('my_value') * multiplier;
// **
// JQuery
// **
// ****************************************************
// I STRONGLY RECOMMEND ONLY GETTING THE ELEMENT ONCE *
// ****************************************************
let element = $('#element'); // Getting the element
element.val(element.attr('my_value') * multiplier); // Setting the value
And the html element would look like:
<input type="text" id="element" my_value="100" />
I managed to fix it the issues, setting the value for each input was achieved by this line:
// Insert result after the current input field.
$(this).after(result);
and getting submit achieved by this line
sum += +$(this).text();
//console.log("Value sum "+sum);
$('#GrandTotal').val(sum);
As I show all result on span I used this below to hide
$( "span" ).hide();
working version on jsfiddle.net
https://jsfiddle.net/erkindunya/L3d4j8hv/17/
This might help one else who doing this

Javascript will not pass information into function from html

Ok so very new to Javascript. Trying to learn the code by simply changing the text on a button using an external javascript file. But I can't even get javascript to read the buttons valueexternally, in Chrome's debug tools I see my button value is btn="". It reads the button object but can't read its properties.
<html>
<head>
<title> Test </title>
<script type="text/javascript" src="Gle.js"></script>
</head>
<body>
<div><canvas id="Gle" width="800" height="600"></canvas>
</div>
<div>
<h2>Enter the mass and coordinates</h2>
<input id="txtbox" type="text" /><br/>
<button id="btn" onclick="change()">Add</button>
</div>
</body>
</html>
The Gle.js
"use strict";
function change() {
var x = document.getElementById("btn").value;
var elem = document.getElementById("btn");
var txt = document.getElementById("txtbox");
txt.text = elem.value;
elem.value = "Ok";
}
When I debug the x value it is "", nothing changes on my screen. I am using brackets IDE.
x is empty because '#btn' doesn't have the 'value' attribute specified. The "Add" string is inside its inner HTML (or text),
alert(document.getElementById("btn").innerText);
And you can index this in the event scope, it's a reference of '#btn', this.innerText.
A alternative is to get the '#btn' child nodes values, which is cross-browser.
alert(this.childNodes[0].nodeValue);
This alert the first text specified in the element inner.
I'm expecting to have the button title "Add" appear?
The button doesn't have a value attribute so its value property is an empty string.
"Add" is the content of the text node inside the button element.
var x = document.getElementById("btn").firstChild.data;
You can try by assigning value attribute to your button
<button id="btn" onclick="change()" value="Add">Add</button>
If you want to update the text of a button based on what's in the input box the code could look like this:
<button id="myButton">Change Me</button>
<input id="myInput" type="text" value="To This"/>
and in the JS:
document.getElementById("myButton").click(function(){
var inputValue = document.getElementById("myInput").value
document.getElementById("myButton").innerText = inputValue
// You could also use 'this' to refer to document.getElementById("myButton"):
// this.innerText = inputValue
})

alerting the value of an input type number

Here is the code that I am having problems with. Below it I'll add an explanation:
$(function() {
var $input = $("#input");
var input = $input.val();
var $go = $("#go");
$go.click(function() {
alert(input);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<input type="number" id="input">
<button type="button" id="go">GO!</button>
</main>
The code above is a dummie example to represent my actual question, no more background is needed.
So I have one input type="number" id="input" in which you input a number, and a button type="button" id="go".
In my jQuery, I first declare $input which holds the element #input, then input which holds the value of the element #input, and finally $go which holds the element #go.
Below that I have a function, that says that when I click on #go, I should be able to alert(input).
Now, this code does not do that. In my head this makes perfect sense, but apparently it doesn't work.
That is because you are declaring input outside the click function, which means the value (simply an empty string) is set at runtime and will not be updated. You should define input within your click event handler:
$(function() {
var $input = $("#input");
var $go = $("#go");
$go.click(function() {
var input = $input.val();
alert(input);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<input type="number" id="input">
<button type="button" id="go">GO!</button>
</main>
First of all, StackOverflow seems to block alerts origination from the code snippet, it will be much easier to output them to the console instead so you can keep track of things.
Your code can be simplified way down without the need for many variables.
But your main problem was the fact that the input value was not getting reset when the click event happened but was getting picked up on page load, meaning it would be stuck at ''.
$(function() {
$("#go").click(function() {
var input = $("#input").val();
console.log(input);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<input type="number" id="input">
<button type="button" id="go">GO!</button>
</main>

Need help using increments and displaying in a textbox

We need to have a textbox where you enter a number, hit a button, and it increments by 1, while staying in the same text box. Here is the code I have so far:
<form action=#>
<p>
Current Count...<input type="text" id="txtCounter" value="0">
</p>
<p>
<input type="button" value="Increment Count" id="btnIncrement" onclick="btnIncrement_onclick()">
<input type="reset">
</p>
</form>
<noscript>This website requires JavaScript to be enabled.</noscript>
JavaScript:
function btnIncrement_onclick() {
// get textbox and assign to a variable
var countTextbox = document.getElementById("txtCounter");
var txtCounterData = txtCounter.value;
var countTextbox.value = 0++;
}
If someone could explain to me how to do it not just give me the answer. I don't know why I'm having such a hard time with this.
Try the following simple code :
function btnIncrement_onclick()
{
//asign the textbox to variable
var textbox = document.getElementById("txtCounter");
//Get the value of textbox and add 1 then update the textbox
textbox.value = parseInt(textbox.value)+1;
}
<form action=#>
<p>
Current Count...<input type="text" id="txtCounter" value="0">
</p>
<p>
<input type="button" value="Increment Count" id="btnIncrement" onclick="btnIncrement_onclick()">
<input type="reset">
</p>
</form>
<noscript>This website requires JavaScript to be enabled.</noscript>
Hope this helps.
In your HTML:
In your html you had a onclick="btnIncrement_onclick()" and that means every click will triggers your function.
In your JS:
function btnIncrement_onclick() {
// Named as countTextbox you input. sou we can use it later.
var countTextbox = document.getElementById("txtCounter");
// Get the current value attribute of it, initialy 0.
var txtCounterData = txtCounter.value;
// The line above is not being used. but you can check it with a console.log like this:
console.log(txtCounterData);
// Now you are calling again your input and changing his value attribute. this ++ means a increment. so we are increasing +1;
countTextbox.value++;
}
You should read more about increment and operators and DOM (the way whe select the tag by id, and again selected his attribute).
Sorry didn't found a good source in english.

Categories

Resources