I was wondering how you can resize text size in javascript based off of user input. Say for example, if the input exceeds 1000000000, then set text size to 14. The userinput in this case would be the Price and the size I would like to modify is the the TotalAmount and TipAmount.
Like this?
function changeTextSize() {
var input = document.getElementById('input').value;
document.getElementById('text').style.fontSize = input + "px";
}
<p id="text">I am some text.</p>
<input type="text" onkeyup="changeTextSize()" id="input">
Or like this?
function changeTextSize() {
var input = document.getElementById('input').value;
if (input > 1000) {
document.getElementById('text').style.fontSize = 30 + "px"; // Changed 14 to 30, because 14 would be smaller than the default text size
}
}
<p id="text">I am some Text</p>
<input type="text" onkeyup="changeTextSize()" id="input">
Is that what you are looking for?
var priceInput = document.getElementById('price-input');
priceInput.addEventListener('input', function(e) {
var price = parseInt(e.target.value);
priceInput.style.fontSize = price > 10 ? "14px" : "10px";
});
<input id="price-input" />
You may apply styles with JS.
Given that input and outputs are strings:
if(price > 10000){outputElement.style.fontSize = "0.8em"}
Related
I have two input value, the two value should be equal to 100%, one input contain 90% and the other should contain 10%, the value should be auto calculated based on input change in any field.
function checkValue (type) {
var no = 0;
var percent = 0;
var otherPercent = 0;
if (type === 'ninetyPercent') {
no = document.getElementById('ninetyPercent').value;
percent = parseInt(no) / 90;
otherPercent = (parseFloat(percent.toFixed(2)) - parseInt(no))
document.getElementById('tenPercent').value = otherPercent;
} else {
no = document.getElementById('tenPercent').value;
percent = parseInt(no) / 10;
otherPercent = (parseFloat(percent.toFixed(2)) + parseInt(no));
document.getElementById('ninetyPercent').value = otherPercent;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>This should consider as 90% for the input</label>
<input type="number" id="ninetyPercent" onInput="checkValue('ninetyPercent')" placeholder="90%">
<br>
<br>
<label>This should consider as 10% for the input</label>
<input type="number" id="tenPercent" onInput="checkValue('tenPercent')" placeholder="10%">
The general Idea is if we insert 90 in first input, the second input should auto fill 10, likewise if we input 10 in second input, the first input should auto fill 90 and so on.
Thanks in advance
This is my approach:
const inputs = document.querySelectorAll('#foo input');
function getOtherInput(changedInput) {
return [...inputs].find(input => input !== changedInput);
}
foo.addEventListener('input', (event) => {
const changedInput = event.target;
const definingValue = Number(changedInput.value);
const definingPercentage = Number(changedInput.dataset.percentage);
const derivedInput = getOtherInput(changedInput);
const derivedPercentage = Number(derivedInput.dataset.percentage);
const derivedValue = definingValue / definingPercentage * derivedPercentage;
derivedInput.value = derivedValue;
});
bar.addEventListener('click', () => {
let firstPercentage = NaN;
while (isNaN(parseInt(firstPercentage))) {
firstPercentage = parseInt(prompt('Enter the percentage for the first input (less than 100, greater than 0, integer):'));
}
inputs[0].dataset.percentage = firstPercentage;
inputs[1].dataset.percentage = 100 - firstPercentage;
})
<div id="foo">
<label>This should consider as 90% for the input
<input type="number" data-percentage="90" placeholder="90%"></label>
<br>
<br>
<label>This should consider as 10% for the input
<input type="number" data-percentage="10" placeholder="10%"></label>
</div>
<button type="button" id="bar">Change ratio</button>
When you click the button labeled "change ratio" it simply changes the data-percentage attributes, and the element behaviour updates automatically (still requires you to cause an input event to trigger in either input to update).
I need a text box which when maxlength is reached, need to position cursor to beginning and on key input needs to replace the characters as keys are pressed. My sample code is below. I can get cursor to start of textbox when maxlength is reached, but the characters are not replaced. Please share any ideas on how I can change the default input field behavior.
https://jsfiddle.net/yd62jugk/7/
function myFunction() {
if (document.getElementById("demo").selectionStart ===
parseInt(document.getElementById("demo").getAttribute('maxlength'), 10)) {
document.getElementById("demo").setSelectionRange(0,0);
}
}
<p>Press keys.</p>
<input type="text" id="demo" maxlength=5 onkeyup="myFunction()">
const input = document.querySelector('input');
const maxLength = Number(input.getAttribute('maxlength'));
input.addEventListener('keydown',(e)=>{
let value=input.value;
let start=input.selectionStart;
value[start+1]=e.keyCode;
input.setSelectionRange(start,start+1);
input.value=value;
if (start===maxLength){
input.setSelectionRange(0,1);
}
});
console.log(maxLength);
<!DOCTYPE html>
<html>
<body>
<p>Press a key inside the text field to set a red background color.</p>
<input type="text" id="demo" maxlength="5">
</body>
</html>
const demo = document.getElementById("demo")
demo.addEventListener("keyup", myFunction )
let cursor_position = 1
let can_update = false
function myFunction(e) {
let max = parseInt(demo.getAttribute('maxlength'), 10)
if ( can_update ) {
e.target.value = replaceAt(e.target.value, cursor_position - 1, e.key)
demo.setSelectionRange(cursor_position, cursor_position);
(cursor_position < max ) ? cursor_position++ : cursor_position = 1
} else if (demo.value.length === max) { can_update = true }
}
const replaceAt = (str, index, replacement) => str.substr(0, index) + replacement + str.substr(index + replacement.length)
<div id="textLength" class="textLength"> Hello World !!!</div>
<script>
function testTextLength() {
var textL = document.getElementById("textLength").innerText;
var maxLength = 15;
if (textL.length > maxLength) {
textL.style.fontSize = "250%";
}
}
</script>
Please help me that font size of "Hello World !!!" should change after reaching the more than 15 characters.
You are setting the fontsize to the innertext. Set it to the element.
<div id="textLength" class="textLength"> Hello World !!!</div>
<script>
function testTextLength() {
var textL = document.getElementById("textLength");
var maxLength = 15;
if (textL.innerText.length > maxLength) {
textL.style.fontSize = "250%";
}
}
</script>
Here's what I would do. Change your div to an input:
<input id="textLength" class="textLength">
Then, bind an event to it, like 'keyup'. You need this so your JS knows when to check on the length of text entered.
<script>
var textL = document.getElementById("textLength");
textL.addEventListener('keyup',function(){
var maxLength = 15;
var txt = textL.value;
if (txt.length > maxLength) textL.style.fontSize = "250%";
});
</script>
Instead of 'keyup', you could also listen for 'keypress', 'keydown' or 'change'. In this case, I recommend using 'keyup'. Here's a working example:
https://jsfiddle.net/wxmvagL3/3/
If you want to reset the font size when the length goes below 15 chars, add an else block:
if (txt.length > maxLength) textL.style.fontSize = "250%";
else textL.style.fontSize = "100%";
Good day everyone
I have a simple textarea on a page,and I need to dynamically count number of symbols, show how much is left under the form,and limit number of characters should be 350.
Thanks in advance.
What i exactly need is to display how many symbols are left to type
function limit(element)
{
var max_chars = 350;
if(element.value.length > max_chars) {
element.value = element.value.substr(0, max_chars);
}
}
<textarea onkeydown="limit(this);" onkeyup="limit(this);"></textarea>
var max_chars = 5;
var charsLeftDisplay = document.getElementById("charsLeft");
function limit(element) {
if (element.value.length > max_chars) {
element.value = element.value.slice(0, -1);
return false;
}
charsLeftDisplay.innerHTML = (max_chars - element.value.length) + " characters left...";
}
<textarea onkeyup="limit(this)"></textarea>
<p id="charsLeft"></p>
I think the best way to do this would be to use JQuery
here's the html
<textarea id="textareaID" rows="4" cols="50" maxlength="50"></textarea>
<p id="numberOfChars"><strong>Character typed:</strong> 0</p>
<p><strong>Max Character:</strong> 50</p>
and here's the jquery code
$('#textareaID').bind('input propertychange', function() {
if(this.value.length){
$("#numberOfChars").html("<strong>Character typed:</strong> "+this.value.length);
}
});
and here's a working fiddle as well https://jsfiddle.net/Visrozar/zbw7j64j/
Here is a simple solution,
just display the leftCharacters in a placeholder;
<script>
$(function() {
var $textarea = $('textarea');
var $input = $('input[name="spaces"]');
var maxLength = $textarea.attr('maxlength');
$input.val(maxLength);
$textarea.on('input', function() {
var currentLength = $textarea.val().length;
var leftCharacters = (maxLength - currentLength);
$input.val(leftCharacters);
});
});
</script>
<textarea name=test" maxlength="350"></textarea>
<input name="spaces" disabled />
This solution really works very well:
1 - Insert a div with id="textarea_count" for example in the place you want to show remaining characters, in your HTML file, near your textarea element (above or under):
<div class="form-group">
<label asp-for="DescCompetencia" class="col-md-2 control-label"></label>
<div class="col-md-10">
<textarea asp-for="DescCompetencia" class="form-control" rows="5"></textarea>
<span asp-validation-for="DescCompetencia" class="text-danger"></span>
<div id="textarea_count"></div>
</div>
</div>
2 - Insert in your javascript file or after /html element in the page you are editing the textarea element:
$(document).ready(function () {
var text_max = 500; //change by your max desired characters
var text_min = 7; //change to your min desired characters (or to zero, if field can be blank))
if ($('#DescCompetencia').length) {
var texto_disponivel = text_max - $('#DescCompetencia').val().length;
}
$('#textarea_count').html(texto_disponivel + ' caracteres disponÃveis para digitar');
$('#DescCompetencia').keyup(function () {
var text_length = $('#DescCompetencia').val().length;
var text_remaining = text_max - text_length;
if (text_length <= text_min) {
$('#textarea_count').html(text_remaining + ' caracteres remanescentes. Digite ' + text_min + ' ou mais caracteres.');
}
else {
$('#textarea_count').html(text_remaining + ' caracteres remanescentes');
}
}); });
Must have Jquery already loaded before calling the above function.
So I've written a web page with a few JavaScript functions.
The page runs perfectly in Dreamweaver but when I tried it out in a browser (Google Chrome and Firefox) the JavaScript flashes for a split second then clears. I have no idea at all why this is.
<body>
<form name="myForm">
<ol>
<li>
<h1> TILE CALCULATOR</h1>
</li>
<li>
<label for="wall height">Wall height (cm)</label>
<input type="text" id="wall_height" />
</li>
<li>
<label for="wall width">Wall Width (cm)</label>
<input type="text" id="wall_width" />
</li>
<li>
<label for="tile height">Tile Height (cm)</label>
<input type="text" id="tile_height" />
</li>
<li>
<label for="tile width">Tile Width (cm)</label>
<input type="text" id="tile_width" />
</li>
<button onclick="javascript:validate();"> Calculate </button>
</ol>
</form>
<br />
<p id="result"></p>
<br />
<canvas id="myCanvas">
Your browser does not support this feature</canvas>
<br />
<br />
<script language="javascript" type="text/javascript">
//functoin to validate the inputs by the user
//user can only enter a number and all fields must be filled
function validate()
{
//first make sure canvas is clear
clearCanvas()
//take the inputs as variables
var x = document.getElementById("tile_width").value;
var y = document.getElementById("tile_height").value;
var z = document.getElementById("wall_width").value;
var i = document.getElementById("wall_height").value;
//check if the user has entered nothing and alert if they have
if (x==null || x=="" || y==null || y=="" || z==null || z=="" || i==null || i=="")
{
alert("All the fields have to be filled out!");
clearResult();
}
// check if the user has entered invalid values, only numbers can be entered
if (isNaN(x) == true || isNaN(y) == true || isNaN(z) == true || isNaN(i) == true)
{
alert("Dimensions can only be numbers!");
clearResult();
}
//check for negatives
if (x <= 0 || y <= 0 || z <= 0 || i <= 0)
{
alert("invalid dimension input, positive non-zero values only");
clearResult();
}
//if valid calculate tiles and print
else
tileCalculator();
}
function tileCalculator()
{
//take the input as variables
var tileWidth = document.getElementById("tile_width").value;
var tileHeight = document.getElementById("tile_height").value;
var wallWidth = document.getElementById("wall_width").value;
var wallHeight = document.getElementById("wall_height").value;
//find the areas of the tile and the wall
var tileArea = tileWidth * tileHeight;
var wallArea = wallWidth * wallHeight;
//divide these to find the number of tiles needed
var noOfTiles = (wallArea/tileArea);
//prints the result of noOfTiles
document.getElementById("result").innerHTML=" The number of Tiles you will need are : " + noOfTiles;
//scalled tiles to the canvas width of your choice
var scalledWidth = 500;
var ratioHW = wallHeight/wallWidth;
var scalledHeight = ratioHW*scalledWidth;
//scaled tile sizes
//scale the tiles to correct pixels
var scalledTileWidth = (tileWidth/wallWidth)*scalledWidth;
var scalledTileHeight = (tileHeight/wallHeight)*300;
//finds the number of tiles needs in a row
var noWidth = wallWidth/tileWidth;
//number of tiles in a column
var noHeight = wallHeight/tileHeight;
var canvas = document.getElementById("myCanvas");
canvas.style.width=scalledWidth + "px";
canvas.style.height=scalledHeight + "px";
printWall(0,0,noWidth,scalledTileWidth,(scalledTileHeight/2),noHeight);
}
//print a tile given the position and dimensions
function printTile(x,y,tileWidth,tileHeight)
{
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillRect(x,y,tileWidth,tileHeight);
}
//prints one row of tiles given the starting position and number to be printed
function printTileRow(x,y,numberOfTiles,tileWidth,tileHeight)
{
var start = 0;
//loops upto number of tiles in a row
while (start < numberOfTiles)
{
//prints a tile each time
printTile(x,y,tileWidth,tileHeight);
//next brick position
x = x + (tileWidth + 1); // add a space between tiles here.
start++;
}
}
//prints the wall
function printWall(x,y,numberOfTiles,tileWidth,tileHeight,numberOfRows)
{
//holds whether last row was shifted
var shiftCount = 0;
//starting index
var start = 0;
//loop up adding a row until required number of rows
while (start < numberOfRows)
{
//prints half a tile at the start of each row
printTile(0,y,(0.5 * tileWidth - 1),(tileHeight));
//prints the row
printTileRow((x+shiftCount),y,numberOfTiles,tileWidth,tileHeight);
//if shifted
if (shiftCount > 0)
{
//was shifted last row
shiftCount = 0;
}
else
{
//was not shifted last row
shiftCount = shiftCount + (0.5*tileWidth);
}
start++;
//start next row
y = y + (tileHeight + 1);
}
}
//clears the canvus each time the button is pressed
function clearCanvas()
{
//reset canvus to 300 by 300 and clear
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext('2d');
canvas.style.height="300px";
canvas.style.width="300px";
context.clearRect(0,0,300,300);
}
function clearResult()
{
document.getElementById("result").innerHTML="";
}
</script>
</body>
I would really appreciate it if someone could have a quick look for me! Thanks,
Try using onclick="javascript:validate();" on the form tag instead of on the button tag and try using 'onsubmit' instead of 'onclick'
Just replace your onclick attribute by onclick='validate(); return false'.
OR (better then previous)
Just add a type="button" attribute to your button tag, once the HTML5 button's default behavior is to submit forms.
Useful tip
Bind your handler programatically, this way (with no jQuery):
<button type="button" id="calculate"> Calculate </button>
...
window.addEventListener("load", function(){
document.getElementById("calculate").addEventListener("click", validate);
});
there is no problem with kepping the button in the form you you need to return false everytime to avoid the form submit using the return false like this
onclick="javascript:validate();return false;"