How to restrict displaying minus values in the text field - javascript

Fiddle.
I have a text field, I want to restrict showing negative values to this text field, if I got negative value then I dont want to display that value in the text box.But my ng-model should contain that negative value.
function LoginController($scope) {
$scope.number = -10;
$scope.number1 = -20;
$scope.number2 = -30;
}
<div ng-app ng-controller="LoginController">
<input ng-model="number"></input>
<input ng-model="number1"></input>
<input ng-model="number2"></input>
<input type="submit" ng-click="login()" value="Login"></input>
</div>

<html>
<body>
<input type="text" onkeypress="OnlyNumber(this);"></input>
</body>
<script>
function OnlyNumber(i)
{
if(i.value.length>0)
{
i.value = i.value.replace(/[^\d]+/g, '');
}
}
</script>
</html>
Use this javascript code.
I have used onkeypress javascript attribute
You can use ng-keyup angularjs directive
check here

function cleanInput(selector){
var elements = document.querySelectorAll(selector);
for(element in elements){
if(parseInt(element.value) < 0 ) {element.value = '';}
}
}
Provided that this is your HTML:
<div id="clean-div" ng-app ng-controller="LoginController">
<input ng-model="number"></input>
<input ng-model="number1"></input>
<input ng-model="number2"></input>
<input type="submit" ng-click="login()" value="Login"></input>
Then,
cleanInput('#clean-div input');
EDIT: Solution by using HTML, is only valid for newer browsers. If you don't care, go ahead with input type=number solution. Else JavaScript is needed.

//try using conditional expression like this.
function LoginController($scope) {
let num=-10
$scope.number = num<0?'':num;
}

No need to use javascript at all.
Convert
<input ng-model="number"></input>
to
<input type="number" min="0" ng-model="number"></input>
for every input tag you need.
P.S: This will not perform not-showing when onLoad and copy/paste is the action but issue a warning that the value is not eligible for the input.

<form action="" method="post">
<input type="number" id="numval" min="0" />
</form>
// Select your input element.
var number = document.getElementById('numval');
// Listener for input element.
number.onkeydown = function(e) {
if(!((e.keyCode > 95 && e.keyCode < 106)
|| (e.keyCode > 47 && e.keyCode < 58)
|| e.keyCode == 8)) {
return false;
}
}
95, < 106 corresponds to Numpad 0 through 9;
47, < 58 corresponds to 0 through 9 on the Number Row; and 8 is Backspace.

HTML :
<div ng-app ng-controller="LoginController">
<input ng-model="number" ng-change="onNumberChange('number')">
</input>
<input ng-model="number1" ng-change="onNumberChange('number1')">
</input>
<input ng-model="number2" ng-change="onNumberChange('number2')">
</input>
<input type="submit" ng-click="login()" value="Login"></input>
</div>
Controller :
function LoginController($scope) {
$scope.number = -10;
$scope.number1 = -20;
$scope.number2 = -30;
$scope.onNumberChange = function(valueName){
var number = parseInt($scope[valueName]);
if(number < 0){
$scope[valueName] = 0
}
}
}

Related

How to disable button until input field has a value using AngularJS

