javascript distribution of inputs - javascript

I am trying to do 2 things:
Balance out 3 inputs into 100
$input1 = $('#input1 ');
$input2 = $('#input2 ');
$input3 = $('#input3 ');
$input1.on('input', function () {
$input2 .val(100 - this.value);
$input3 .val(100 - this.value - $input2.value)
});
$input2 is displayed well yet doesn't output into $input3 (NaN).
I also tried to create a callback for input3 and that didn't work out well either.
How to block the input from showing numbers out of the range of 0-100.
Here's a JSF

Try to get rid of jQuery because you are confusing both the DOM API and jQuery API. The DOM is what you should learn, not jQuery.
let $input1 = document.querySelector('#input1');
let $input2 = document.querySelector('#input2');
let $input3 = document.querySelector('#input3');
$input1.addEventListener('input', function () {
$input2.value = (100 - this.value)/2;
$input3.value = 100 - this.value - $input2.value;
});
<form>
<input id='input1'/><br/>
<input id='input2'/><br/>
<input id='input3'/>
</form>

$input2 is a jQuery wrapped element. You cannot call value on it directly. You need to get the value using val() instead. Since value will return undefined, the final output is NaN.
Change this:
$input3.val(100 - this.value - $input2.value)
to this:
$input3.val(100 - this.value - $input2.val())
Alternatively, you can get the native element out of the jQuery wrapper and call value on it. The following should work seamlessly as well:
$input3.val(100 - this.value - $input2[0].value)
For #2, you may want to look into input[type=number] and restrict the range using min and max attributes.

As in other answer by #31piy you need to use $input2.val() or $input2[0].value. And balancing of values in field input2 and input3 can be done as below.
$input1 = $('#input1 ');
$input2 = $('#input2 ');
$input3 = $('#input3 ');
$input1.on('input', function() {
$input2.val(parseInt((100 - this.value) / 2));
$input3.val(100 - this.value - $input2.val())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input id="input1" type=number min="0" max="100">
<input id="input2" type=number min="0" max="100">
<input id="input3" type=number min="0" max="100">

Related

Basic math functions in JavaScript to show on HTML page

I would like to make major of basic math functions (addition, subtraction, ect.) to develop in JavaScript. Input parameters should be from HTML webpage, than do the in JavaScript and return result on the same HTML page.
function math() {
//document.getElementById("frm1").innerHTML;
var numb = document.getElementById("number").innerHTML;
var mod = document.getElementById("modifier").innerHTML;
console.log(numb);
console.log(mod);
var sum = 1; //numb + mod; //the 1 is a placeholder
console.log(sum);
sum = document.getElementById("sum").innerHTML;
}
<form id="frm1" action="randScript.js">
Number: <input type="int" name="number" id="number"><br> Modifiers: <input type="int" name="modifier" id="modifier"><br>
<input type="button" onclick="math()" value="Submit">
</form>
<p id="sum"></p>
Your form tag has an action attribute. This means the page will submit your information to the specified page. You can use jQuery to prevent the form from submitting.
$("#yourFormId").on("submit",function(event){event.preventDefault()})
You can also edit the forms action attribute itself to prevent it from submitting.
<form id="frm1" action"javascript:void(0);">
First: The type is text - there is no "int" thing
Number: <input type="text" name="number" id="number">
Second: if we read a bit documentation we figure also out how to get the alue into the JS part
var numb = document.getElementById("number").value;
here you can now do your further homework ;)
Third: Get things back:
either use another input. They work two ways.
document.getElementById("result").value="I did not do my homework alone"
or you place a div somewhere with an id
<div id="result"> </div>
and now you can really use innerHTML in js
document.getElementById("result").innerHTML="I am too lazy";
The rest and to put it all together is now up to you :) Have fun to study :)
Try that if you want to display the sum at the html element:
document.getElementById("sum").innerHTML = sum;
But a more precise Question would help!
There is no int type for form inputs in HTML you can learn here about input types: HTML form input types
<form id="frm1" >
Number1: <input type="number" name="number" id="number1"><br>
Number2: <input type="number" name="number" id="number2"><br>
Modifiers: <input type="text" name="modifier" id="modifier"><br>
<input type="button" onclick="math()" value="Submit">
</form>
<p id = "sum"></p>
<script type="text/javascript">
function math() {
var numb1 = parseInt(document.getElementById("number1").value);
var numb2 = parseInt(document.getElementById("number2").value);
var mod = document.getElementById("modifier").value;
if(mod == '+'){
var sum = numb1 + numb2;
}else if(mod == '-'){
var sum = numb1 - numb2;
}else if(mod == '*'){
var sum = numb1 * numb2;
}
if(sum === undefined){
alert('invalid inputs');
return false;
}else{
document.getElementById("sum").innerHTML = sum;
}
return true;
}
To retrieve inputs values properly use value rather then innerHtml.
Retrieved values are strings so you need to parse them to numbers (with parseInt) before using them in math.
function math() {
const numb = document.getElementById("number").value;
const mod = document.getElementById("modifier").value;
sum = document.getElementById("sum").innerText = parseInt(numb) + parseInt(mod);
}

