This seems embarrassing to ask even for a newbie like me, but I have a huge headache with displaying new value in the html input field after adding spaces between numbers in html input.
Basically, what I want to achieve is to add spaces between numbers in the input field after the user "unclicks" the input.
For example, 123456789123456789 would change to 12 3456 7891 2345 6789. I get the value of users input and add spaces where I want, but I just can't make it appear in the input field. My code looks like this:
'use strict';
$(document).ready(function (){var $inputTwo = $('#separateNumbers');
$inputTwo.change(function() {
var inputNumber = $inputTwo.val();
var separatedNumbers = [];
var part1 = inputNumber.substring(0, 2);
separatedNumbers.push(part1);
for (var i = 2; i < inputNumber.length; i += 4){
separatedNumbers.push(inputNumber.substring(i, i + 4))
}
var displayNumber = separatedNumbers.join(' ');
$inputTwo.val(displayNumber);
})
});
<body>
<div class="wrapper">
<div id="Task1_2">
<h1>Task 1.2</h1>
<label for="separateNumbers">Write more than 10 digits:</label><br/>
<input type="number" id="separateNumbers" placeholder=" i.e. 12345678901234567">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
I don't understand why this doesn't work. I tried to replace last code line with
document.getElementById('separateNumbers').value = displayNumber;
but then I got this in console:
The specified value "87 6178 1" is not a valid number.
The value must match to the following regular expression:
-?(\d+|\d+\.\d+|\.\d+)([eE][-+]?\d+)?.
This appears no matter what combination of numbers I put. Unfortunately I don't understand Regex yet, so I don't even know what would be a valid value...
a number does not have spaces in it. change your input to a type = text and it should work
change the type to text because adding space not work in the text format
$(document).ready(function() {
// Displaying new input value (adding spaces) -- Solution
$("#separateNumbers").change(function() {
$inputTwo = $('#separateNumbers');
var inputNumber = $inputTwo.val();
var separatedNumbers = [];
var part1 = inputNumber.substring(0, 2);
separatedNumbers.push(part1);
for (var i = 2; i < inputNumber.length; i += 4) {
separatedNumbers.push(inputNumber.substring(i, i + 4))
}
var displayNumber = separatedNumbers.join(' ');
$inputTwo.val(displayNumber);
});
});
<body>
<div class="wrapper">
<div id="Task1_2">
<h1>Task 1.2</h1>
<label for="separateNumbers">Write more than 10 digits:</label><br/>
<input type="text" id="separateNumbers" placeholder=" i.e. 12345678901234567">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
Related
I’m trying to get the computer to take an input from the HTML and add and multiply some number to it in Javascript. I’m from python and the variable system in Javascript makes no sense to me, so can someone please lmk what to do?
<div class = "text">How much energy do you use?</div>
<input id = "q1" type = "text" placeholder = "# of KilaWatts"></input>
<button type="button" onclick="getInputValue();">Submit</button>
<!-- Multiply InputValue by 3 and Add 2 —->
I tried to do something with parseInt, and parseString, but it didn’t work as it would just not run.
try this, first query input value then calculate your desire numbers then alert the user,
like this <!-- Multiply InputValue by 3 and Add 2 —->
function getInputValue() {
const inputVal = document.getElementById("q1").value; //query input value
const calculatedValue = ((inputVal *3) +2); // first multiply input value with 3
// then add 2
alert(calculatedValue); // show the calculated value through an alert
};
It's not that hard. try to play with the below code. Cheers!!
<html>
<body>
<label for="insertValue">Enter Your Value:</label>
<input type="text" id="insertValue">
<button onclick="Multiply()">Multiply</button> <!-- Calling to the JS function on button click -->
<p id="answer"></p>
<!-- Always link or write your js Scripts before closing the <body> tag -->
<script>
function Multiply() {
let value = document.getElementById("insertValue").value; //get the inserted Value from <input> text box
let answer = 0;
//Your Multiplication
answer = value * 2 * 3;
//Display answer in the <p> tag and it id ="answer"
document.getElementById("answer").innerText = "Your Answer is: "+ answer;
}
</script>
</body>
</html>
Easy (to understand) Solution:
<div class="text">How much energy do you use?</div>
<input id="q1" type="text" placeholder="# of KilaWatts"></input>
<button type="button" onclick="getInputValue();">Submit</button>
<br>
<output id="a1"></output>
<script>
var input = document.getElementById("q1");
var output = document.getElementById("a1");
function getInputValue() {
output.textContent = (input.value * 3) + 2;
}
</script>
I'm trying to grab the end digit of the target div, replace and join two attributes (js-data-reveals) with that digit added at the end (_1).
I know it has something to do with the regular expression that I am using to replace the attributes but I can't figure it out.
Hope you can help.
$('#js-form-group-UPLOAD_DOCUMENT_ID_1').find('input').each(function() {
var attrName = 'js-data-reveals';
var $el = $(this);
//Get Last Digit from ID
var idNumber = $el.attr('id').match(/\d+$/);
var attrs = $el.attr(attrName);
//Split the two attributes in js-data-reveals
var data = attrs.split(',').map(function(item) {
return item.replace(/.{0}$/, function(idNumber) {
return idNumber
});
});
$el.attr(attrName, data.join(','));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="js-form-group-UPLOAD_DOCUMENT_ID_1">
<fieldset>
<input type="file" class="form-control" id="UPLOAD_DOCUMENT_ID_1"
js-data-driven="true"
js-data-reveals="DOCUMENT_TYPE,UPLOAD_DOCUMENT_DESCRIPTION">
</fieldset>
</div>
match() returns an array.
Can simplify this using attr(attrName, function)
$('input[js-data-reveals]').attr('js-data-reveals', function(_, existing) {
var idNumber = this.id.match(/\d+$/)[0];
return existing.split(',').map(function(s) {
// replace number if it already exists or add it if it doesn't
return s.match(/_\d+$/)
? s.replace(/\d+$/, idNumber)
: s += '_' + idNumber;
}).join();
});
console.log($('#UPLOAD_DOCUMENT_ID_1').attr('js-data-reveals'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="js-form-group-UPLOAD_DOCUMENT_ID_1">
<fieldset>
<input type="file"
class="form-control"
id="UPLOAD_DOCUMENT_ID_1"
js-data-driven="true"
js-data-reveals="DOCUMENT_TYPE,UPLOAD_DOCUMENT_DESCRIPTION_999">
</fieldset>
</div>
Remove the '+' in your Regular Expression to make it:
var idNumber = $el.attr('id').match(/\d$/);
The '+' makes a Regular Expression match the given character 1 or more times, so \d+$ would match 12345 in 'd12345'. Since you only want the last digit to match, removing the '+' will make it works as expected.
i hava an input type number
<input type="number" class="form-control" id ="nbchambre" name="nbchambre" onchange="myFunction()">
I have another input that i want to show multiple times based on the number that the user enter, now i wrote this javascript code:
function myFunction(){
var n = document.getElementById("nbchambre").value;
for(count = 1; count < n+1; count++){
var div = document.createElement('div');
div.innerHTML = 'test';
document.getElementById('content').appendChild(div);
}
}
but this code doesn't work, when ever i write a number the div will show the word 'test' 10 times the number (for example when i write 3 it will show the word test 30 times), also when i write 5 after i wrote 3 it will add 50 'test' to the first 30 'test'. I am not good at javascript so please help me fix this code. Thanks
You need to make sure you are converting your input value to a number. Otherwise it will be treated as a string.
<input type="number" class="form-control" id ="nbchambre" name="nbchambre" onchange="myFunction()">
<div id="content"></div>
<script>
function myFunction(){
var n = Number(document.getElementById("nbchambre").value);
var content = document.getElementById('content');
content.innerHTML="";
for(var count = 1; count < n+1; count++){
var div = document.createElement('div');
div.innerHTML = 'test';
content.appendChild(div);
}
}
</script>
I have a form that has 3 text areas, a copy button, and a reset button. I want to add all the characters to one sum, then display that sum next to the copy/reset button. There is a 500 character limit, and the counter should start at 49 characters. Should I just take all my textareas and "Funnel" them into a var, then count that var? I'm not sure how I should approach this. I've tried this technique
but it only works with one text area, not the sum of all. If the char count goes above 500, I'd like the text to turn red and say "you've gone over your character limit." I do not want to restrict or limit the text once its over 500. I'm a little fried trying to find a solution, and I'm an obvious html/javascript novice.
I do not need to worry about the carriage return issue in firefox/opera since everyone will be using IE11.
<h1>
Enter your notes into the text boxes below
</h1>
<p>
Please avoid using too many abbreviations so others can read your notes.
</p>
<form>
<script type="text/javascript"><!--
// input field descriptions
var desc = new Array();
desc['kcall'] = 'Reason for Call';
desc['pact'] = 'Actions Taken';
desc['mrec'] = 'Recommendations';
function CopyFields(){
var copytext = '';
for(var i = 0; i < arguments.length; i++){
copytext += desc[arguments[i]] + ': ' + document.getElementById (arguments[i]).value + '\n';
}
var tempstore = document.getElementById(arguments[0]).value;
document.getElementById(arguments[0]).value = copytext;
document.getElementById(arguments[0]).focus();
document.getElementById(arguments[0]).select();
document.execCommand('Copy');
document.getElementById(arguments[0]).value = tempstore;
document.getElementById("copytext").reset();
}
--></script>
<p> Reason For Call: </p> <textarea rows="5" cols="40" id="kcall"></textarea><br>
<p> Actions Taken: </p> <textarea rows="5" cols="40" id="pact"></textarea><br>
<p> Recommendations: </p> <textarea rows="5" cols="40" id="mrec"></textarea><br>
<br>
<button type="button" onclick="CopyFields('kcall', 'pact', 'mrec');">Copy Notes</button>
<input type="reset" value="Reset"/>
</form>
I think this question is a little more tricky that you think, and is not cause the complex of count the number of character inside of a textarea thats is actually pretty simple. in jquery:
$("textarea").each(function(index, item){
sum += $(this).val().length;
});
The problem begins whit the keyup event since and how you manage that event, in my follow example, I pretty much manage when the user press the key like in regular state but if you start holding a key then stoping and copy and paste really quick, the event get lost a little bit and recover after the second keyup. Any way here is my full example with count of character counter, change from red to black and black to red if you over pass the max characters and validation for submit or not the form
Fiddle:
https://jsfiddle.net/t535famp/
HTML
<textarea></textarea>
<textarea></textarea>
<textarea></textarea>
<button class="reset"></button>
You have use <span class="characters"></span> of <span class="max"></span>
<button class="submit">submit</button>
JS
$(function(){
var counter = 0; //you can initialize it with any number
var max = 400; //you can change this
var $characters = $(".characters");
var $max = $(".max");
var submit = true;
$characters.html(counter);
$(".max").html(max);
function count(event){
var characters = $(event.target).val().length;
$characters.html(counter);
//sum the textareas
var sum = 0;
$("textarea").each(function(index, item){
sum += $(this).val().length;
});
counter = sum;
if(counter > max) {
$characters.css({ color : "red" });
submit = false;
}else{
$characters.css({ color : "black" });
submit = true;
}
}
$(document).on("keyup","textarea",count);
$(document).on("click",".submit",function(){
if(submit)
alert("done");
else
alert("you have more characters than " + max);
});
})
Good luck my 2 cents
function textareaLength() {
var charCount = 0;
Array.prototype.forEach.call(document.querySelectorAll('textarea'), function (textarea) { charCount += textarea.value.length; });
return charCount;
}
That will return the count of all textareas on the page. Change the querySelector to be more specific if you only want to count specific textareas.
One option would be to add onchange events to your textareas which call a function like below:
<script>
function validate() {
if(textareaLength() >= 500) {
//limit reached
}
}
function textareaLength() {
var charCount = 0;
Array.prototype.forEach.call(document.querySelectorAll('textarea'), function (textarea) { charCount += textarea.value.length; });
return charCount;
}
</script>
<textarea onchange="validate()"></textarea>
<textarea onchange="validate()"></textarea>
<textarea onchange="validate()"></textarea>
Count
Here's a really simple function:
function TextLength() {
return Array.prototype.reduce.call(
document.querySelectorAll('textarea'),
function(b,a) { return b+a.value.length }, 0);
}
Or with ES6:
const TextLength = () => Array.from(document.querySelectorAll('textarea')).reduce((b,a) => b + a.value.length, 0)
To use this:
TextLength();
Change
Now add this:
Array.prototype.forEach.call(document.querySelectorAll('textarea'), function (e) { e.oninput = TextLength });
And again, ES6:
Array.from(document.querySelectorAll('textarea')).forEach(e => e.oninput = TextLength );
Since the button is in the same form as the textarea elements, you can get a reference to the form using the button's form property. You can also get all the text area elements in the form using querySelectorAll, then loop over them, adding up the characters in each.
The following just counts the total number of characters in the textarea elements:
<button type="button" onclick="count(this)">Copy Notes</button>
and the function:
function count(el) {
var tas = el.form.querySelectorAll('textarea');
var numChars = 0;
for (var i=0, iLen=tas.length; i<iLen, I++) {
numChars += tas[i].value.length;
}
return numChars;
}
If you can rely on ES5+ methods, then you can do:
function count(el) {
return Array.prototype.reduce.call(el.form.querySelectorAll('textarea'),
function(numChars, ta){return numChars += ta.value.length}, 0);
}
Note that by convention, functions starting with a capital letter are reserved for constructors, so CopyFields should be copyFields.
Here's a working example:
function count(el) {
return Array.prototype.reduce.call(el.form.querySelectorAll('textarea'),
function(numChars, ta){return numChars += ta.value.length}, 0);
}
<form>
<textarea name="ta0"></textarea>
<textarea name="ta1"></textarea>
<textarea name="ta2"></textarea><br>
<input type="text" name="numChars">
<button type="button" onclick="this.form.numChars.value = count(this)">count</button>
<input type="reset">
</form>
If you have more than one textarea (Multiple) and you want to display character count on each textarea, you may try below code, as its working me like a charm.
$(document).ready(function () {
$('textarea').on("load propertychange keyup input paste",
function () {
var cc = $(this).val().length;
var id=$(this,'textarea').attr('id');
$('#'+id).next('p').text('character Count: '+cc);
});
$('textarea').trigger('load');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<textarea id="one">hello</textarea>
<p></p>
<textarea id="two"></textarea>
<p></p>
<textarea id="three"></textarea>
<p></p>
Hi I am NewBee in Javascript. This is my second week.
Below is the code that has a form with three input fields.
The relationship of the fields is:
the second field is twice the value of the first field
the third field is the square of the first field
I have managed to do the above but i am not able to do the below :
If a user enters a value in the second or third field, the script should calculate the appropriate value in the other fields. Currently the code works well ONLY if I enter the value in the first field.
I hope I explained well in other words : how do I enter say 144 in the last textbox and the other 2 textboxes show 12 and 24 respectively. Or If I enter 24 first and first and the third text boxes show 12 and 144.
Thanks
Vipul
<html>
<head>
<script>
window.onload = init;
function init() {
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
function doMath(){
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMath()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= doMath()>
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= doMath()> <br><br>
</form>
</body>
</html>
take a look at the code below:
<html>
<head>
<script>
window.onload = init;
var init = function(){
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
}
var doMathbase = function(){
console.log('here');
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
var doMathBase2Time = function(){
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value;
var base = document.getElementById("base").value = (baseNumber_timesTwo/2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMathbase()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= "doMathBase2Time()">
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= "doMathBaseSquare()">
<br><br>
</form>
</body>
You need to bind another function to the second and third field. I did it to the second. Now if you entered a number in the second field it return the 'base' number and the square of the base.
Try do it for the third :)
This should fit your needs:
Fiddle
//declaring those earlier saves you to get those by ID every
//time you call "doMath()" or something else
var base = document.getElementById("base");
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo");
var baseNumber_square = document.getElementById("baseNumber_square");
function clearUp() {
base.value = "";
baseNumber_timesTwo.value = "";
baseNumber_square.value = "";
}
function doMath() {
//check which of the fields was filled
if(baseNumber_timesTwo.value){
base.value = baseNumber_timesTwo.value / 2;
}
if(baseNumber_square.value){
base.value = Math.sqrt(baseNumber_square.value);
}
//fill other fields according to that
baseNumber_timesTwo.value = (base.value*2);
baseNumber_square.value = (base.value*base.value) ;
}
As you see: There is no need to write more than one arithmetic function if you make sure that only one value is given at the time of evaluation (this is achieved by the cleanUp()
method)
However there are still some flaws in this solution! Since you are a js beginner I would suggest you to read the code and think about possible solutions for those problems as a little exercise :-)
- You cannot enter a 2 (or more) digit number in any field, why not? What do you have to change in order to allow such numbers as input?
- Why is it better (in this case!) to set the values to " " instead of '0' in the cleanUp function? Why does the code break when you try using '0' instead of "" ?
- Why does doMath() only check for values in the last two field (baseNumber_timesTwo and baseNumber_square) while ignoring the 'base' field?
Greetings, Tim