Get Javascript maxLength in input - javascript

I have a problem with downloading and displaying the value, when set to "rigidly" maxLenght - everything works fine, but when I want the script to download the value myself, I have a problem.
The script is supposed to get the value maxlenght = "" from each <input> and after typing by the user it will print out how many characters are left.
var maxLen = document.getElementsByClassName("handlerWorld").maxLength;
function countChar(jqObj) {
var len = jqObj.val().length;
var diff = maxLen - len;
if (len > maxLen) {
len = maxLen;
diff = 0;
}
jqObj.val(jqObj.val().substr(0, len)).prev('label').find('span.chars-twenty').text(diff);
}
$(document).ready(function () {
$("[class*='handlerWorld']").keyup(function () {
countChar($(this));
}).each(function () {
countChar($(this));
});
});
My HTML:
<div class="form-group">
<label for="nameIput">Nazwa firmy <span>Remaining: <span class="chars-twenty"></span></label>
<input type="text" id="name" maxlength="140" name="name" class="form-control handlerWorld">
</div>
<div class="form-group">
<label for="urlInput">URL <span>Remaining: <span class="chars-twenty"></span></label>
<input type="text" id="url" name="url" maxlength="100" class="form-control handlerWorld">
</div>
Edit:
Now I would like it to show the number of characters, e.g .:
10/140
quantity written / quantity in the value "maxlenght"
$("#add-category").find('span.maxchar').text(maxLen);
They work but not as they should.

Move the MaxLength calculation to the Count method
var maxLen = jqObj.attr("maxlength");
here's fiddle for you:
https://jsfiddle.net/d53yjpr8/1/
function countChar(jqObj) {
var maxLen = jqObj.attr("maxlength");
var len = jqObj.val().length;
var diff = maxLen - len;
if (len > maxLen) {
len = maxLen;
diff = 0;
}
jqObj.val(jqObj.val().substr(0, len)).prev('label').find('span.chars-twenty').text(diff);
}
$(document).ready(function() {
$("[class*='handlerWorld']").keyup(function() {
countChar($(this));
}).each(function() {
countChar($(this));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label for="nameIput">Test <span>Remaining:</span> <span class="chars-twenty"></span></label>
<input type="text" id="name" maxlength="140" name="name" class="form-control handlerWorld">
</div>
<div class="form-group">
<label for="urlInput">URL <span>Remaining:</span> <span class="chars-twenty"></span></label>
<input type="text" id="url" name="url" maxlength="100" class="form-control handlerWorld">
</div>

Related

Storing variable from calculated inputs - javascript

Welcome ! I have a question. Is the any possibility to store calculated data from three inputs for further math calculations? My clue is to store this dowform.value after calculations in new variable so i could for example divide this calculated value or multiply it and get new value. Code below for better understanding:
Javascript:
function dryOperatingWeight() {
const bew = document.getElementById("bew").value;
const crew = document.getElementById("crew").value;
const pantryDiv = document.getElementById("pantry").value;
let arr = document.getElementsByName("dow");
let tot = 0;
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].value)) tot += parseInt(arr[i].value);
}
dowform.value = tot;
}
HTML:
<div class="form-group">
<label for="bew">Basic Empty Weight</label>
<input class="form-control" name="dow" type="text" id="bew" value="" onkeyup = "dryOperatingWeight()"/>
</div>
<div class="form-group">
<label id="crew"> Crew Weight</label>
<input
type="number"
name="dow"
class="form-control"
id="crew"
value=""
placeholder="crew weight"
onkeyup = "dryOperatingWeight()"
/>
<div class="form-group">
<label id="pantry">Pantry Weight</label>
<input
type="number"
name="dow"
class="form-control"
id="pantry"
placeholder="Enter pantry code"
onkeyup = "dryOperatingWeight()"
/>
</div>
<div class="form-group">
<label id="pantry">Water Weight</label>
<input
type="number"
name="dow"
class="form-control"
id="water"
placeholder="Enter water weight"
onkeyup = "dryOperatingWeight()"
/>
</div>
<div id="dow">
<div class="form-group">
<label for="dryoperating weight">Dry Operating Weight</label>
<input class="form-control" type="number" id="dowform" readonly/>
</div>
</div>
You can declare your variable outside of the function and just reuse it and modify it as needed.
let dow;
function dryOperatingWeight() {
const bew = document.getElementById("bew").value;
const crew = document.getElementById("crew").value;
const pantryDiv = document.getElementById("pantry").value;
let arr = document.getElementsByName("dow");
dow = 0;
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].value)) dow += parseInt(arr[i].value);
}
dowform.value = dow;
}