Change html slider step exponentially

I am trying to change the slider step by the power of 10 on each slide but it's not working correctly. I am unsure if I should use stepUp() or change the value of value of step directly.
This is how I increment by the power of 10:
var increment = (function(n) {
return function() {
n = n + 2;
var x = Math.pow(10, n);
console.log(x +" " + "Math.Pow thingy");
return x;
}
Here is how I try to pass it as an argument:
document.getElementById("something").stepUp(increment);
In case anyone is wondering, here is the stepUp() that I am using.
Also, here is a fiddle of my slider: Slider Fiddle #1
I want my slider to step to change to 10,100,1000,10000 on each slide.
Pretty sure you can't really do it your way, you'll need to do some kind of calculation yourself. Step only works for constant numbers
var input = document.getElementById("input")
var output = document.getElementById("output")
function getValue() {
let power = input.value
let result = Math.pow(10, +power)
output.value = result
}
<input id="input" type="range" min="1" max="10" value="1" oninput="getValue()" />
<input type="text" id="output" value="10"/>
The natural behaviour of <input type="range" /> is linear, so you have to engineer the required mapping of natural values to required values.
What you are looking for is slider with a socalled log-linear action such that the slider is set up to yield the logarithm of the values you ultimately want;
<input id="something" name="something" type="range" min="2" max="5" value="3" step="1" class="form-control slider" />
Here, the critical settings are
min="2" - log-base10(100) == 2
max="5" - log-base10(100000) == 5
value="3" - log-base10(1000) == 3
Then to get back to the values you actually want, you have to do an anti-logarithm, or Math.pow(10, x).
var slider = document.getElementById('something');
var output = document.getElementById('demo');
slider.onchange = function() {
output.innerHTML = Math.pow(10, this.value);
}
slider.onchange(); // set output for the initial value
DEMO
EDIT:
The behaviour of an <input type="range" /> slider element is inescapably linear. At its current state of development, HTML offers nothing else.
In order to submit the value you actually want, you can use your slider field as the UI for an underlying hidden field, the value of which is maintained to hold a transform of the linear element's value. Providing you can write code to perform the transformation, you are in business. In this case, it's simple - antilogarithm.
So your HTML might be something like this :
<input id="something-ui" type="range" min="2" max="5" value="3" step="1" class="form-control slider" />
<input id="something-hidden" name="something" type="hidden" />
And the corresponding javascript :
var slider = document.getElementById('something-ui');
var hidden = document.getElementById('something-hidden');
var output = document.getElementById('demo');
slider.oninput = function() { // or onChange
output.innerHTML = hidden.value = Math.pow(10, this.value); // antilogarithm
}
slider.oninput(); // set hidden value and output for the initial value
So now, the UI control still behaves linearly but is given (by demo) the appearance, and a submit behaviour (by something-hidden), of being exponential.
This is one way to do this
// Get DOM refs for the required elements
var slider = document.getElementById('myRange');
var res = document.getElementById('res');
var inc = document.getElementById('inc');
// Initialize Div to show starting value
res.innerHTML = slider.value;
// Register on change handler to update div value if slider is changed
slider.onchange = function(){
res.innerHTML = this.value;
}
// Register a click handler inside a closure to increment exponentially
inc.onclick = (function(){
// Initial increment value
var n = 1;
// Return a click handler function which has access to the variable n because of the closure
return function(){
// Button is clicked, increment by n
slider.stepUp(n);
// Update div value for display
res.innerHTML = slider.value;
// Multilply n by 10 so the next time the increment is 10x
n *= 10;
}
})()
<input type="range" id="myRange" value="1000" min="1" max="1000">
<div id="res"></div>
<button id="inc">Increment</button>

Javascript - prevent onclick event from being attached to all elements with same class

I'm working on a simple form that includes an input field where the user will fill in the required amount by clicking the incrementor/decrementor. The form is created based on data pulled dynamically from the database
Below is the problematic part: html and the jquery handling it:
The incrementor, decrementor and the input field:
-
<input type="text" id="purchase_quantity" class = "purchase_quantity" min="1" max="6" delta="0" style = "width: 32px;" value="1">
+
and the jquery handling the above:
jQuery(function ($) {
$('.addItem').on('click', function () {
var inputval = $(this).siblings('.purchase_quantity').val();
var num = +inputval;
num++;
if(num>6)num=6;
console.log(num);
$(".purchase_quantity").val(num);
return false;
});
$('.removeItem').on('click', function () {
var inputval = $(this).siblings('.purchase_quantity').val();
var num = +inputval;
num--;
if(num<1)num=1;
console.log(num);
$(".purchase_quantity").val(num);
return false;
});
});
Now, what's happening is: onclick of the incrementor/decrementor (+ and -) the value on the input field changes across all the fields in the page instead of the one clicked only. Have spent quite some time on this with no success and will appreciate some help
The line
$(".purchase_quantity").val(num);
says, literally, to change the value on all the fields. Earlier you used
$(this).siblings('.purchase_quantity').val()
to get the value, so why not also use
$(this).siblings('.purchase_quantity').val(num)
to set it?
That's because siblings will get you all items on the same level.
Get the siblings of each element in the set of matched elements,
optionally filtered by a selector.
Place them in separate div elements, and adjust your setter to actually only update the siblings inside that div.
jQuery(function ($) {
$('.addItem').on('click', function () {
var inputval = $(this).siblings('.purchase_quantity').val();
var num = +inputval;
num++;
if(num>6)num=6;
console.log(num);
$(this).siblings('.purchase_quantity').val(num);
return false;
});
$('.removeItem').on('click', function () {
var inputval = $(this).siblings('.purchase_quantity').val();
var num = +inputval;
num--;
if(num<1)num=1;
console.log(num);
$(this).siblings('.purchase_quantity').val(num);
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
-
<input type="text" id="purchase_quantity2" class = "purchase_quantity" min="1" max="6" delta="0" style = "width: 32px;" value="1">
+
</div>
<div>
-
<input type="text" id="purchase_quantity1" class = "purchase_quantity" min="1" max="6" delta="0" style = "width: 32px;" value="1">
+
</div>
you should change $(".purchase_quantity").val(num) to $("#purchase_quantity").val(num)

jquery, attribute selector, get current attribute value

I have an input:
<input type="text" size="5" maxlength="5" decimals="2">
where "decimals" could be a value from 0 to 4.
In the onblur event, whatever number the user types in will be changed to conform, thus:
decimals="2"
User enters: 123.456
Input is changed to: 123.46
That's trivial, no problem. My question is about the most efficient way to get the value of "decimals." Ordinarily, I'd write (jquery):
$('[decimals]').blur(function(){
val = $(this).attr('decimals');
// *** do stuff with val ***
});
...but it seems to me there ought to be a more efficient way to get the value of "decimals" since we've already selected the input based on that attribute. Is there, or is my code as written the only way?
You may take a look to attributes. This is a NamedNodeMap with some functions.
If you are referring to attributes and not to custom data attributes you can do:
$(function () {
$('[decimals]').blur(function(){
var val = this.attributes.decimals.value;
var val1 = this.attributes.getNamedItem('decimals').value;
var val2 = this.getAttribute('decimals');
console.log('this.attributes.decimals.value = ' + val);
console.log('this.attributes.getNamedItem("decimals").value = ' + val1);
console.log('this.getAttribute("decimals") = ' + val);
// *** do stuff with val ***
}).trigger('blur');
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<form>
<input type="text" size="5" maxlength="5" decimals="2">
</form>
Instead if you are referring to custom data attributes:
decimals="2"
User enters: 123.456
Input is changed to: 123.46
You can do:
$(function () {
$('[data-decimals]').on('blur', function(e){
var val = +$(this).data('decimals');
var txtNumber = +this.value;
this.value = txtNumber.toFixed(2);
});
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<form>
<input type="number" size="5" maxlength="5" data-decimals="2">
</form>

Get value of an input type Range

I have this code:
<p class="slider1">Your approximate total debt:
<output name="slider_output1" id="slider_output1" for="form_slider1">0</output><br>
<input type="range" class="form_slider1" name="form_slider1" id="form_slider1"
value="0" min="0" max="60000" step="100"
oninput="slider_output1.value=form_slider1.value"
onchange="slider_output1.value=value"/>
</p>
I need to get the range/slider value for condition statement.
I tried using jQuery:
var slider1 = $("form_slider1").val();
but I got "undefined" when I alert the value.
alert(slider1);
Thank you guys in advance!
try this
var slider1 = $(".form_slider1").val();
javascript
Replace the object with your element object and the eventCallback with your event(onclick for example)
object.eventCallback=function(){
var r = document.getElementById('form_slider1').value;
alert(r);
};
jquery
var slider1 = $(".form_slider1").val();
This is regarding your comment
<input type="range" id="r" min="1" max="20">
<input type="submit" id="sub">
<script>
var r1=document.getElementById("sub");
r1.onclick=function(){
var r = document.getElementById('r').value;
if(r>10){
alert("You crossed the half of it");
}
else alert("Value less than 10");
};
</script>
You can give your own conditions if you want (eq r==20 alert("the peak"));
You should try this:
var slider1 = $("#form_slider1").val();
From your code we can find that the class name and id of input component is same: form_slider1.
So, if you want use id to get this element's value, you should use this
var slider1 = $("#form_slider1").val();.
if you want to use class to get this element's value, you should use this
var slider1 = $(".form_slider1").val();

Categories

Resources