calculation using decimal number field - javascript

I'm trying to make a calculation using number fields that have set decimal places.
While the decimals are being displayed properly, the calculation is not running. Here is my javascript:
function setZeroNumberDecimal(el) {
el.value = parseFloat(el.value).toFixed(0);
};
function setThreeNumberDecimal(el) {
el.value = parseFloat(el.value).toFixed(3);
};
$(document).ready(function(){
$(".calc").keyup(function(){
var areasf = +$(".SF").val();
$("#acre").val(areasf/43560);
});
});
And the HTML:
<input type="number" onchange="setZeroNumberDecimal(this)" name="grosslandSF" class="calc SF">
<input type="number" onchange="setThreeNumberDecimal(this)" name="grosslandacre" disabled="disabled" id="acre">
Any help would be great.

Instead of inline onchange event you can use oninput event.
When you change a value like in:
$("#acre").val(areasf/43560)
this will not fire the corresponding event, so you must do it by yourself:
$("#acre").val(areasf/43560).trigger('input');
The snippet:
function setZeroNumberDecimal(el) {
el.value = parseFloat(el.value).toFixed(0);
};
function setThreeNumberDecimal(el) {
el.value = parseFloat(el.value).toFixed(3);
};
$(document).ready(function(){
$(".calc").keyup(function(){
var areasf = +$(".SF").val();
$("#acre").val(areasf/43560).trigger('input');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="number" oninput="setZeroNumberDecimal(this)" name="grosslandSF" class="calc SF">
<input type="number" oninput="setThreeNumberDecimal(this)" name="grosslandacre" disabled="disabled" id="acre">
</form>

Related

JavaScript calculate % of number in <input> field

I have 2 input fields:
<input id="input1" etc />
<input id="answer" etc />
What I want to do is when a user types in a numerical value (and to restrict them to numbers, no letters or special characters) in "input1" then "answer" input field shows what 0.0015% is of that number (i.e. user types in 35000 so in the answer field it would show 52.5 as that's 0.0015% of the number they entered). This is to be done real time with no submit or calculate button.
How can I do this?
You can do this way to add keyup event on your first input element. I've used vanilla JS though you've used jquery on your fiddle. My fiddle,
function myFunction() {
var inputVal = document.getElementById("input").value;
var answerVal = document.getElementById("answer");
var percentage = (0.0015/100) * parseInt(inputVal,10) * 100;
if(inputVal !== ''){
answerVal.value = (Math.round( percentage * 100 ) / 100).toFixed(1)
}else{
answerVal.value = '';
}
}
input:<input id="input" type="number" onkeyup="myFunction()"/>
answer:<input id="answer" type="text" value=""/>
Your code is almost working perfectly, but it was not working in the given example by you and the reason for that is you have used parseint function of javascript which does not allow decimal values, and to restrict numbers you can use input type number.
$(function(){
$('#pointspossible').on('input', function() {
calculate();
});
$('#pointsgiven').on('input', function() {
calculate();
});
function calculate(){
var pPos = $('#pointspossible').val();
var pEarned = $('#pointsgiven').val();
var perc="";
if(isNaN(pPos) || isNaN(pEarned)){
perc=" ";
}else{
perc = ((pEarned*pPos) / 100);
}
$('#pointsperc').val(perc);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='number' id="pointspossible"/>
<input type='number' id="pointsgiven" />
<input type='text' id="pointsperc" disabled/>

dynamically detect if textbox value is change

Is it possible to detect the change of a textbox even if that textbox value is not entered by user like the below scenario? I have some scenarios like when the page is loading for the first time the texbox get loaded with data.
$("#txt1").change(function(){
$("#txt2").val("1")
//$("#txt2").change();
});
$('#txt2').on("change", function() {
// some computation will happen here.
alert("1");
});
$("#btn1").click(function(){
$("#txt2").val("1");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="txt1">
<input type="text" id="txt2" name='text1'>
<button id="btn1">
Click
</button>
The value changed by JavaScript does not trigger any event so you just can't catch event in this case.
You can implement a watcher to your input value using interval
var oldValue = $("#txt2").val();
setInterval(function() {
var currentValue = $("#txt2").val();
if (currentValue !== oldValue) {
$("#txt2").trigger("change");
oldValue = currentValue;
}
}, 100);
$("#txt1").change(function(){
$("#txt2").val("1")
});
$('#txt2').on("change", function() {
// some computation will happen here.
alert("1");
});
$("#btn1").click(function(){
$("#txt2").val("1");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="txt1">
<input type="text" id="txt2" name='text1'>
<button id="btn1">
Click
</button>
As you know that on textbox1 change event you are changing second textbox value, you need to trigger it manually
$(document).ready(function () {
$("#txt1").change(function () {
$("#txt2").val("1")
$("#txt2").trigger("change");
});
$("#txt2").change(function () {
alert("1");
});
})

Copy text of a field into another automatically

I need to copy the text entered in a field (whether it was typed in, pasted or from browser auto-filler) and paste it in another field either at the same time or as soon as the user changes to another field.
If the user deletes the text in field_1, it should also get automatically deleted in field_2.
I've tried this but it doesn't work:
<script type="text/javascript">
$(document).ready(function () {
function onchange() {
var box1 = document.getElementById('field_1');
var box2 = document.getElementById('field_2');
box2.value = box1.value;
}
});
</script>
Any ideas?
You are almost there... The function is correct, you just have to assign it to the change event of the input:
<script type="text/javascript">
$(document).ready(function () {
function onchange() {
//Since you have JQuery, why aren't you using it?
var box1 = $('#field_1');
var box2 = $('#field_2');
box2.val(box1.val());
}
$('#field_1').on('change', onchange);
});
$(document).ready(function() {
$('.textBox1').on('change', function() {
$('.textBox2').val($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="textBox1"/>
<input type="text" class="textBox2"/>
If you are using jQuery, it is very easy - you need just register the right function on the right event :)
Here's the code:
<input id="foo" />
<input id="bar" />
$(function(){
var $foo = $('#foo');
var $bar = $('#bar');
function onChange() {
$bar.val($foo.val());
};
$('#foo')
.change(onChange)
.keyup(onChange);
});
JSFiddle: http://jsfiddle.net/6khr8e2b/
Call onchange() method on the first element onblur
<input type="text" id="field_1" onblur="onchange()"/>
try with keyup event
<input type="text" id="box_1"/>
<input type="text" id="box_2"/>
$('#box_1').keyup(function(){
$('#box_2').val($(this).val());
})
Try something like:
$(document).ready(function () {
$('#field_1').on('change', function (e) {
$('#field_2').val($('#field_1').val());
});
});
Heres a fiddle: http://jsfiddle.net/otwk92gp/
You need to bind the first input to an event. Something like this would work:
$(document).ready(function(){
$("#a").change(function(){
var a = $("#a").val();
$("#b").val(a);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="a" />
<input type="text" id="b" />
If you want that the value of the second field is updated as the same time that the first one, you could handle this with a timeout.
Each time a key is pressed, it will execute the checkValue function on the next stack of the execution. So the value of the field1 in the DOM will already be updated when this function is called.
var $field1 = $("#field_1");
var $field2 = $("#field_2");
$field1.on("keydown",function(){
setTimeout(checkValue,0);
});
var v2 = $field2.val();
var checkValue = function(){
var v1 = $field1.val();
if (v1 != v2){
$field2.val(v1);
v2 = v1;
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="field_1" value=""/><br/>
<input id="field_2" value=""/>

Validating textbox on copy paste in mvc

I have a textbox that has variable maxlenght based on some condition. There are keyup and keydown events associated with the textbox. On paste my maxlenght validation fails.If "Location" is selected the type of textbox is number with maxlenght 6, for other the type is text with maxlen 11 and 15 respectively "
$(document).on("pageinit", function (event) {
$('input[type="text"]').on('keyup keydown', function (event) { /*Some validation*/} });
$('input[type="number"]').on('keyup keydown', function (event) { /*Some validation*/} });
JQuery
$(document).ready(function() {
var characters ;
$("#text").keyup(function(){
if($('#vehicle').prop('checked')){
characters=5;
}
else{
characters=10;
}
if($(this).val().length > characters){
$(this).val($(this).val().substr(0, characters));
}
});
});
HTML
<input type="checkbox" id="vehicle" value="Bike">I have a bike<br>
<input type="text" id="text"/>
SEE DEMO HERE
I used paste event to trigger keyup event because only using paste event I can somehow get the input but I couldn't manipulate the input given. Here's how I found a way -
$(".AlphaValidateOnPaste").on('paste', function(e) {
$(e.target).keyup();
});
$('.AlphaValidateOnPaste').on('keyup',function(e){
var value = $(this).val();
var i = value.length;
while (i--) {
var result = value.charAt(i).match(/^[a-zA-Z ]*$/);
if(result == null){
$(this).val('');
alert('Only Alphabates and Spaces');
break;
}
}
});
<label for="name">Name <span class="required">*</span></label>
<input type="text" name="employee_name" class="form-control AlphaValidateOnPaste" id="employee_name" required>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>

How to create an event handler for a range slider?

I'm trying to get a range slider to work but I can't.
How do I add an event handler so when the user chooses a value my code reads that value. Right now its value is always 1.
I would like to do this using pure Javascript.
HTML:
<div id="slider">
<input class="bar" type="range" id="rangeinput" min="1" max="25" value="1" onchange="rangevalue.value=value"/>
<span class="highlight"></span>
<output id="rangevalue">1</output>
</div>
JAVASCRIPT:
var rangeInput = document.getElementById("rangeinput").value;
var buttonInput = document.getElementById("btn");
if (buttonInput.addEventListener) {
buttonInput.addEventListener("click", testtest, false);
}
else if (buttonInput.attachEvent) {
buttonInput.attachEvent('onclick', testtest);
}
function testtest(e) {
if (rangeInput > 0 && rangeInput < 5) {
alert("First");
} else {
alert("Second");
}
}
JSFIDDLE
Single Read
The problem is that you're only reading the value once (at startup), instead of reading it every time the event occurs:
// this stores the value at startup (which is why you're always getting 1)
var rangeInput = document.getElementById("rangeinput").value;
You should be reading the value in the handler instead:
function testtest(e) {
// read the value from the slider:
var value = document.getElementById("rangeinput").value;
// now compare:
if (value > 0 && value < 5) {
alert("First");
} else {
alert("Second");
}
}
Or to rewrite your code:
var rangeInput = document.getElementById("rangeinput");
var buttonInput = document.getElementById("btn");
if (buttonInput.addEventListener) {
buttonInput.addEventListener("click", testtest, false);
}
else if (buttonInput.attachEvent) {
buttonInput.attachEvent('onclick', testtest);
}
function testtest(e) {
var value = rangeInput.value;
if (value > 0 && value < 5) {
alert("First");
} else {
alert("Second");
}
}
Updating rangevalue
It also looks like you want to update the output element with the value of the range. What you're currently doing is referring to the element by id:
onchange="rangevalue.value=value"
However, as far as I know, this isn't standard behavior; you can't refer to elements by their id alone; you have to retrieve the element and then set the value via the DOM.
Might I suggest that you add a change listener via javascript:
rangeInput.addEventListener("change", function() {
document.getElementById("rangevalue").textContent = rangeInput.value;
}, false);
Of course, you'll have to update the code to use addEventListener or attachEvent depending on the browsers that you want to support; this is where JQuery really becomes helpful.
Use the mouseup event for that.
var rangeInput = document.getElementById("rangeinput");
rangeInput.addEventListener('mouseup', function() {
if (this.value > 0 && this.value < 5) {
alert("First");
} else{
alert("Second");
}
});
DEMO: http://jsfiddle.net/ZnYjY/1
You can also use the FORMs oninput method:
<form oninput="result.value=parseInt(a.value)+parseInt(b.value)">
<input type="range" name="b" value="50" />100 +
<input type="number" name="a" value="10" /> =
<output name="result"></output>
</form>
This has an advantage over onclick/onmouseup because it handles the case where the slider is moved using the keyboard (tab to the input and use the arrow keys)
Use the oninput event.
HTML Codes:
<div id="slider">
<input class="bar" type="range" id="range-input" min="1" max="25" value="1"/>
<span class="highlight"></span>
<output id="range-value">1</output>
</div>
<button id="btn" type="submit">Submit</button>
Javascript scripts
(function() {
var rangeInput = document.getElementById("range-input")
var rangeValue = document.getElementById("range-value")
var button = document.getElementById("btn")
// Show alert message when button clicked
button.onclick = testTest
function testTest() {
let value = rangeInput.value
if(value > 0 && value < 5) {
alert("first")
return true
}
alert("second")
return false
}
// Print the range value to the output
rangeInput.oninput = rangeOutput
function rangeOutput() {
rangeValue.innerText = rangeInput.value
}
})()
Demo
UPDATE 2021
Another option is to use the input event handler i.e. eventTarget.addEventListener("input", alert("Hello World"), though this event handler is the same with oninput, the difference having we can use addEventListener
<script type="text/javascript">
function range()
{
//the simplest way i found
var p = document.getElementById('weight');
var res = document.getElementById('rangeval');
res.innerHTML=p.value+ " Lbs";
}
</script>
<label for="weight">Your weight in lbs:</label>
<input name="weight" type="range" id="weight" max="500" min="0" value="75" onChange="range()" onKeyUp="range()">
<span id="rangeval"></span>

Categories