Set input value with Javascript on outside click - javascript

i want to set a max value to a number input. I used the "max" HTML attribute but the user can write a number over the max value anyway. Is there any way to reset the value of that input to the maximum value I set it, after the user sets it beyond the maximum value? Maybe when the user clicks outside that input?
Here is my code
<input type="number" name="days" id="days" min="1" max="365" value="<?php echo $ipq[0]['valueParam']?>">

You might want to consider using a range control along with the value of the range being shown in a span element next to it. This way only the value range you specify is allowed (which is really what the range control is for).
const output = document.getElementById("output");
document.getElementById("days").addEventListener("input", function(){
output.textContent = this.value;
});
<input type="range" name="days" id="days" min="1" max="365" value="1"><span id="output">1</span>

The max attribute is validated on form submit. AS you can see in the snippet below the user will get a message when he tries to submit the form.
<form>
<input type="number" name="days" id="days" min="1" max="365" value="366">
<input type='submit'>
</form>
If you want to prevent the user for inputting a value over 365 you can use js to do that. The snippet below shows how to prevent values over 365 for all number inputs.
document.querySelectorAll('input[type="number"]').forEach((el) => el.addEventListener('input', (e) => {
let inputEl = e.currentTarget;
if(parseFloat(inputEl.value) > parseFloat(inputEl.max)) {
inputEl.value = inputEl.max;
}
}));
<form>
<input type="number" name="days" id="days" min="1" max="365" value="366">
<input type='submit'>
</form>

Related

html output tag doesn't display output

I have initial values displaying in the fields and want the initial total of the calculated value to display.
The total only displays once a field is modified. I am guessing because it reacts to oninput event.
Code:
<form id="form" oninput="result.value = parseInt(field1.value) + parseInt(field2.value)">
<input type="number" name="field1" id="field1" value="600">
<input type="number" name="field2" id="field2" value="200">
Total <output name="result" id="result" value="document.write(this.result.value)">
</output>
</form>
I could type 800 inside the output tag, but I want it to be dynamic.
Your document.write isn't doing anything useful (it's basically saying "set this attribute to the value of this attribute") and can be removed; rather than writing the value into the HTML you can just set the form field's value attribute in js.
Here I've simplified your code by removing the nonessential or nonfunctional parts, moving the javascript out of the HTML attributes, and combining the "initialize" and "update" tasks into a single function:
// these happen implicitly based on the field IDs; I'm redeclaring
// them here just for clarity, but you could leave these next four
// lines out and this code would still work:
var result = document.getElementById('result')
var field1 = document.getElementById('field1');
var field2 = document.getElementById('field2');
var form = document.getElementById('form');
// update value on input:
form.oninput = function() {
// use Number() instead of parseInt() if you want to support non-integer values here
result.value = parseInt(field1.value) + parseInt(field2.value);
}
// set initial value on page load by calling that function:
form.oninput()
<form id="form">
<input type="number" id="field1" value="600">
<input type="number" id="field2" value="200">
Total <output id="result"></output>
</form>
You can use document.getElementById() and specify the id of the input fields.
Because the value for the input fields is a string, you need to convert to those values to type Number by the Number() function.
let value1 = Number(document.getElementById('field1').value);
let value2 = Number(document.getElementById('field2').value);
result.value = value1 + value2;
<form id="form" oninput="result.value=parseInt(field1.value)+parseInt(field2.value)">
<input type="number" name="field1" id="field1" value="600">
<input type="number" name="field2" id="field2" value="200">
Total <output name="result" id="result" value="document.write(this.result.value)"></output>
</form>
You can read more info about document.getElementById() and Number()

Finding the value of multiple input boxes