I know nothing about Angular but I was asked to create a validation for the new google map input. All I want to do is have the #lugar_continuar button stay disabled until the input #ciudad is filled in, but the button isn't disabled for some reason.
index.php, input to validate
<div class="">
<input id="ciudad" name="ciudad" class="ciudad" type="text"
placeholder="Ciudad" value="" required ng-model="ciudadSet">
<div id="map"></div>
<input type="hidden" id="distance" size="31" value="31">
</div>
Input type button that should stay disabled
<input id="lugar_continuar" name="lugar_continuar" type="button" onClick="_gaq.push(['_trackEvent', 'Reserva', 'Continuar', 'preciohome'])" value="Continuar" ng-disabled="validacion2() && ciudadSet" ng-click="from_precio = true" >
Using ng-model doesn't work. I also tried with JS, in main.js:
var ReservasApp = angular.module('Reservas',['rzModule']);
ReservasApp.controller('ReservasController',function($scope){
$scope.ciudad = "";
$scope.validacionCiudad = function() {
var disabled = false;
if( $scope.ciudad != null && $scope.ciudad != "" )
{
disabled = false;
}
else
{
disabled = true;
}
}
}
index.php
<input id="lugar_continuar" name="lugar_continuar" type="button" onClick="_gaq.push(['_trackEvent', 'Reserva', 'Continuar', 'preciohome'])" value="Continuar" ng-disabled="validacion2() && validacionCiudad()" ng-click="from_precio = true" >
I also tried using only JS:
var validacionCiudad = function() {
var ciudad = document.getElementById('ciudad');
var btn = document.getElementById('lugar_continuar');
if (ciudad.value == "") {
btn.setAttribute("disabled", "disabled");
} else {
btn.removeAttribute("disabled");
}
}
validacionCiudad();
I have tried many ways to achieve this but nothing is working!
you can try this: ng-disabled = "ciudadSet == ''", since ng-disabled is valid when the expression equals true. If you must call function validacionCiudad to judge this, you have to return bool value in your function. May this will help.
Change $scope.ciudad ="" to $scope.ciudad = undefined;
change your ng-model to:
ng-model="ciudad"
and your ng-disabled to:
ng-disabled="!ciudad"
that shall work
You can validate it like this.
<div ng-controller="MyCtrl">
<form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate>
<input name="name" ng-model="name" type="text" required >
<br>
<button type="submit" ng-disabled="userForm.$invalid" >Enviar</button>
</form>
</div>
https://jsfiddle.net/ivanm07/y2t88817/

Counter char script for many fields

Hi I want use this script to count char in form with many fields,
but not want duplicate code, I want use only one code for all fields,
how can pass to javascript name fields count and display this count...
As one counter for many fields input type...
thanks
Salvatore
<script>
function countChar(val) {
var len = val.value.length;
if (len >= 66) {
val.value = val.value.substring(0, 66);
} else {
$('#charNum').text(65 - len);
}
};
</script>
<div id="charNum"></div>
<input type="text" name="name_var1" value="" maxlength="66" onkeyup="countChar(this)" />
<div id="charNum"></div>
<input type="text" name="name_var2" value="" maxlength="66" onkeyup="countChar(this)" />
<div id="charNum"></div>
<input type="text" name="name_var3" value="" maxlength="66" onkeyup="countChar(this)" />
the problem is that you are using ids several times. Try to work with classes and generate the selectors from the class name of the element.
<script>
function countChar(val) {
var len = val.value.length;
if (len >= 66) {
val.value = val.value.substring(0, 66);
} else {
$('.' + val.className + '_charNum').text(65 - len);
}
};
</script>
<div class="name_var1_charNum"></div>
<input class="name_var1" type="text" name="name_var1" value="" maxlength="66" onkeyup="countChar(this)" />
<div class="name_var2_charNum"></div>
<input class="name_var2" type="text" name="name_var2" value="" maxlength="66" onkeyup="countChar(this)" />
<div class="name_var3_charNum"></div>
<input class="name_var3" type="text" name="name_var3" value="" maxlength="66" onkeyup="countChar(this)" />
As far as I understood you do need to display characters left value for each field (depending on max-length) and restrict user from adding extra characters (more than allowed limit). Probably that's what you need.
<div class="countable-item">
<div class="char-num"></div>
<input type="text" name="any" class="countable" max-length="66" />
</div>
<div class="countable-item">
<div class="char-num"></div>
<input type="text" name="any2" class="countable" max-length="66" />
</div>
<script>
(function($){
var restrictMaxLength = function () {
var maxLength = $(this).attr('max-length'),
currentValue = $(this).val(),
currentLength = currentValue.length;
if (currentLength >= maxLength) {
return false;
}
},
displayCountCharacters = function () {
var maxLength = $(this).attr('max-length'),
currentValue = $(this).val(),
currentLength = currentValue.length;
$(this).closest('.countable-item')
.find('.char-num')
.text(maxLength - currentLength);
};
$(document)
.on('keypress', '.countable', restrictMaxLength)
.on('keyup', '.countable', displayCountCharacters);
})(jQuery);
</script>

getting values to populate a text instead of the span

I have pieced together a script that adds the values in text boxes and displays the sums in a span. I have tried a ton of things, but I can not get it to display the sums in a input textbox. Here is a fiddle that I have been working in ..
http://jsfiddle.net/elevationprint/MaK2k/17/
Basically I want to change the spans to input text boxes. If anyone can take a look and let me know what I am missing, I would appreciate it!
The code is this
HTML
Red<br>
12x12<input class="qty12" value="" /><br/>
12x24<input class="qty24" value="" /><br>
<br>
Blue<br>
12x12<input class="qty12" value="" /><br/>
12x24<input class="qty24" value="" /><br>
<br><br>
Total = <span class="qty12lable"></span> x $.95<br>
Total = <span class="qty24lable"></span> x $1.40<br>
SCRIPT
$('.qty12').keyup(function(){
var qty12Sum=0;
$('.qty12').each(function(){
if (this.value != "")
qty12Sum+=parseInt(this.value);
});
// alert('foo');
$(".qty12lable").text(qty12Sum);
//console.log(amountSum); });
$('.qty24').keyup(function(){
var qty24Sum=0;
$('.qty24').each(function(){
if (this.value != "")
qty24Sum+=parseInt(this.value);
});
// alert('foo');
$(".qty24lable").text(qty24Sum);
//console.log(amountSum); });
You can target the input fields like so:
Total = <input class="qty12lable" value=""> x $.95<br>
Total = <input class="qty24lable" value=""> x $1.40<br>
$("input.qty12lable").val(qty12Sum);
$("input.qty24lable").val(qty24Sum);
To set the text (value) of a textbox you have to use .val() not .text(). Like this:
$('.qty12').keyup(function() {
var qty12Sum = 0;
$('.qty12').each(function() {
if (this.value != "")
qty12Sum += parseInt(this.value);
});
$(".qty12lable").val(qty12Sum);
});
$('.qty24').keyup(function() {
var qty24Sum = 0;
$('.qty24').each(function() {
if (this.value != "")
qty24Sum += parseInt(this.value);
});
$(".qty24lable").val(qty24Sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Red
<br>12x12
<input class="qty12" value="" />
<br/>12x24
<input class="qty24" value="" />
<br>
<br>Blue
<br>12x12
<input class="qty12" value="" />
<br/>12x24
<input class="qty24" value="" />
<br>
<br>
<br>Total = <input class="qty12lable"/> x $.95
<br>Total = <input class="qty24lable"/> x $1.40
<br>
This snippet has some logic about how you can attach event listeners on input fields and how you can get their values. It's not perfect and has quite a few bugs from production level perspective but this will give a hint about how you can listen and manipulate DOM using Jquery. Which is what Jquery is all about.
$( "input" )
.change(function () {
var prevVal = ($('#total').html() !== '') ? $('#total').html() : 0;
if(parseInt($(this).val()) === NaN) {
return;
}
$('#total').html(parseInt($(this).val()) + parseInt(prevVal));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="1"></input><br>
<input type="text" id="2"></input><br>
<hr>
Total = <span id="total" class="qty12lable"></span> <br>

Dynamic form validation and disable submit button

My form is loaded with different input fields like radio button , text field ,numeric field which are generated dynamically while iterating through a list.
<c:forEach var="Item" items="${listBean.nameList}" varStatus="status">
<input type="number"name="nameList<c:outvalue='[${status.index}]'/>.initialWeight" onchange="checkOnChange(this,'<c:out value='${Item.personId}'/>','<c:out value='${Item.minWeight}'/>','<c:out value='${Item.maxWeight}'/>','<c:out value='[${status.index}]'/>')">
<br><br>
<input type="number" name="nameList<c:out value='[${status.index}]'/>.finalWeight" onchange="checkOnChange(this,'<c:out value='${Item.personId}'/>','<c:out value='${Item.minWeight}'/>','<c:out value='${Item.maxWeight}'/>','<c:out value='[${status.index}]'/>')">
<br><br>
<input type="text" class="formtext" name="nameList<c:out value='[${status.index}]'/>.Reason" id ="reason<c:out value='[${status.index}]'/>" value="" maxlength="255" >
<br><br>
<input type="submit" value="submit" id="submit" />
</c:forEach>
The numeric fields will be validated against minimum and maximum values.if any of the numeric fields fails in the validation , submit button needs to be disabled .
JSFIDDLE
Any ways to achieve this using jquery or javascript?
Thanks for your valuable time and suggestions
Give IDs to your inputs and then use jQuery's .change() function.
Example:
HTML
<input id="test" type="number"/>
<input id="test2" type="number"/>
<input id="submit" type="submit" value="Submit"/>
JS
var testVal = $('#test'),
testVal2 = $('#test2'),
submit = $('#submit'),
minVal = 22,
maxVal = 33;
testVal.change(function() {
if((testVal.val() > maxVal || testVal.val() < minVal) ||
(testVal2.val() > maxVal || testVal.val() < minVal)) {
submit.prop('disabled', true);
} else {
submit.prop('disabled', false);
}
});
jsfiddle
So, you could do something like below.
var flag = true;
if (nameVal > maxVal) {
alert(id + ' Enter the reason before proceeding');
//var reason = nameList[index].Reason;
document.getElementbyId("reason" + index).focus();
flag = false;
}
if (itemVal < minVal) {
alert(id + ' Enter the reason before proceeding');
//var reason = nameList[index].Reason;
document.getElementbyId("reason" + index).focus();
flag = false;
}
document.getElementById("submit").disabled = !flag;
return flag;

Why this function not work on IE 7 , 8?

How to apply for work on IE7 , 8
for test, fill 1 into input and then press button , input will change border to red and return false.
But ie7 8 not work all.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form onsubmit="return checkform(this);">
<div>
<p>
<label>
<input type="text" class="price" size="20" name="price[]">
</label>
</p>
</div>
<div>
<p>
<label>
<input type="text" class="price" size="20" name="price[]">
</label>
</p>
</div>
<div>
<p>
<label>
<input type="text" class="price" size="20" name="price[]">
</label>
</p>
</div>
<input type="submit" name="submit" value="OK">
</form>
<script language="JavaScript" type="text/javascript">
function checkform ( form )
{
var list = document.querySelectorAll(".price");
var z;
var input;
var isValid = true;
var value;
// Loop through the list
for (z = 0; z < list.length; ++z) {
console.log("z = " + z);
// Get this input
input = list[z];
// Check its value
if (input.value != "" && parseInt(input.value, 10) < 1.5) {
input.style.border = "1px solid red";
isValid = false;
}
else {
input.style.border = "1px solid #d5d5c5";
}
}
// Return result
return isValid;
}
</script>
querySelectorAll is an HTML5 DOM API, IE7, 8 are not ready for it.
See this page for more info.
Alternatively, since you are using jquery, you can use $(".price") instead.

Categories

Resources