jquery dynamically print out value of input - javascript

I'm working on a dynamic calculation program to practice jquery, but so far it's not going well, I can store the values in a variable, of course (see code here).
<form>
Tafeltje van:
<input type="number" name="tafel" id="tafel" />
Aantal:
<input type="number" name="aantal" id="aantal" />
</form>
<div id="output"></div>
and the JS:
var tafel = $('#tafel').val();
var aantal = $('#aantal').val();
How would one be able to print out these values in output while the user is typing in the text fields?

You can bind your code with keyup or input event of the inputs. Then, once you have got the values, you can use either text() or html() to display the values in #output div in whatever format you want.
// $("input").on("keyup", function(){
$("input").on("input", function(){
var tafel = $('#tafel').val();
var aantal = $('#aantal').val();
$("#output").text("tafel: " + tafel + " aantal: "+aantal);
});//keyup

Related

Variable multiplier

I have created a simple calculator that takes variable #1 and variable #2 and multiplies them to generate a result.
When I change variable #1 the result instantly changes. However, when I change variable #2 the result remains unchanged.
How do I reconfigure my code so that the result instantly changes when either variable is altered?
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h6>Variable #1</h6>
<input id="var1">
<h6>Variable #2</h6>
<input id="var2">
<h6>Result</h6>
<input readonly="readonly" id="result">
<script>
$(document).ready(function(){
var mt=$("#var1");
mt.keyup(function(){
var total=isNaN(parseInt(mt.val()* $("#var2").val())) ? 0 :(mt.val()* $("#result").val())
$("#result").val(total);
});
});
</script>
You have many things going wrong here,
you need to bind keyup event in var1 textbox and var2 textbox both
Also, your multiply formula is also wrong. Here is the desire code:
$(document).ready(function(){
var mt=$("#var1,#var2");
mt.keyup(function(){
debugger;
var total= 0;
if(!isNaN(parseInt($("#var1").val())* parseInt(parseInt($("#var2").val())))){
total= parseInt($("#var1").val())* parseInt(parseInt($("#var2").val()));
}
$("#result").val(total);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h6>Variable #1</h6>
<input id="var1">
<h6>Variable #2</h6>
<input id="var2">
<h6>Result</h6>
<input readonly="readonly" id="result">
Consider binding keyup events on both #var1 and #var2 inputs using the following jQuery syntax #var1, #var2 to achieve this desired behaviour, as shown:
$(document).ready(function(){
// Select and bind keyup event to both "var" input elements using
// this syntax
$('#var1, #var2')
.keyup(function(){
// Adjust your keyup handler to perform calculation when keyup
// occurs on either input field
var total= 0;
if(!isNaN(parseInt($("#var1").val())* parseInt($("#var2").val()))){
total = parseFloat($("#var1").val())* parseFloat($("#var2").val());
}
$("#result").val(total);
});
});
I just want to answer in vanilla Javascript for future reference of the problem..
I make var1,var2 class="input", then querySelect them both, then loop them, so that when you put any number to them, their value(product) will be produce in the id="result"
if you did not put any number to them, the default value is zero(0) for both of them, so let say, you only put 10 to var1, then the output will only be 10, and if you put non numeric character, then the output is NaN.
let input = document.querySelectorAll(".input");
let var1 = document.querySelector("#var1");
let var2 = document.querySelector("#var2");
let output = document.querySelector("#result");
function result(var1=0,var2=0) {
output.value = Number(var1)*Number(var2);
}
for(let i=0;i<input.length;i++)
{
input[i].addEventListener(`keyup`,()=>result(var1.value,var2.value))
}
<h6>Variable #1</h6>
<input id="var1" class="input">
<h6>Variable #2</h6>
<input id="var2" class="input">
<h6>Result</h6>
<input readonly="readonly" id="result">
By the way you can also make the code much shorter by instead of putting the id var1,var2 value, you can instead just put the input class[0], and [1] it's the same..
so it can also be done this way.
let input = document.querySelectorAll(".input");
let output = document.querySelector("#result");
function result(var1=0,var2=0) {
output.value = Number(var1)*Number(var2);
}
for(let i=0;i<input.length;i++)
{
input[i].addEventListener(`keyup`,()=>result(input[0].value,input[1].value))
}
<h6>Variable #1</h6>
<input id="var1" class="input">
<h6>Variable #2</h6>
<input id="var2" class="input">
<h6>Result</h6>
<input readonly="readonly" id="result">
By the way if you want to follow the same logic by using ternary operator,
let's follow his example, by using ternary operator,
change the result function to this.
function result(var1=0,var2=0) {
(var1*var2 ===0)? output.value=0: output.value=Number(var1) * Number(var2);
}

Syntax for Displaying name of a textbox with alert

How can i show the name "First Textbox Name", I have tried a multitude of things but nothing seems to work.
This is the text box among other textboxes.
<td>FirstTextbox Name:
<input id="box1" name="box1" class="nosonly" type="text" oninput="calculate()" /></td>
</td>
<script>
var x = document.getElementById("box1").WhatwouldGohere?
alert(x);
</script>
Textboxes don't have a closing tag and therefore cannot have any innerHTML.
But, you can access other aspects of a textbox. Also, don't use inline HTML event attributes (onclick, onmousover, etc.). Even though you see them used everywhere, it's only because a lot of new JavaScript folks pick up bad habits. There are many reasons not to use them.
// Get a reference to the textbox
var tb = document.getElementById("box1");
// Set up the event handler in JavaScript, not HTML
tb.addEventListener("input", calculate);
function calculate(){
// You can access HTML attributes as object properties:
console.clear();
// To get the content of the parent element, use the parentElement property
// Then, access the textContent of that element to only get text (and not
// nested child elements). Finally, strip off any leading or trailing
// spaces from that value (if desired) with .trim()
var parentText = this.parentElement.childNodes[0].textContent.trim();
alert("The text that preceeds the textbox is: " + parentText);
console.log("The name of the textbox is: " + box1.name);
console.log("There are " + this.value.length + " characters in the box.");
console.log("The value of the box is: " + this.value);
}
<td>FirstTextbox Name:
<input id="box1" name="box1" class="nosonly" type="text">
</td>
But, your question has asked about the textbox's "label" and it turns out that there is actually a <label> element that you can and should use because it creates a more accessible UI and makes this even easier:
// Get a reference to the textbox and the label
var tb = document.getElementById("box1");
var lbl = document.querySelector("label[for=box1]");
// Set up the event handler in JavaScript, not HTML
tb.addEventListener("input", calculate);
function calculate(){
// You can access HTML attributes as object properties:
console.clear();
alert("The text that preceeds the textbox is: " + lbl.textContent);
console.log("The name of the textbox is: " + box1.name);
console.log("There are " + this.value.length + " characters in the box.");
console.log("The value of the box is: " + this.value);
}
<td>
<label for="box1">FirstTextbox Name:</label>
<input id="box1" name="box1" class="nosonly" type="text">
</td>
Well, you do a basic mistake which many people does having no experience with the DOM model. Keep in mind that the code should be executed after the DOM is initialised, so if you want to show the name of the textarea do the following as it's visible that you are using jQuery:
<td>
<label>Label for Box 1</label>
<textarea id="box1"></textarea>
</td>
<script>
$(function() {
alert("My box name is "+ $('#box1').prevAll('label').html());
});
</script>
if no label tag (which is not very clever BTW):
<td>FirstTextbox Name:
<input id="box1" name="box1" class="nosonly" type="text" oninput="calculate()" /></td>
</td>
<script>
$(function() {
alert("My box name is "+ $('#box1').parent().text());
});
</script>
Your initial code was showing that you are using jQuery.
This is a simple representation of your html combined with the code above:
alert($('<div>').html('<td>FirstTextbox Name: <input id="box1" name="box1" class="nosonly" type="text" /></td>').find('#box1').parent().text());
alerts FirstTextbox Name:
Try this
<script>
function calculate() {
var x = $('#box1').val();
alert(x);
}
</script>
<script>
function calculate() {
var x = $('#box1').attr('name')
alert(x);
}
</script>
That would alert the name of your textbox.
Or given your edit you could do:
<script>
function calculate() {
var x = document.getElementById("box1").getAttribute('name');
alert(x);
}
</script>

jQuery library to autopopulate multiple fields

I have multiple textboxes with set character limits that together make up a code. There is value in the boxes being separated for a variety of reasons. I want to be able to paste a complete code in the first textbox and have it automatically populate all the textboxes. Is there a way to do this in javascript or a jquery library for this case?
Currently I'm using jQuery autotab on each textbox and I'd prefer to keep that functionality.
DEMO
Use the onpaste event to capture the data from the user's clipboard. Then take that data and produce an array appropriate for your inputs. Then set those values using .val()
JS
$(function(){
// get first input element
pastable = document.getElementById('pastable');
// listen for the user to paste
pastable.onpaste = function(e){
// retrieve paste data as an array split to each 3 characters (3 dots below in regex)
var inputArray = e.clipboardData.getData('text/plain').match(/.../g);
// loop over input fields
$('input').each(function(i){
// place data from paste
$(this).val(inputArray[i]);
});
};
});​
HTML
<input type='text' id="pastable" maxlength="3"/>
<input type='text' maxlength="3" />
<input type='text' maxlength="3" />​
You can certainly do this in JS. I don't know about a library to do it for you through. Shooting from the hip here but maybe something like this:
Example HTML
<input type='text' data-auto-pop='true' data-group='1' data-char-limit='3'/>
<input type='text' data-auto-pop='true' data-group='1' data-char-limit='3'/>
<input type='text' data-auto-pop='true' data-group='1' data-char-limit='4'/>
Example JS
$("input[data-auto-pop='true']").change(function () {
var $this = $(this), val = $this.val();
if ($this.data("char-limit") > val.length) {
return;
} else {
var setVal = function() {
$this.val(val.slice(0, $this.data("char-limit"));
val = val.slice($this.data("char-limit"));
};
setVal();
while ($this.closest("input[data-group='"+$this.data("group")+"']") && val.length > 0) {
$this = $this.closest("input[data-group='"+$this.data("group")+"']");
setVal();
}
}
}
Probably has some mistakes in it but you should get the idea.

Calculate one variable based on changing input

I have the following function:
function updateInput(ish){
document.getElementById("BetAmount").value = ish;
}
I have the following HTML inputs:
<input class="defaultText" type="number" name="BetAmount" id="BetAmount" onchange="updateInput(this.value)">
<input type="number" name="PotentialGain" id="PotentialGain" />
When users enter in a bet amount number(BetAmount), I would like to instantly show a calculated PotentialGain, which, for example, can be found by multiplying a constant by the specified bet amount entered in by the user.
I'm not very familiar with JavaScript, so any help is greatly appreciated!
Your code is almost correct - you are showing the result in the BetAmount field so no change is visible.
Change your code to:
document.getElementById("PotentialGain").value = ish;
Here's a working demo. I changed the event to onkeyup as onchange only happens on blur - i.e. when a field loses focus.
Here is the final JQuery function that I used.
function changeBet(bet) {
var moneyline = <?php echo json_encode($win) ?>;
var gain = moneyline * bet;
document.getElementById("PotentialGain").value = gain;
}
Along with these inputs:
<input type="text" name="BetAmount[]" id="BetAmount" onkeyup="changeBet(this.value);" >
<input type="number" name="PotentialGain" id="PotentialGain" />

Persisting textbox value using jQuery

I'd like to save the newly entered values, so I could reuse them. However, when I try to do the following, it does not work:
// el is a textbox on which .change() was triggered
$(el).attr("value", $(el).val());
When the line executes, no errors are generated, yet Firebug doesn't show that the value attribute of el has changed. I tried the following as well, but no luck:
$(el).val($(el).val());
The reason I'm trying to do this is to preserve the values in the text boxes when I append new content to a container using jTemplates. The old content is saved in a variable and then prepended to the container. However, all the values that were entered into the text boxes get lost
var des_cntr = $("#pnlDesignations");
old = des_cntr.html();
des_cntr.setTemplate( $("#tplDesignations").html() );
des_cntr.processTemplate({
Code: code,
Value: val,
DivisionCode: div,
Amount: 0.00
});
des_cntr.prepend(old);
This is the template:
<div id="pnlDesignations">
<script type="text/html" id="tplDesignations">
<div>
<label>{$T.Value} $</label>
<input type="text" value="{$T.Amount}" />
<button>Remove</button>
<input type="hidden" name="code" value="{$T.Code}" />
<input type="hidden" name="div" value="{$T.DivisionCode}" />
</div>
</script>
</div>
You want to save the previous value and use in the next change event?
This example uses .data to save the previous value. See on jsFiddle.
$("input").change(function(){
var $this = $(this);
var prev = $this.data("prev"); // first time is undefined
alert("Prev: " + prev + "\nNow: " + $this.val());
$this.data("prev", $this.val()); // save current value
});
jQuery .data
If you want old/Initial text box value, you can use single line code as follows.
var current_amount_initial_value = $("#form_id").find("input[type='text']id*='current_amount']").prop("defaultValue");
If you want current value in the text box, you can use following code
$("#form_id").find("input[type='text']id*='current_amount']").val();

Categories