I want to change width of a textfield when user enters more than 17 characters in that textfield using Javascript (if possible) otherwise by any other means.
I wrote a code to do the same, but it only changes width when user click outside the textfield after entering more than 17 characters. I want it to change width automatically when user enters more than 17 characters :
function widen() {
var value = nametf.value;
if (value.length > 17) {
nametf.style.width = '300px';
} else {
nametf.style.width = '200px';
}
}
#nametf {
width: 200px;
height: 20px;
padding: 5px 10px;
}
<title>TEXTFIELD TEST</title>
<form method="get" action="wwhome.php">
<input type="text" name="name1" id="nametf" onchange="widen()" value="" required>
</form>
onchange gets activated when the input looses focus, that's why it works when you click outside. On the other hand oninput will be triggered immediately when the value changes:
const nametf = document.getElementById('nametf');
function widen() {
var value = nametf.value;
if (value.length > 17) {
nametf.style.width = '300px';
} else {
nametf.style.width = '200px';
}
}
#nametf {
width: 200px;
height: 20px;
padding: 5px 10px;
}
<html>
<form method="get" action="wwhome.php">
<input type="text" name="name1" id="nametf" oninput="widen()" value="" required>
</form>
</html>
You need to pass a self-reference to the function using this. I would also change on-change to on-key-up, because on-change waits for you to move focus away from the field.
onkeyup="widen(this)"
Then you need to parameterize the function with your variable "nametf"
function widen(nametf) {
// ...
}
Example
function widen(nametf) {
var value = nametf.value;
if (value.length > 17) {
nametf.style.width = '300px';
} else {
nametf.style.width = '200px';
}
}
#nametf {
width: 200px;
height: 20px;
padding: 5px 10px;
}
<title>TEXTFIELD TEST</title>
<form method="get" action="wwhome.php">
<input type="text" name="name1" id="nametf" onkeyup="widen(this)" value="" required>
</form>
A better approach would be to use em units to expand the text are based on the current value.
initExpandingFields();
function initExpandingFields() {
Array.from(document.querySelectorAll('.expanding-field')).forEach(field => {
field.addEventListener('keyup', onFieldChange);
});
}
function onFieldChange(e) {
let field = e.target,
len = field.value.length;
field.style.width = (len * 0.667) + 'em';
}
#nametf {
width: 200px;
height: 20px;
padding: 5px 10px;
}
<title>TEXTFIELD TEST</title>
<form method="get" action="wwhome.php">
<input type="text" class="expanding-field" name="name1" id="nametf" value="" required>
</form>
Try this:
var nametf = document.getElementById("nametf");
nametf.addEventListener("input", function(){
if(nametf.value.length > 17) {
nametf.size = "30";
} else {
nametf.size = "20";
}
});
#nametf {
height: 20px;
padding: 5px 10px;
}
<title>TEXTFIELD TEST</title>
<form method="get" action="wwhome.php">
<input type="text" name="name1" id="nametf" size="20" value="" required>
</form>
in my class we are using firstChild.nodeValue to display text if a user enters in an incorrect value. However, I can't get my two other fields to display the error message and only the first one. What am I doing wrong? When I run it in the code snipped is says that the nodeValue is null. I have the error messages display through a span and they are being used by the firstChild.nodeValue.
var $ = function (id) {
return document.getElementById(id);
}
var calculateClick = function () {
var investment = parseInt( $("investment").value);
var rate = parseFloat( $("rate").value);
var years = parseInt($("years").value);
//var amount = interest * rate * years;
if (investment==="" || investment < 100 || investment > 100000){
$("investment_error").firstChild.nodeValue="Must be an integer from 100 - 100,000";
}
else if (rate ==="" || rate <0.1 || rate >12){
$("rate_error").firstChild.nodeValue="Must be a value from .1 - 12";
}
else if (years ==="" || years <1 || years > 50){
$("years_error").firstChild.nodeValue="Must be an integer from 1 - 50";
}
var nt = 4*years;
var amount = investment * (1 + (rate/4)) ** nt;
$("future_value").value=amount.toFixed(2);
}
var clear_fields = function (){
$("investment").value="";
$("rate").value="";
$("years").value="";
$("future_value").value="";
}
window.onload = function () {
$("calculate").onclick = calculateClick;
$("calculate").ondblclick=clear_fields;
$("investment").focus();
}
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 48%;
padding: 0 1em .5em;
border: 3px solid blue;
}
h1 {
margin: .5em 0;
text-align: center;
}
label {
float: left;
width: 10em;
text-align: right;
padding-bottom: .5em;
}
input {
margin-left: 1em;
margin-bottom: .5em;
}
span {
color: blue;
}
<!DOCTYPE html>
<html>
<head>
<title>Future Value Calculator</title>
<link rel="stylesheet" href="future_value.css">
<script src="future_value.js"></script>
</head>
<body>
<main>
<h1 id="heading">Future Value Calculator</h1>
<label for="investment">Investment Amount:</label>
<input type="text" id="investment">
<span id="investment_error"> </span><br>
<label for="rate">Annual Interest Rate:</label>
<input type="text" id="rate">
<span id="rate_error"></span><br>
<label for="years">Number of Years:</label>
<input type="text" id="years">
<span id="years_error"></span><br>
<label for="future_value">Future Value:</label>
<input type="text" id="future_value" disabled="disabled"><br>
<label> </label>
<input type="button" id="calculate" value="Calculate"><br>
</main>
</body>
</html>
Its working on the first span becouse you have space between the span tags as:
with space
<span id="investment_error"> </span>
without
<span id="rate_error"></span>
In any case you should use innerHTML instead.
first child is good in case you already have a child in the html tags like this
<div>
<p id="i_am_div_first_child"> first child</p>
</div>
please hit correct answer if that was helpfull.
So what is the difference? A simple test will show you why.
console.log("1:", document.querySelector("#s1").firstChild)
console.log("2:", document.querySelector("#s2").firstChild)
<span id="s1"> </span>
<span id="s2"></span>
The one has a whitespace in it, the others do not the one with the whitespace has a firstChild, the others do not.
What should you do?
I would just set the textContent or innerHTML of the span and not set the nodeValue.
And another issue with your code, is you have
var rate = parseFloat( $("rate").value);
and
if ( rate==="")
That empty string check is not going to happen to be true ever since parseFloat is going to return NaN.
$("rate_error").firstChild returns null because it has no childrne (not even whit space), and so does not have a nodeValue property.
You could just use innerHTML instead of firstChild.nodeValue.
Also you don't need the else, just tell the user immediately all they have to fix.
var $ = function(id) {
return document.getElementById(id);
}
var calculateClick = function() {
var investment = parseInt($("investment").value);
var rate = parseFloat($("rate").value);
var years = parseInt($("years").value);
//var amount = interest * rate * years;
if (investment === "" || investment < 100 || investment > 100000) {
$("investment_error").innerHTML = "Must be an integer from 100 - 100,000";
}
if (rate === "" || rate < 0.1 || rate > 12) {
$("rate_error").innerHTML = "Must be a value from .1 - 12";
}
if (years === "" || years < 1 || years > 50) {
$("years_error").innerHTML = "Must be an integer from 1 - 50";
}
var nt = 4 * years;
var amount = investment * (1 + (rate / 4)) ** nt;
$("future_value").value = amount.toFixed(2);
}
var clear_fields = function() {
$("investment").value = "";
$("rate").value = "";
$("years").value = "";
$("future_value").value = "";
}
window.onload = function() {
$("calculate").onclick = calculateClick;
$("calculate").ondblclick = clear_fields;
$("investment").focus();
}
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 48 %;
padding: 0 1em .5em;
border: 3px solid blue;
}
h1 {
margin: .5em 0;
text-align: center;
}
label {
float: left;
width: 10em;
text-align: right;
padding-bottom: .5em;
}
input {
margin-left: 1em;
margin-bottom: .5em;
}
span {
color: blue;
}
<!DOCTYPE html>
<html>
<head>
<title>Future Value Calculator</title>
<link rel="stylesheet" href="future_value.css">
<script src="future_value.js"></script>
</head>
<body>
<main>
<h1 id="heading">Future Value Calculator</h1>
<label for="investment">Investment Amount:</label>
<input type="text" id="investment">
<span id="investment_error"> </span><br>
<label for="rate">Annual Interest Rate:</label>
<input type="text" id="rate">
<span id="rate_error"></span><br>
<label for="years">Number of Years:</label>
<input type="text" id="years">
<span id="years_error"></span><br>
<label for="future_value">Future Value:</label>
<input type="text" id="future_value" disabled="disabled"><br>
<label> </label>
<input type="button" id="calculate" value="Calculate"><br>
</main>
</body>
</html>
I have this input text:
<div class="form-group">
<label for="newPrice">New Price</label>
<input type="text" class="form-control" id="newPrice" name="newPrice" placeholder="New price">
</div>
I would like to change the border of the input dynamically as the user is typing depending what the value is.
This value will be a percent based on an earlier defined amount that will change depending on the value the user is adding.
So if the value is under 5% it's red between 5-10% it's amber and over 10% is green etc.
Any JavaScript whizzes out there know the best way to do this?
I'll go with 2 events. The first is input, but contenteditable elements won't fire an input event on IE11, so I'll go for keypress with a timeout too.
input will be fired right after a user inputs something and the value is changed. keypress will fire after a user inputs something but right before the value is changed, in between.
This way you will keep all modern and older browsers covered (to a limit, because of addEventListener):
var tim = null;
var el = document.getElementById("newPrice");
el.addEventListener("keypress", function() {
tim = setTimeout(input, 0);
});
el.addEventListener("input", function input() {
clearTimeout(tim);
// do whatever you want with el.value
if (el.value == "BLAH") {
el.style.backgroundColor = "red";
} else if (parseInt(el.value) > 10) {
el.style.backgroundColor = "green";
} else if (parseInt(el.value) < -12) {
el.style.backgroundColor = "whizzeblue";
}
});
<input id="txt" type="number" onkeyup="changeborder(this.id, this.value)" />
<script type="text/javascript">
function changeborder(id, value){
if(value < 5){
document.getElementById(id).style.border = "2px solid red";
}
else if(value > 5 && value < 10 ){
document.getElementById(id).style.border = "2px solid yellow";
}
}
</script>
Use focusout . In snippet validation is not applied.
$("#newPrice")
.focusout(function() {
var price = $(this).val();
if (parseInt(price) <= 5) {
$(this).removeClass('green');
$(this).removeClass('blue');
$(this).addClass('red');
}
if (parseInt(price) > 5 && parseInt(price) <= 10) {
$(this).removeClass('red');
$(this).removeClass('blue');
$(this).addClass('green');
}
if (parseInt(price) > 10) {
$(this).removeClass('green');
$(this).removeClass('red');
$(this).addClass('blue');
}
});
.red {
border: solid 2px red;
}
.green {
border: solid 2px green;
}
.blue {
border: solid 2px blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label for="newPrice">New Price</label>
<input type="text" class="form-control" id="newPrice" name="newPrice" placeholder="New price">
</div>
I'm trying to change the width of a box using user-input with a for loop and if-else statement. Cant seem to get the first if statement to execute. Here is the javascript:
function changeWidth(){
var widthSize = document.getElementById("num").value;
for(var s = 0; s < widthSize; s++){
if(s < 0 || s > 800){
alert("Not a valid width size"); }
else {
document.getElementById("box-1").style.width="s";
}
}
}
The CSS:
.box {
border: 1px solid black;
width: 200px;
height: 200px;
float:left;
margin-left:30px;
}
The HTML:
<input type="number" id="num" name="num" value="" placeholder="Please enter width size" />
<input type="button" id="btt3" name="btt3" value="Generate size" onclick="changeWidth();" />
<div class="box" id="box-1"></div>
You don't need a loop, this should do it.
function changeWidth(){
var widthSize=document.getElementById("num").value;
if(widthSize < 0 || widthSize > 800){
alert("Not a valid width size"); }
else {
document.getElementById("box-1").style.width=widthSize+"px";
}
}
If your trying to change the width several times, So you just need to remove the quotes for your variable s.
Like this:
document.getElementById("box-1").style.width=s;
But in case your trying to just set the value of widthSize, and just once, it maybe be like this:
document.getElementById("box-1").style.width=widthSize;
return;
This should work...
function changeWidth() {
var widthSize = parseInt(document.getElementById("num").value);
if (widthSize < 0 || widthSize > 800) {
alert("Not a valid width size");
} else {
document.getElementById("box-1").style.width = widthSize + 'px';
}
}
.box {
border: 1px solid black;
width: 200px;
height: 200px;
float: left;
margin-left: 30px;
transition: width 1s ease;
}
<input type="number" id="num" name="num" value="" placeholder="Please enter width size" /> <input type="button" id="btt3" name="btt3" value="Generate size" onclick="changeWidth();" />
<div class="box" id="box-1">
<div class="box-1-words" id="b1-words"> Hello World </div>
</div>
s will never be less than 0 as thats the min value for your for loop and if the number u input is less than 800 then the IF condition will never execute. Are you entering a number more than 800 and still the alert is not showing up?
function changeWidth(){
var widthSize=document.getElementById("num").value;
for(var s=0;s<widthSize;s++){
if(widthSize<0 || widthSize>800){
alert("Not a valid width size");
break;
}
else{
var a ="transition:2s ease-in;width:"+widthSize+"px;"
document.getElementById("box-1").style.cssText=a;
}
}
}
.box{border:1px solid black; width:200px; height:200px; float:left; margin-left:30px;}
<input type="number" id="num" name="num" value="" placeholder="Please enter width size" />
<input type="button" id="btt3" name="btt3" value="Generate size" onclick="changeWidth();" />
<div class="box" id="box-1"></div> </body>
How can I check in jQuery if inputs with name denominationcomune_{{loop.index}} and denominationcomune_{{loop.index}} are empty not all inputs ?
I have a twig like this:
<form action="" method="post">
{% for mat in mat_temp_array %}
<input type="text" name="nomentite_{{loop.index}}"/>
<input type="text" name="denominationcomune_{{loop.index}}" value="{{ mat.denominationcommun }}"/>
<input type="text" name="denominationcomerce_{{loop.index}}" value="{{ mat.denominationcomerce }}"/>
{% endfor %}
<input type="submit" class="btn" value="save"/>
</form>
var empty = true;
$('input[type="text"]').each(function() {
if ($(this).val() != "") {
empty = false;
return false;
}
});
This should look all the input and set the empty var to false, if at least one is not empty.
EDIT:
To match the OP edit request, this can be used to filter input based on name substring.
$('input[name*="denominationcomune_"]').each(...
You could do it like this :
bool areFieldEmpty = YES;
//Label to leave the loops
outer_loop;
//For each input (except of submit) in your form
$('form input[type!=submit]').each(function(){
//If the field's empty
if($(this).val() != '')
{
//Mark it
areFieldEmpty = NO;
//Then leave all the loops
break outer_loop;
}
});
//Then test your bool
You can do it using simple jQuery loop.
Total code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{display:inline-block;height:20px;padding:4px;margin-bottom:9px;font-size:13px;line-height:18px;color:#555555;}
textarea{height:auto;}
select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{background-color:#ffffff;border:1px solid #cccccc;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-webkit-transition:border linear 0.2s,box-shadow linear 0.2s;-moz-transition:border linear 0.2s,box-shadow linear 0.2s;-ms-transition:border linear 0.2s,box-shadow linear 0.2s;-o-transition:border linear 0.2s,box-shadow linear 0.2s;transition:border linear 0.2s,box-shadow linear 0.2s;}textarea:focus,input[type="text"]:focus,input[type="password"]:focus,input[type="datetime"]:focus,input[type="datetime-local"]:focus,input[type="date"]:focus,input[type="month"]:focus,input[type="time"]:focus,input[type="week"]:focus,input[type="number"]:focus,input[type="email"]:focus,input[type="url"]:focus,input[type="search"]:focus,input[type="tel"]:focus,input[type="color"]:focus,.uneditable-input:focus{border-color:rgba(82, 168, 236, 0.8);outline:0;outline:thin dotted \9;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);height: 20px;}
select,input[type="radio"],input[type="checkbox"]{margin:3px 0;*margin-top:0;line-height:normal;cursor:pointer;}
select,input[type="submit"],input[type="reset"],input[type="button"],input[type="radio"],input[type="checkbox"]{width:auto;}
.uneditable-textarea{width:auto;height:auto;}
#country{height: 30px;}
.highlight
{
border: 1px solid red !important;
}
</style>
<script>
function test()
{
var isFormValid = true;
$(".bs-example input").each(function(){
if ($.trim($(this).val()).length == 0){
$(this).addClass("highlight");
isFormValid = false;
$(this).focus();
}
else{
$(this).removeClass("highlight");
}
});
if (!isFormValid) {
alert("Please fill in all the required fields (indicated by *)");
}
return isFormValid;
}
</script>
</head>
<body>
<div class="bs-example">
<form onsubmit="return test()">
<div class="form-group">
<label for="inputEmail">Email</label>
<input type="text" class="form-control" id="inputEmail" placeholder="Email">
</div>
<div class="form-group">
<label for="inputPassword">Password</label>
<input type="password" class="form-control" id="inputPassword" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
</body>
</html>
Define a helper function like this
function checkWhitespace(inputString){
let stringArray = inputString.split(' ');
let output = true;
for (let el of stringArray){
if (el!=''){
output=false;
}
}
return output;
}
Then check your input field value by passing through as an argument. If function returns true, that means value is only white space.
As an example
let inputValue = $('#firstName').val();
if(checkWhitespace(inputValue)) {
// Show Warnings or return warnings
}else {
// // Block of code-probably store input value into database
}
I'd suggest to add an class='denominationcomune' to all elements that you want to check and then use the following:
function are_elements_emtpy(class_name)
{
return ($('.' + class_name).filter(function() { return $(this).val() == ''; }).length == 0)
}
$('input[type="text"]').get().some(item => item.value !== '');
$(document).ready(function () {
$('input[type="text"]').blur(function () {
if (!$(this).val()) {
$(this).addClass('error');
} else {
$(this).removeClass('error');
}
});
});
<style>
.error {
border: 1px solid #ff0000;
}
</style>