The input number value on click and on change using control buttons - javascript

What event should I use to get an input number value where the value is changed typing or changed with button,
<p><input id="multiplier" type="number"></p>
change doesn't work when types only using the buttons
$('#multiplier').change(function(){
var value = $(this).val();
});

let multiplier = document.getElementById("multiplier");
multiplier.addEventListener("input",function(){
let value = this.value;
console.log(value)
})
<p><input id="multiplier" type="number"></p>

You can combine two event triggers like this:
$('#multiplier').on('keyup change', function(){
var value = $(this).val();
console.log(value)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><input id="multiplier" type="number"></p>

Related

Find the value entered by a color input in Javascript

I am trying to code a very simple color picker but I have been stuck on how to get the value of the color that the user picked into javascript. This is my code:
<input type="color" value="#ff0000">
<script>
const input = document.querySelector("input")
input.addEventListener("change")
const color = e.target.value;
console.log(rgb);
</script>
Thanks in advance!
You have to add a handler function in which you have to get the color:
const input = document.querySelector("input")
input.addEventListener("change", function(event){
const color = event.target.value;
console.log(color);
});
<input type="color" value="#ff0000">
You will get the color value like this
<input type="color" id="myColor" value="#ff0000">
var colorval = document.getElementById("myColor").value;
There are several issues with your code.
First, I'd add an id attribute to your input and use getElementById().
You also need to pass 2 arguments to addEventListener, the first one being on what event to trigger (here on change) and the second a function which will run when that event occurs. The function takes a parameter e (the event) from which you can access e.target.value and use it as you wish.
<input id="color-picker" type="color" value="#ff0000">
<script>
const input = document.getElementById("color-picker")
input.addEventListener("change", function(e) {
const color = e.target.value;
console.log(color);
});
</script>

getting the value of a textbox when user enters the name/id of the field

Using jquery to get the value of a textbox.
BUT
i need to enter the id of the textbox, then use that value to get the value of the textbox using jquery.
var tt = $("#fieldname").val()
that works
now how do i enter the fieldname at runtime, and get jquery to execute the val command as if it was hard coded?
There are a few ways that you could do this. One way is to listen to one of the keyboard or change events on the textbox you enter the id into, to help determine when the input has changed. So for example
$("#inputText").on("keyup", function(keyupEvent){
var textboxId = $("#inputText").val();
var textboxIdValue = $("#" + textboxId).val();
});
Or another way could be to use a click event with similar kind of logic, so for example
$("#clickMe").on("click", function(){
var textboxId = $("#inputText").val();
var textboxIdValue = $("#" + textboxId).val();
})
An example for the use case of both can be seen here https://fiddle.jshell.net/xpvt214o/114584/
Here is an example for you to get started with:
<body>
<p>Type "one" or "two" below</p>
<input id="search" />
<input id="one" value="This input is #one" />
<input id="two" value="And this is #two" />
<p id="result">No input specified</p>
</body>
And the corresponding jQuery code:
// Cache jQuery elements for performance and readability
var $search = $("#search");
var $result = $("#result");
$search.on("change", function() {
var search_value = $search.val();
if (search_value.length) {
search_value = "#" + search_value.toLowerCase().trim(); // Sanitise user input
if ($(search_value).length) {
$result.text($(search_value).val());
} else {
$result.text("Input not found");
}
} else {
$result.text("No input specified");
}
});
This will show the value of the specified input, if it exists.
You can see it in action here: https://jsfiddle.net/jeevantakhar/xpvt214o/114558/

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>

Read dynamically updated attribute value jquery

I have a situation over here. I'm writing this situation in a chronology.
Assume that there are an input[type=number] and a button.
When the button is clicked, it will change the attribute value (data-oldval="") to the current value of the input number.
The next time I click the button, it supposed to add the current value in the input with the number in the data-oldval attribute.
But the problem is, I can't read the newly updated attribute value.
To make the situation clearer, I included the code snippet below. I hope that anybody here can help me with this.
var response = $('.response');
$('body').on('click', '.btn', function() {
var btn = $(this),
t = btn.parent('.dummy'),
n = t.find('input[type=number]'),
val = n.val(),
oldval = n.data('oldval');
n.attr('data-oldval', val+oldval);
response.text(n.data('oldval'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dummy">
<input type="number" value="1" data-oldval="0">
<button class="btn" type="submit">Add</button>
</div>
<div class="response"></div>
Two issues; you need to retrieve the value using data('oldval'), not attr(), and you also need to convert val() to an integer so it can be added to the old value. Try this:
var response = $('.response');
$('body').on('click', '.btn', function() {
var btn = $(this),
t = btn.parent('.dummy'),
n = t.find('input[type=number]'),
val = parseInt(n.val(), 10),
oldval = n.data('oldval');
n.data('oldval', val + oldval);
response.text(n.data('oldval'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dummy">
<input type="number" value="1" data-oldval="0">
<button class="btn" type="submit">Add</button>
</div>
<div class="response"></div>
You need to parse the number entered into the input or it will be returned as a string and concatenated when setting val + oldval
console.log(typeof(val)) // string
val = parseInt(n.val());
You can also set the attribute by using the jQuery data method, the same way you're retrieving it to update the response element.
n.data('oldval', val + oldval);
See https://jsfiddle.net/aso1s0xz/
There is already a great answer but here is solution without data-oldval as I don't see why is it needed in this case.
$('body').on('click', '.btn', function() {
var response = parseInt($('.response').text());
if(isNaN(response))response=0;
var val = parseInt($('input').val());
var sum = val+response;
$('.response').text(sum);
})
To get dynamic Value Try JS, It will work perfectly
document.getElementById('element-id').getAttribute('data-oldval');
Use the Data() method in jQuery to set the value too:
var response = $('.response');
$('body').on('click', '.btn', function() {
var btn = $(this),
t = btn.parent('.dummy'),
n = t.find('input[type=number]'),
val = n.val(),
oldval = n.data('oldval');
n.data('oldval', parseInt(val)+parseInt(oldval));
response.text(n.data('oldval'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dummy">
<input type="number" value="1" data-oldval="0">
<button class="btn" type="submit">Add</button>
</div>
<div class="response"></div>

press button and value increases in text box

So when the page loads the text box will contain a stored value. I want the user to press the '+' button and the value in the text box will increase by one. Im guessing this is done with JQuery...Any ideas on where to get started so far I have...
<input type="text" name="BoqTextBox" id="BoqTextBox" value="0" />
<input type="Button" value="+" onclick="AddOne(document.getElementById('BoqTextBox').value)" />
<script>
function Add(data) {
//so the current digit is passed to here, where I need to do some funky code
//where it increments the current digit by one and stores it in BoqTextBox - replacing the old digit.
//Also to note if the text box contains 124.54 for example and + is pressed
//then new value will be 125.54
}
</script>
Any assistance with this would be great.
Thank you
...something like data = data + 1, but then how do I return the value into the text box?
You can use jQuery's val() to fetch and set a value. In this case the code you need could look like this (demo):
<input type="text" name="BoqTextBox" id="BoqTextBox" value="0" />
<input type="Button" id='AddButton' value="+" />
<script>
$('#AddButton').on('click', function () {
var input = $('#BoqTextBox');
input.val(parseFloat(input.val()) + 1);
})
</script>
$('input[type="button"]').on('click', function() { // bind click event to button
$('#BoqTextBox').val(function() { // change input value using callback
return ++parseFloat( this.value, 10); // make value integer and increment 1
})
});
you are callin Addone function inline so that means your function should be AddOne()
try this
function AddOne(obj){
var value=parseFloat(obj) + 1;
$('#BoqTextBox').val(value);
}
$("#buttonId").click(function()
{
var txtBox = $("#boqtextbox");
if(!isNaN(txtBox.val()))
{
txtBox.val(parsFloat(txtBox.val())+1) ;
}else
{
//do validation or set it to 0
txtBox.val(0);
}|
});

Categories

Resources