How should I put limit inside for loop using if condition using javascript

My goal is that only 15 quantities of input elements can be accepted, once the user enters 16 it should say that only 15 input elements is allowed. However I don't know how will I do this. I tried putting condition inside for but it is not not working. I am a little bit confused on this
Here is my HTML code
<div class="form-group">
<label> Quantity: </label>
<input class="form-control" name="quantity" type="number" id="get_Elem"
required>
<br>
<input type="button" id="sb_add_ctrl" name="is_Sub" class="btn btn-
primary" value="Add Control Number">
</div>
<div class="form-group" name="parent" id="parent"></div>
Here is my JS code
$(document).on('click', '#sb_add_ctrl', function() {
var element = $('#get_Elem').val();
var input;
var parent = $(document.getElementById("parent"));
var value = $('#sel_control_num').val();
functionPopulate(parent);
if (isNaN(element)) {
return;
}
for (var i = 0; i < element; i++) {
if(should I do it here??){
}
value = value.replace(/(\d+)$/, function(match, element) {
const nextValue = ++match;
return ('0' + nextValue).slice(1);
});
document.getElementById("parent").style.padding = "5px 0px 0px 0px";
document.getElementById("parent").innerHTML += '<br><input type="text"
value="' + value +
'" class="form-control" name="get_Input_show[]" required>'
}
});
You can check if the element value is < 16 if yes then only add html else show error message.
Demo Code :
$(document).on('click', '#sb_add_ctrl', function() {
var element = $('#get_Elem').val();
var input;
//var value = $('#sel_control_num').val();
var value = 12;
//functionPopulate(parent);
if (isNaN(element)) {
return;
}
//check if elemnt value if < 16
if (element < 16) {
$("#parent").empty() //empty div
for (var i = 0; i < element; i++) {
/* value = value.replace(/(\d+)$/, function(match, element) {
const nextValue = ++match;
return ('0' + nextValue).slice(1);
});*/
document.getElementById("parent").style.padding = "5px 0px 0px 0px";
document.getElementById("parent").innerHTML += '<br><input type="text" value = "' + value + '" class="form-control" name="get_Input_show[]" required>';
}
} else {
alert("only 15") //show error
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label> Quantity: </label>
<input class="form-control" name="quantity" type="number" id="get_Elem" required>
<br>
<input type="button" id="sb_add_ctrl" name="is_Sub" class="btn btn-
primary" value="Add Control Number">
</div>
<div class="form-group" name="parent" id="parent"></div>
There are two ways in which you can restrict it
You can use maxLength property of an input tag, which will restrict the user to input the 16th character.
You can keep checking the value in the input field and show error if the length is more than 15 character. To do this you can use onkeypress event on input, like
HTML
<input type="text" id="test" onkeypress="test()" />
JS:
<script>
function test() {
alert('Hi')
}
</script>

Calculating multiple inputs value with javascript

i'm having trouble going trough making a calculator (sum only) of 5 inputs fields in html/javascript and i can't manage to find what's wrong in my code
i tried messing around with types such as int instead of var and passing the value into parseInt, i somehow managed to have a result like "11111" where it should be like "5" but alongside that case the result is never printed in the innerHTML even after i added the "if not null" condition
Here is my html
<body>
<h1 class="head-title"></h1>
<div class="input-group">
<label for="design">Design :</label>
<input class="input-text" type="number" id="design">
</div>
<div class="input-group">
<label for="plot">Plot :</label>
<input class="input-text" type="number" id="plot">
</div>
<div class="input-group">
<label for="character">Character :</label>
<input class="input-text" type="number" id="character">
</div>
<div class="input-group">
<label for="enjoyment">Enjoyment :</label>
<input class="input-text" type="number" id="enjoyment">
</div>
<div class="input-group">
<label for="music">Music :</label>
<input class="input-text" type="number" id="music">
</div>
<div class="button-group">
<button class="button-primary" onclick="ratingCompute();">Calculate</button>
</div>
<div class="input-group">
<label for="total">Rating :</label>
<p class="rating-score" id="total"></p>
</div>
</body>
and here is my javascript
function ratingCompute()
{
var designValue = document.getElementById("design").value;
var plotValue = document.getElementById("plot").value;
var charValue = document.getElementById("character").value;
var enjoyValue = document.getElementById("enjoyment").value;
var musicValue = document.getElementById("music").value;
var totalValue = designValue + plotValue + charValue + enjoyValue + musicValue;
if (totalValue != null)
{
document.getElementById("total").innerHTML = totalValue + "/10";
}
else
{
document.getElementById("total").innerHTML = "0/10";
}
}
Any clue?
JavaScript is not a type variable language try using let or const. And here is how you properly parse it. If you did it already then its because of your variable declaration.
let designValue = parseInt(document.getElementById("design").value);
let plotValue = parseInt(document.getElementById("plot").value);
let charValue = parseInt(document.getElementById("character").value);
let enjoyValue = parseInt(document.getElementById("enjoyment").value);
let musicValue = parseInt(document.getElementById("music").value);
In javascript you should use keyword var/let/const instead of int. and you have to convert String type input value to int using parseInt method.
Please check this:
function ratingCompute()
{
var designValue = parseInt(document.getElementById("design").value);
var plotValue = parseInt(document.getElementById("plot").value);
var charValue = parseInt(document.getElementById("character").value);
var enjoyValue = parseInt(document.getElementById("enjoyment").value);
var musicValue = parseInt(document.getElementById("music").value);
var totalValue = designValue + plotValue + charValue + enjoyValue + musicValue;
if (totalValue)
{
document.getElementById("total").innerHTML = totalValue + "/10";
}
else
{
document.getElementById("total").innerHTML = "0/10";
}
}
<body>
<h1 class="head-title"></h1>
<div class="input-group">
<label for="design">Design :</label>
<input class="input-text" type="number" id="design">
</div>
<div class="input-group">
<label for="plot">Plot :</label>
<input class="input-text" type="number" id="plot">
</div>
<div class="input-group">
<label for="character">Character :</label>
<input class="input-text" type="number" id="character">
</div>
<div class="input-group">
<label for="enjoyment">Enjoyment :</label>
<input class="input-text" type="number" id="enjoyment">
</div>
<div class="input-group">
<label for="music">Music :</label>
<input class="input-text" type="number" id="music">
</div>
<div class="button-group">
<button class="button-primary" onclick="ratingCompute()">Calculate</button>
</div>
<div class="input-group">
<label for="total">Rating :</label>
<p class="rating-score" id="total"></p>
</div>
</body>
As mentioned by #Joshua Aclan, JavaScript does not have an "int" variable declaration, only "var". Also you have to cast all of the inputs to int or float, because otherwise you are adding strings and the values of input fields are always strings. Also the output is most likely empty because int designValue... produces an error.
function ratingCompute()
{
var designValue = parseInt(document.getElementById("design").value);
var plotValue = parseInt(document.getElementById("plot").value);
var charValue = parseInt(document.getElementById("character").value);
var enjoyValue = parseInt(document.getElementById("enjoyment").value);
var musicValue = parseInt(document.getElementById("music").value);
var totalValue = designValue + plotValue + charValue + enjoyValue + musicValue;
if (totalValue != null)
{
document.getElementById("total").innerHTML = totalValue + "/10";
}
else
{
document.getElementById("total").innerHTML = "0/10";
}
}

Output wont show (javascript)

I have 1 input. And it has to print out 2 outputs 1 with -1 to the output and the other with -2. But the output doesn't show anything. can someone tell me what I'm doing wrong here.
Code:
// Meters en Centimeters value
function updateTotal() {
const list = document.getElementsByClassName("AutosubmitCalculator");
const values = [];
for (let i = 0; i < list.length; ++i) {
values.push(parseFloat(list[i].value));
}
let total = values.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
});
document.getElementById("schermentotaal").value = total - 2;
document.getElementById("schermentotaal2").value = total - 1;
}
HTML Input:
<div class="InputField InputMeters">
<input type="tel" name="iFenceMeters" id="FenceMeters" class="AutosubmitCalculator" data-minimum-length="1" tabindex="1" placeholder="00" maxlength="3" value="">
<div class="FormExclamation Tipped Hidden" id="FormCalculatorExclamationFence">0</div>
</div>
HTML Output:
<div class="SummaryRow">
<strong>Schermen</strong>
<input name="schermentotaal" type="text" id="schermentotaal" value=""></input>
</div>
<div class="SummaryRow">
<strong>Palen en onderplaten</strong>
<input name="schermentotaal2" type="text" id="schermentotaal2" value=""></input>
</div>
Thanks in advance :D
You're not calling your updateTotal anywhere. I suggest you run this function on the oninput event on your input field. This will make it so that whenever you enter a number it will run the function updateTotal.
You also have some additional errors, such as you are trying to get the element with the id total but don't have an element with this id in your HTML.
document.getElementById("total").value
I've changed this to be schermentotaal2 which is a valid id in your HTML:
document.getElementById("schermentotaal2").value
See working example below:
function updateTotal() {
const list = document.getElementsByClassName("AutosubmitCalculator");
const values = [];
for (let i = 0; i < list.length; i++) {
values.push(parseFloat(list[i].value));
}
let total = values.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
});
document.getElementById("schermentotaal").value = (total - 2) || '';
document.getElementById("schermentotaal2").value = (total - 1) || '';
}
<div class="InputField InputMeters">
<input type="tel" name="iFenceMeters" id="FenceMeters" class="AutosubmitCalculator" data-minimum-length="1" tabindex="1" placeholder="00" maxlength="3" value="" oninput="updateTotal()" />
<div class="FormExclamation Tipped Hidden" id="FormCalculatorExclamationFence">0</div>
</div>
<div class="SummaryRow">
<strong>Schermen</strong>
<input name="schermentotaal" type="text" id="schermentotaal" value="" />
</div>
<div class="SummaryRow">
<strong>Palen en onderplaten</strong>
<input name="schermentotaal2" type="text" id="schermentotaal2" value="" />
</div>
Also, if you only have one input you may want to reconsider using a class to get the input value for this as you don't require a loop to get the value from one input field.

