Hide <p> element if innerHTML is "0" or empty - javascript

I am trying to make a simple calculator but I am stuck; I need to hide some elements. My code is shown with comments below.
function ekogroszek() {
var p = document.getElementById("powierzchnia").value;
var w = document.getElementById("wysokosc").value;
var k = p * w;
var e = 7.8;
var s = k * e;
document.getElementById("wynik").innerHTML = s;
}
$('#wysokosc').keypress(function(event) {
if (((event.which != 46 || (event.which == 46 && $(this).val() == '')) ||
$(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
}).on('paste', function(event) {
event.preventDefault();
});
$('#powierzchnia').keypress(function(event) {
if (((event.which != 46 || (event.which == 46 && $(this).val() == '')) ||
$(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
}).on('paste', function(event) {
event.preventDefault();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<span>First field</span>
<input class="polekalkulacji" type="text" id="powierzchnia" name="powierzchnia" placeholder="np. 120">
</div>
<div>
<span>Second</span>
<input class="polekalkulacji" type="text" id="wysokosc" name="wysokosc" placeholder="np. 2.8">
</div>
<button onclick="ekogroszek()">Calculate</button>
<!--- Show below elements only if number (p id=wynik) is bigger than: "0" and field is filled --->
<p id="zapotrzebowanie">Result is:</p>
<p type="text" id="wynik"></p>
So as you can see I need to show these two "p" elements only if id=wynik is filled and bigger than 0. How would I go about doing this?

If your goal is to keep them hidden until anything is written on them, and also the value on it is greater than 0, then the best way to achieve it is by hidding them on default with:
<p id="zapotrzebowanie" style="display: none;">Result is:</p>
<p type="text" id="wynik" style="display:none;"></p>
And when you are writting HTML to them, show them with jQuery:
function ekogroszek() {
var p = $("#powierzchnia").val();
var w = $("#wysokosc").val();
var k = p * w;
var e = 7.8;
var s = k * e;
document.getElementById("wynik").innerHTML = Math.trunc(s);
if(s>0){
$("#zapotrzebowanie").show();
$("#wynik").show();
}
}
You can check a working version of your code in this fiddle:
https://jsfiddle.net/0arcxze4/2/

Why not simply check to the value:
if($(this).val() == '0' || $(this).val() == '' ) {
$('#wynik').hide();
}
You may show with jquery and at initial phase hide the html element with css. But I see you're showing them after calculating? Then, that's just fine.
But if you want the harder way then it is:
$('#wynik').css('display', function(i, v) {
return ($(this).text() == '0' || $(this).text() == '') ? 'none' : 'block'
});

Related

Allow 2 digit number after the decimal

Hi i am trying to restrict user to input 2 digit number after the decimal.The below functionality is working but i am not able to modify the last two digit.suppose I have entered number 3456.78 and i want to modify 3456.68 it is not allowing.
$('.PMT_AMT').keypress(function(event) {
var $this = $(this);
if ((event.which != 46 || $this.val().indexOf('.') != -1) &&
((event.which < 48 || event.which > 57) &&
(event.which != 0 && event.which != 8))) {
event.preventDefault();
}
var text = $(this).val();
if ((event.which == 46) && (text.indexOf('.') == -1)) {
setTimeout(function() {
if ($this.val().substring($this.val().indexOf('.')).length > 3) {
$this.val($this.val().substring(0, $this.val().indexOf('.') + 3));
}
}, 1);
}
if ((text.indexOf('.') != -1) &&
(text.substring(text.indexOf('.')).length > 2) &&
(event.which != 0 && event.which != 8) &&
($(this)[0].selectionStart >= text.length - 2)) {
event.preventDefault();
}
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<input type="text" class="PMT_AMT">
Here's one possibility that uses a regular expression. Save the old input value on keypress, and if the new value on keyup does not validate, reset to that old value.
You need to validate on keypress as well, because otherwise, if the user types very fast, an invalid value can be saved:
const re = /^\d+(\.\d{0,2})?$/;
let oldVal;
$('.PMT_AMT').keypress(function(event) {
const { value } = this;
if (re.test(value)) oldVal = value;
});
$('.PMT_AMT').keyup(function(event) {
const newVal = this.value;
if (!re.test(newVal)) this.value = oldVal;
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<input type="text" class="PMT_AMT">
This solution creates a prediction and tests the regular expression against that instead.
$('.PMT_AMT').keypress(function(event) {
if(!/^\d*(\.\d{0,2})?$/.test(
this.value.slice(0, this.selectionStart)
+ String.fromCharCode(event.which)
+ this.value.slice(this.selectionEnd)
)) event.preventDefault();
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<input type="text" class="PMT_AMT">
Why use jQuery and not just browser functionality?
<input type="number" step="0.01">
On submit the browser will check if the submitted value of the input field has maximum two decimals.

How to restrict zero at second position

In the below code the text box is restricting zero at starting position. But I want to allow only one zero at first position but not more than one. here is the example
Eg:- 0.1012400==> correct
000.4545000==>not correct
0154==> correct
00154 ==> not correct
$('input#abc').keypress(function(e){
if (this.selectionStart == 0 && (e.which == 48 || e.which == 46 )){
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="abc">
You can simply test if there is 2 consecutive zero at the start and if yes you remove one:
$('input#abc').on('keypress keydown keyup',function(e){
var v = $(this).val();
if(v.length >=2 && v[0]=='0' && v[1]=='0') {
$(this).val(v.substring(1));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="abc">
UPDATE
Here is a code if you want to consider the minus sign at the start:
$('input#abc').on('keypress keydown keyup', function(e) {
var v = $(this).val();
if (v.length >= 2 && v[0] == '0' && v[1] == '0') {
$(this).val(v.substring(1));
} else if (v.length >= 3 && v[0] == '-' && v[1] == '0' && v[2] == '0') {
$(this).val('-' + v.substring(2));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="abc">
You could check the final string like
$('input#abc').on('change', function () {
console.log(this.value.indexOf('00') === 0);
});

Auto complete is not working properly asp.net Jquery

I have write jquery code for Auto complete on text-box with onkeypress event it is working proper while text-box is empty but when i use ctrl+a or shift+tab and type to search some thing it is appending old data which resulting wrong search
e.g.
if i search "1" in text box it showing list of all records with 1
but suppose i had pressed ctrl+a or shift+tab and enter "2" it is showing list of "12" instead of "2"
<asp:TextBox ID="txtDrg" onkeypress="SearchText('DRG',this,event);" runat="server" ></asp:TextBox>
function SearchText(searchType, searchKey, event) {
if (searchType != '' && searchKey != '') {
var x = event.which || event.keyCode;
var searchKeyWord = '';
if (searchType == 'DRG') {
if (x == 8 || x == 46) {
if (searchKey.value.length > 0) {
searchKeyWord = searchKey.value.toString().slice(0, -1);
}
}
else {
if (x == 110 || x == 190)
searchKeyWord = '.';
else
searchKeyWord = String.fromCharCode(x);
if (searchKey.value != '' || searchKey.value != undefined)
searchKeyWord = searchKey.value + searchKeyWord;
}
if (valiadte)
GetAutoData(searchType, searchKeyWord);
}
}
}
function GetAutoData() {
//code
}

Strange .replace() behaviour in Chrome browser

<div>
<input type="text" class="allownumericwithdecimal"/>saadad
</div>
$(".allownumericwithdecimal").live("keypress keyup ", function (event) {
$(this).val($(this).val().replace(/[^0-9\.]/g, ''));
var text = $(this).val();
if (!((event.which >= 48 && event.which <= 57) || event.which == 8 || event.which == 46 || event.which == 110 || event.which == 0)) {
var text = $(this).val();
if ((text.indexOf('.') != -1) && (text.substring(text.indexOf('.'), text.indexOf('.').length).length > 2)) {
//event.preventDefault();
}
}
var text = $(this).val();
if ((event.which >= 48 && event.which <= 57) && (text.indexOf('.') != -1)) {
if ((text.substring(text.indexOf('.'), text.indexOf('.').length).length) > 2) {
//event.preventDefault();
}
if (event.which == 190) {
//event.preventDefault();
}
}
if (text.indexOf('.') != -1 && event.which == 190) {
if (text.match("^[0-9]+(\.[0-9]{0,2})?$")) {} else {
$(this).val('');
}
}
if (text.indexOf('.') == -1 && text.length > 7 && (event.which != 190 && event.which != 8 && event.which != 46 && event.which != 110 && event.which != 0)) {
event.preventDefault();
}
});
http://jsfiddle.net/Lx9h2smh/
The problem is If I type a value in textBox say 3434 and now I want to make it 35434 by putting cursor after 3 and pressing 5, it works fine in Firefox and IE but in chrome the 5 get added after value and it becomes 34345.
The culprit line is one which replace non numeric characters.
How to handle this issue??
Try this code, it runs. jsFiddle
I just do a test
if ( /[^0-9\.]/g.test($(this).val()) ) {
$(this).val($(this).val().replace(/[^0-9\.]/g,''));
}
Explain
You just make sure that the user enter the value of what you want. You replace if the entered value is not an integer. Your regex mean: "Those which are not integer or dot (.), replace them with an empty value". That why You need to make this test. Therefore, if the user enters the value you want, it doesn't do the action replace and it doesn't pass to the test.
$(".allownumericwithdecimal").live("keypress keyup ",function (event) {
var caretP= $(this).getCursorPosition();
$(this).val($(this).val().replace(/[^0-9\.]/g,''));
var text = $(this).val();
if (!((event.which >= 48 && event.which <= 57) || event.which ==8 || event.which ==46 || event.which ==110 || event.which ==0) )
{
var text = $(this).val();
if ((text.indexOf('.') != -1) && (text.substring(text.indexOf('.'), text.indexOf('.').length).length > 2)) {
//event.preventDefault();
}
}
var text = $(this).val();
if((event.which >= 48 && event.which <= 57) && (text.indexOf('.') != -1))
{
if((text.substring(text.indexOf('.'), text.indexOf('.').length).length)>2)
{
//event.preventDefault();
}
if(event.which==190)
{
//event.preventDefault();
}
}
if(text.indexOf('.') != -1 && event.which==190 )
{
if(text.match("^[0-9]+(\.[0-9]{0,2})?$")){
}
else{
$(this).val('') ;
}
}
if(text.indexOf('.') == -1 && text.length>7 && (event.which!=190 && event.which !=8 && event.which !=46 && event.which !=110 && event.which !=0)){
event.preventDefault();
}
$(this).selectRange(caretP,caretP);
});
(function($) {
$.fn.selectRange = function(start, end) {
return this.each(function() {
if (this.setSelectionRange) {
this.focus();
this.setSelectionRange(start, end);
} else if (this.createTextRange) {
var range = this.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', start);
range.select();
}
});
};
$.fn.getCursorPosition = function() {
var input = this.get(0);
if (!input) return; // No (input) element found
if (document.selection) {
// IE
input.focus();
}
return 'selectionStart' in input ? input.selectionStart:'' || Math.abs(document.selection.createRange().moveStart('character', -input.value.length));
}
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<div>
<input type="text" class="allownumericwithdecimal"/>saadad
</div>
kepress seems to be the culprit when I changed the fiddle to just use keyup the replacement happened correctly (though the cursor shifted to the end)
http://jsfiddle.net/Lx9h2smh/1/
Just remove the 'keypress' event keypress event is very similar to the keydown event. If you press a button keypress event cannot identify the character. In your code it takes as current input Empty so it replace the character.

Key Press Event In Jquery

I have many input types in the form .Now i want that the user can enter only integer values in the input types.The input can be like this 110.00 only two values after ..But i am not able to get this features.
I have done with the interger input but i am not getting how can we do this :
Code
$(".amount_class").live("keypress",function(e){
var charCode = (e.which) ? e.which : e.keyCode;
var Enteted = String.fromCharCode(e.which).toLowerCase();
if ((charCode >= 48 && charCode <= 57) || charCode == 8 || charCode == 9 || charCode == 37 || charCode == 39 || (charCode == 46 && Enteted != '.'))
return true;
else
return false;
});
The values are amount and it can be decimal but not more than two after decimal sign.Please help me
I have done this and working fine for me :
$('.salary').live("keypress",function(e) {
var charCode = (e.which) ? e.which : e.keyCode;
var Enteted = String.fromCharCode(e.which).toLowerCase();
if(!((charCode >= 48 && charCode <= 57) || charCode == 8 || charCode == 9 || (charCode == 37 && Enteted !='%') || charCode == 39 || charCode == 46)) {
e.preventDefault();
}
if(charCode == 46 && $(this).val().indexOf('.') != -1 && Enteted ==".") {
e.preventDefault();
} // prevent if already dot
if(charCode == 46 && Enteted =="." && !$(this).val()) {
e.preventDefault();
}
if($(this).val().indexOf('.')!=-1){
if($(this).val().split(".")[1].length >= 2){
if(charCode != 8 && charCode != 46) e.preventDefault();
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixed(2);
}
}
return this;
});
Use as below
HTML
<input type="text" id="checkDecimal" class="decimal" />
JS
$(function () {
$('#checkDecimal').bind('paste', function () {
var self = this;
setTimeout(function () {
if (!/^\d*(\.\d{1,2})+$/.test($(self).val())) $(self).val('');
}, 0);
});
$('#checkDecimal').keypress(function (e) {
var character = String.fromCharCode(e.keyCode)
var newValue = this.value + character;
if (isNaN(newValue) || parseFloat(newValue) * 100 % 1 > 0) {
e.preventDefault();
return false;
}
});
});
have a look here.
Regex - /^\d+(\.\d{0,2})?$/g;
i have experimented here
<!DOCTYPE html>
<html>
<head>
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$('#input_field').keyup(function(e) {
var regex = /^\d+(\.\d{0,2})?$/g;
if (!regex.test(this.value)) {
this.value = '';
}
});
});
</script>
</head>
<body>
<input type= "text" id = "input_field" name ="input_field" value=""/>
</body>
</html>
The logic is every time a user entering a number you have to check two things.
Has the user entered decimal point?
Are the decimal places more than two?
For the first one you can use $(this).val().indexOf('.') != -1For the second one you can use $(this).val().substring($(this).val().indexOf('.'), $(this).val().indexOf('.').length).length > 2
Here is the code:
$('.amount_class').keypress(function (event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
var text = $(this).val();
if ((text.indexOf('.') != -1) && (text.substring(text.indexOf('.')).length > 2)) {
event.preventDefault();
}
});
And the DEMO
Simply use
value.toFixed(2);
thats it..

Categories

Resources