I'm building a multiple quantity selector for my store. Image below:
On the site, the price of the product updates based on the quantity added. 10 products = 10% off etc. I'd like to be able to display this price change as and when the user edits any one of the input boxes in the quantity selector.
The input fields are built like this:
<div data-value="S" data-varientid="8195426353207" class="swatch-element swatch-element-2 size s available">
<input id="swatch-0-s" data-variant-id="variant_8195426353207" type="checkbox" name="option-0" value="S">
<label for="swatch-0-s">
S
<img class="crossed-out" src="//cdn.shopify.com/s/files/1/0020/2188/3959/t/2/assets/soldout.png?5180939831627851747" alt="">
</label>
<input id="qty" name="quantity" class="swatchinput" placeholder="0" value="0" type="text">
</div>
I'm able to watch the input boxes for change by doing the below:
var qty = $('.swatchinput');
$('.swatchinput').on('paste keyup', function() {
console.log(qty);
});
However, this returns the information about the element rather than the contents. I'm also unsure of the best way to then add the contents of the various input fields together to reach the total quantity.
You could also use the Array reduce method to do this. Select all the inputs, get the array, then reduce their values into the sum.
var total = $('.swatchinput').get().reduce(function(total, input){
return total + parseInt(input.value || '0');
}, 0);
console.log(total);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="quantity" class="swatchinput" placeholder="0" value="1" type="text">
<input name="quantity" class="swatchinput" placeholder="0" value="2" type="text">
<input name="quantity" class="swatchinput" placeholder="0" value="3" type="text">
<input name="quantity" class="swatchinput" placeholder="0" value="4" type="text">
This needs to be
var qty = $('.swatchinput').val();
not
var qty = $('.swatchinput');
As for your second question,
loop each of these inputs, getting the value, then add them up with a total. Initialize the total OUTSIDE of the loop also so it doesn't overwrite it.
Something like this?
var total = 0;
$('.switchinput').each(function(){
total += $(this).val();
});
console.log(total);
To get the value of an element in jQuery, use .val():
http://api.jquery.com/val/
.each loops through each matched element and runs a function on that element (accessible through 'this')
http://api.jquery.com/each/

Add placeholder instead of value in number and range input when value is 0 - Angular.js

I have a number and range input that are working in unison using same value using Angular.js value. When the value is set to 0 (which is what it is by default when page loads $scope.lbs_needed = 0;, I want to show a placeholder="0" whenever the value of the number or range input is set to 0 that way the 0 value isn't in front of the user's input without them having to manually delete default 0.
Here's my html:
<form>
<div class="form-group">
<label for="number">Pounds of nitrogen desired per acre:</label>
<input type="number" class="form-control number-input" id="number" ng-model="lbs_needed" ng-change="calculate2()" value="{[{lbs_needed}]}" min="0" max="500" value="{[{lbs_needed}]}" placeholder="0">
<input type="range" min="0" max="500" class="form-control" id="number" ng-model="lbs_needed" ng-change="calculate2()" value="{[{lbs_needed}]}" placeholder="0">
</div>
</form>
So, if I understand correctly you want the textbox to have a default value but also want it to be changeable instantly without users having to backspace over the default?
Try this:
var input = document.getElementById('change-default');
input.onfocus = function () {
if (input.value == 0) {
input.value = '';
}
}
input.onblur = function () {
if (input.value == '') {
input.value = '0';
}
}
<input type="number" placeholder="0" value="0" id="change-default">
What I'm doing is listening for an focus event, you could also use addEventListener instead of onfocus.
If the value of the input box is 0 you remove its value ready for the user to type theirs in.

Setting the max value of an input field to the value of a label

I have an input field (type = number) and a label. I am trying to set the max attribute of the input field to the value of the label.
I have tried in different ways to no avail:
1)
<input id="Input1" type="number" step="any" min="1" max='<%#Convert.ToDecimal(Label1.InnerText) %>'>
2)
function setMaxTonnes() {
var input = document.getElementById("<%= Input1.ClientID %>");
var maxValue = document.getElementById("<%= Label1.ClientID %>").innerText;
input.setAttribute("max", maxValue);
}
<input type="number" step="any" min="1" onfocus="setMaxTonnes()">
There are no errors which return with either of these efforts but it doesn't prevent me from entering a value greater than the value stored in Label1.
Any ideas where I am going wrong?
Are you sure the asp variable is corrected output in the compiled markup? Try to inspect with DevTools if the input element actually gets your max value.
Your example looks accurate, <input type="number" step="any" min="1" max="12"> does work fine.

How to change the max value for input type number on HTML5 with Javascript?

I need change the max attribute of an input element with JavaScript. For example:
<input type="number" name="miname" min="0" max="MyVar" value="0"/>
You can assign an id to your input :
<input id="myInput" type="number" name="miname" min="0" max="MyVar" value="0"/>
then access it via javascript:
var input = document.getElementById("myInput");
input.setAttribute("max",100); // set a new value;
Note you can also access it directly if your input is in a form
document.formName.miname.setAttribute("max",newValue);
sharing the angular way of doing it. Use [attr.max].
<input matInput type="number" min="0" [attr.max]="totalOrders" placeholder="Total Skybridge Orders" formControlName="totalSkybridge" (change)="onTotalSkybridgeOrders($event)"

Categories

Resources