jQuery add ID increment to .html() appending on input onchange and refresh onchange value

I apologize for the wordy title but I haven't found a solution to my problem yet. I am a newbie with jQuery and web development so any guidance would be appreciated.
I have a <input> that allows user to enter a value (number) of how many rows of a set of input fields they want populated. Here's my example:
<div id="form">
<input id="num" name="num" type="text" />
</div>
<p> </p>
<div id="form2">
<form action="" method="post" class="form_main">
<div class="data">
<div class="item">
<input id="name" name="name[]" type="text" placeholder="name" /><br/>
<input id="age" name="age[]" type="text" placeholder="age" /><br/>
<input id="city" name="city[]" type="text" placeholder="city" /><br/>
<hr />
</div>
</div>
<button type="submit" name="submit">Submit</button>
</form>
My jQuery:
<script>
var itemNum = 1;
$("#num").on("change", function() {
var count = this.value;
var item = $(".item").parent().html();
//item.attr('id', 'item' + itemNum);
for(var i = 2; i <= count; i++) {
itemNum++;
$(".data").append(item);
}
})
</script>
I'm having problems adding an ID item+itemNum increment to <div class="item">... item.attr() didn't work. It doesn't append once I added that line of code.
Also, how can I get it so that once a user enters a number that populates rows of input fields, that if they change that number it will populate that exact number instead of adding to the already populated rows? Sorry if this doesn't make any sense. Please help!
Here is a DEMO
var itemNum = 1;
$("#num").on("change", function() {
$('.data div').slice(1).remove(); //code for removing previously populated elements.
var count = this.value;
console.log(count);
var item;
//item.attr('id', 'item' + itemNum);
var i;
for(i = 1; i <= count; i++) {
console.log(i);
item = $("#item0").clone().attr('id','item'+itemNum);
//prevent duplicated ID's
item.children('input[name="name[]"]').attr('id','name'+itemNum);
item.children('input[name="age[]"]').attr('id','age'+itemNum);
item.children('input[name="city[]"]').attr('id','city'+itemNum);
itemNum++;
$(".data").append(item);
}
})
Use clone() instead of html()
Try
var itemNum = 1,
item = $(".data .item").parent().html();;
$("#num").on("change", function () {
var count = +this.value;
if (itemNum < count) {
while (itemNum < count) {
itemNum++;
$(item).attr('id', 'item' + itemNum).appendTo('.data')
}
} else {
itemNum = count < 1 ? 1 : count;
$('.data .item').slice(itemNum).remove();
}
})
Demo: Fiddle

Categories