Add slashes (' / ') in date field using javascript in php - javascript

I have this textbox:
<td width="10%"><input name="date" type="text" size=11 maxlength=10 /></td>
when typing date in the field it must add a forward slash in it like 09/02/2016

You can do the same functionality in PHP using JS OR jQuery.
Replace
<input name="date" type="text" size=11 maxlength=10 />
To
<!-- SET type="date" -->
<input type="date" name="date">
jQuery Code:-
//Put our input DOM element into a jQuery Object
var $jqDate = jQuery('input[name="date"]');
//Bind keyup/keydown to the input
$jqDate.bind('keyup','keydown', function(e){
//To accomdate for backspacing, we detect which key was pressed - if backspace, do nothing:
if(e.which !== 8) {
var numChars = $jqDate.val().length;
if(numChars === 2 || numChars === 5){
var thisVal = $jqDate.val();
thisVal += '/';
$jqDate.val(thisVal);
}
}
});
Hope it will help you :)

This one was very ticky! This is how I got it working, though it's not complete as you will need to check for when a number is deleted
<input type="hidden" id='counter' value='0'>
<input name="date" id='date' type="text" size=11 maxlength=10 onkeydown="doDate()"/>
<script>
function doDate(){
var dateSoFar = document.getElementById("date");
var counter = parseInt(document.getElementById("counter").value);
counter = counter+1;
document.getElementById("counter").value = counter;
if(counter == 3 || counter == 5 )
document.getElementById("date").value = document.getElementById("date").value + '/';
}
</script>

Try this,
<input name="date" id='date' type="text" size=11 maxlength=10 onkeydown="updateDate()"/>
<script>
function updateDate(){
var dateSoFar = document.getElementById("date");
var counter = dateSoFar.value.length;
if(counter == 2 || counter == 5 )
document.getElementById("date").value = document.getElementById("date").value + '/';
}
</script>

Related

Get number of characters selected from a text inside textarea or input text [duplicate]

I am working on a project that requires me to count the number of characters entered in a text box and dynamically display the result elsewhere on the page.
As I said, this would preferably be done in jQuery or Javascript.
Thanks in advance.
You could do this in jQuery (since you said you preferred it), assuming you want the character count displayed in a div with id="characters":
$('textarea').keyup(updateCount);
$('textarea').keydown(updateCount);
function updateCount() {
var cs = $(this).val().length;
$('#characters').text(cs);
}
UPDATE: jsFiddle (by Dreami)
UPDATE 2: Updating to include keydown for long presses.
This is my preference:
<textarea></textarea>
<span id="characters" style="color:#999;">400</span> <span style="color:#999;">left</span>
Then jquery block
$('textarea').keyup(updateCount);
$('textarea').keydown(updateCount);
function updateCount() {
var cs = [400- $(this).val().length];
$('#characters').text(cs);
}
<script type="text/javascript">
function countChars(countfrom,displayto) {
var len = document.getElementById(countfrom).value.length;
document.getElementById(displayto).innerHTML = len;
}
</script>
<textarea id="data" cols="40" rows="5"
onkeyup="countChars('data','charcount');" onkeydown="countChars('data','charcount');" onmouseout="countChars('data','charcount');"></textarea><br>
<span id="charcount">0</span> characters entered.
Plain Javascript.
I would like to share my answer which i used in my project and it is working fine.
<asp:TextBox ID="txtComments" runat="server" TextMode="MultiLine" Rows="4" Columns="50" placeholder="Maximum limit: 100 characters"></asp:TextBox><br />
<span id="spnCharLeft"></span>
<script type='text/javascript'>
$('#spnCharLeft').css('display', 'none');
var maxLimit = 100;
$(document).ready(function () {
$('#<%= txtComments.ClientID %>').keyup(function () {
var lengthCount = this.value.length;
if (lengthCount > maxLimit) {
this.value = this.value.substring(0, maxLimit);
var charactersLeft = maxLimit - lengthCount + 1;
}
else {
var charactersLeft = maxLimit - lengthCount;
}
$('#spnCharLeft').css('display', 'block');
$('#spnCharLeft').text(charactersLeft + ' Characters left');
});
});
</script>
Source: URL
Though it has been already solved, I'm interested to share something that I have used in one of my projects:
<textarea id="message" cols="300" rows="200" onkeyup="countChar(this)"
placeholder="Type your message ..." >
</textarea>
<input id="text-character" class="input-mini uneditable-input"
placeholder="0 Chars" readonly />
<input id="text-parts" class="input-mini uneditable-input"
placeholder="0 Parts" readonly />
<input id="text-remaining" class="input-medium uneditable-input"
placeholder="160 Chars Remaining" readonly />
Javascript code:
function countChar(val) {
var len = val.value.length;
var ctext = len + " Chars";
var str = val.value;
var parts = [];
var partSize = 160;
while (str) {
if (str.length < partSize) {
var rtext = (partSize - str.length) + " Chars Remaining";
parts.push(str);
break;
}
else {
parts.push(str.substr(0, partSize));
str = str.substr(partSize);
}
}
var ptext = parts.length + " Parts";
$('#text-character').val(ctext);
$('#text-parts').val(ptext);
$('#text-remaining').val(rtext);
}
<script Language="JavaScript">
<!--
function Length_TextField_Validator()
{
var len = form_name.text_name.value.length; //the length
return (true);
}
-->
</script>
<form name="form_name" method="get" action="http://www.codeave.com/html/get.asp"
onsubmit="return Length_TextField_Validator()">
<input type="text" name="text_name">
<input type="submit" value="Submit">
</form>
Source(s) : Text Validation

onchange event not accepting my javascript code

I have two text input for the user to type numbers, and I would like the page to output the total of these two numbers in another text input
<input id="attendance_1" onchange="parseInt(document.getElementById('attendance_output').value) += parseInt(this.value);" type="text" name="attendance_1" value="" />
<input id="attendance_2" onchange="parseInt(document.getElementById('attendance_output').value) += parseInt(this.value);" type="text" name="attendance_2" value="" />
// The results of adding the two text values should go here
<input id="attendance_output" type="text" value="" />
I get the error:
ReferenceError: invalid assignment left-hand side
I suggest putting the code of your onchange in a function and just calling that function onclick. It makes things way more easy to debug.
Example
function addValue(field) {
parseInt(document.getElementById('attendance_output').value) += parseInt(field.value);
}
<input id="attendance_1" onchange="addValue(this)" type="text" name="attendance_1" value="" />
<input id="attendance_2" onchange="parseInt(document.getElementById('attendance_output').value) += parseInt(this.value);" type="text" name="attendance_2" value="" />
// The results of adding the two text values should go here
<input id="attendance_output" type="text" value="" />
But the problem is, that your calculation is not assigned to anything. You take the field value, parse it and try to and a value to the parse result.
I guess you want to add that value to the field value and assign it?!
function addValue(field) {
var val = parseInt(document.getElementById('attendance_output').value);
val += parseInt(field.value);
document.getElementById('attendance_output').value = val;
}
Try below code. it should work.
your code is not working because += sign in expression.
<input id="attendance_1" onchange="document.getElementById('attendance_output').value=parseInt(document.getElementById('attendance_output').value) + parseInt(this.value);" type="text" name="attendance_1" value="" />
<input id="attendance_2" onchange="document.getElementById('attendance_output').value=parseInt(document.getElementById('attendance_output').value) + parseInt(this.value);" type="text" name="attendance_2" value="" />
// The results of adding the two text values should go here
<input id="attendance_output" type="text" value="" />
So this is really basic JS with typechecks
function addValue(field) {
parseInt(document.getElementById('attendance_output').value) += parseInt(field.value);
}
<input id="attendance_1" onchange="addValue(this)" type="text" name="attendance_1" value="" />
<input id="attendance_2" onchange="parseInt(document.getElementById('attendance_output').value) += parseInt(this.value);" type="text" name="attendance_2" value="" />
// The results of adding the two text values should go here
<input id="attendance_output" type="text" value="" />
But the problem is, that your calculation is not assigned to anything. You take the field value, parse it and try to and a value to the parse result.
I guess you want to add that value to the field value and assign it?!
function addValue(field) {
var oVal = parseInt(document.getElementById('attendance_output').value);
var iVal = parseInt(field.value);
if(!oVal || Number.isNaN(oVal)) {
oVal = 0;
}
if(!iVal || Number.isNaN(iVal)) {
iVal = 0;
}
oVal = oVal + iVal;
document.getElementById('attendance_output').value = oVal;
}
try this. :) it will not work properly if the user input string, so i think it should have validation.
function addValue() {
var num1 = document.getElementById('attendance_1').value;
var num2 = document.getElementById('attendance_2').value;
if (num1 === ''){
num1 = 0;
}
if(num2 === ''){
num2 = 0;
}
var sum = parseInt(num1) + parseInt(num2);
document.getElementById('attendance_output').value = sum;
}
you can make the textbox accept only numbers, by using jquery
$(document).ready(function() {
$("#attendance_1, #attendance_2").keydown(function (e) {
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
(e.keyCode == 65 && ( e.ctrlKey === true || e.metaKey === true ) ) ||
(e.keyCode >= 35 && e.keyCode <= 40)) {
return;
}
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
});
Use this code inside
onchange="document.getElementById('attendance_output').value=+document.getElementById('attendance_output').value+ +this.value"
Hope it will be useful for you :)
This may be an option. I removed the inline JS completely. Went from onchange to an oninput handler, which will only do the calculation if the values given are actually numbers not strings.
var inpt = document.querySelectorAll('.attendance');
var out = document.getElementById('attendance_output');
var onInput = function(e) {
if(/\d/.test(this.value)) {
var sum = [].slice.call(inpt).reduce(function(a, b) {
if (a.value.length && b.value.length) {
return +a.value + +b.value;
} else {
return +a.value || +b.value;
}
})
out.value = sum || this.value;
} else {
out.value = "";
}
}
inpt.forEach(function(el) {
el.addEventListener('input', onInput, false)
})
<input class="attendance" type="text" name="attendance_1" value="" /> <span>+</span>
<input class="attendance" type="text" name="attendance_2" value="" />
<br><br>
<input id="attendance_output" type="text" value="" disabled />

How To Make Make Auto Sum Calculation Input Field

Please take a look at this http://jsfiddle.net/F2wEK/4/:
HTML
cost 1 :<input type="text" class="cost" name="cost1" /><br />
cost 2 :<input type="text" class="cost" name="cost2" /><br />
cost 3 :<input type="text" class="cost" name="cost3" /><br />
cost 4 :<input type="text" class="cost" name="cost4" /><br /><br />
sum : <input type="text" id="sum" readonly />
Javascript
$(document).ready(function(){
$(".cost").each(
function(){
$(this).keyup(
function(){
calculateSum()
});
});
});
function calculateSum(){
var sum=0;
$(".cost").each(
function(){
var vl = this.value.replace(',','');
if(!isNaN(vl) && vl.length!=0){
sum+=parseFloat(vl);
}
});
$("#sum").val(sum.toFixed(2));
}
$(document).ready(function(){
$('input.cost').keyup(function(event){
// skip for arrow keys
if(event.which >= 37 && event.which <= 40){
event.preventDefault();
}
var $this = $(this);
var num = $this.val().replace(/,/gi, "").split("").reverse().join("");
var num2 = RemoveRougeChar(num.replace(/(.{3})/g,"$1,").split("").reverse().join(""));
console.log(num2);
// the following line has been simplified. Revision history contains original.
$this.val(num2);
});
});
function RemoveRougeChar(convertString){
if(convertString.substring(0,1) == ","){
return convertString.substring(1, convertString.length)
}
return convertString;
}
Why it can not be auto sum if i enter 100000, 1000000, 10000000, more bigger...? How to make it work with thousand, million or billion number? Please help me guys..
The Problem is your replace function, it only replaces the first ',' not all. In your calculateSum() function you do this:
var vl = this.value.replace(',', '');
I would propose to
var vl = this.value.split(',').join('');
instead. Or use a RegExp for the ',' like here:
var myExp = /,/g;
var vl = this.value.replace(myExp, '');
Try the fiddle it works fine for me.
Change your replace function. It replaces only first occurrence of comma:
var vl = this.value.replace(/,/g, '');

count total number of input where input attribute is pre defined

I am trying to make a function using jquery where i want to get the total number of input in a page with attibute value defined by me . For eg there are four input tags
<input type="hidden" class="code" barcode="567" total_quantity="3" name="product1" value="Nokia rita" class="product-10105">
<input type="hidden" class="code" barcode="567" total_quantity="3" name="product1" value="Nokia rita" class="product-10105">
<input type="hidden" class="code" barcode="567" total_quantity="3" name="product1" value="Nokia rita" class="product-10105">
<input type="hidden" class="code" barcode="200" total_quantity="3" name="product1" value="book" class="product-200">
In the above tags i want to pre define barcode number in a variable and the count the number of inputs accordingly and also get the value of total_quantity in a variable for that barcode number i provide. I made the following code to get the total inputs but its for all input and is not according to barcode i will specify .
var barcode_pd = $('input[barcode]').size();
var total_pd = $('input.code').attr("total_quantity");
var sumOfVals = 0;
$(".mn-no-cnt").each(function(){sumOfVals = sumOfVals + parseInt($(this).val(), 10);});
Using above code the ouput for count of input is 4 and i want to specify the barcode number too such as 567 so that the count could be 3 or if i use barcode number 200 then the count is 1.
I have used array to store values.
var code = [];
var count = [];
$("input.code").each(function(){
var c = $(this).attr("barcode");
if(code.indexOf(c) >= 0){
count[code.indexOf(c)] += 1;
}
else{
code.push(c);
count.push(1);
}
});
for(var i=0;i<code.length;i++){
$("body").append("<p>Barcode:"+code[i]+" Count:"+count[i]+"</p>");
}
DEMO here.
Without using jQuery:
function getCount(barcode){
var code = document.getElementsByClassName('code') ;
var length = code.length ;
var count = 0 ;
for(var i = 0 ; i < length ; i++){
if(code[i].attributes['barcode'].value == barcode) count++ ;
}
return count ;
}
// Test
alert(getCount(567)) ; // 3
alert(getCount(200)) ; // 1
Demo : http://jsfiddle.net/wz98E/
http://jsfiddle.net/A95Js/
function countBarcode(numberToFind){
var countInputs = 0;
$('input[barcode]').each(function(){
if($(this).attr("barcode") == numberToFind){
countInputs ++;
}
return countInputs;
});
}
$('#answer').html(countBarcode(567));
This is purely to count them - but combined with Hirals answer you should be able to work out how to turn his into a function. JSfiddle is above - obviously to make this useful you need to return the value not add it to a div - was just showing how to count it.
Try this. Set the barcode variable to the barcode you want to search for. I have also converted to data- attributes and have provided code to count and sum the data-total_quantity:
HTML:
<input type="hidden" class="code" data-barcode="567" data-total_quantity="3" name="product1" value="Nokia rita" id="product-10105">
<input type="hidden" class="code" data-barcode="567" data-total_quantity="3" name="product1" value="Nokia rita" id="product-10106">
<input type="hidden" class="code" data-barcode="567" data-total_quantity="3" name="product1" value="Nokia rita" id="product-10107">
<input type="hidden" class="code" data-barcode="200" data-total_quantity="3" name="product1" value="book" class="product-200">
Javascript:
$(function () {
var barcode = 567; // set to whatever you want to search for...
var sumOfVals = 0;
$("input.code[data-barcode='" + barcode + "']").each(function () {
sumOfVals += parseInt($(this).data('total_quantity'), 10);
});
alert("Length: " + $("input.code[data-barcode='" + barcode + "']").length);
alert("Sum: " + sumOfVals);
});
Fiddle:
http://jsfiddle.net/d89BR/4/
Try this :
var barcode = 123;
var $123 = $('input[data-barcode="' + barcode + '"]');
var howMany = $123.length;
var sumOfQuantities = Function('return ' + $123.map(function () {
return $(this).data('quantity');
}).get().join('+') + ';')();
var sumOfValues = Function('return ' + $123.map(function () {
return $(this).val() || '0';
}).get().join('+') + ';')();
HTML (example) :
<input data-barcode="123" data-quantity="123" value="123" />

Counting number of inputs filled

I have 4 inputs on a form and I want to do a calculation based on the number of inputs filled.
I have come up with this and it works in IE but not in FF. FF doesnt seem to like the multiple document.getElementById. Any help would be appreciated.
<script type="text/javascript" language="javascript">
function countlines(what) {
var headline = 1 ;
var oneline = 1 ;
var twoline = 1 ;
var webline = 1 ;
var valhead = document.getElementById('adverttexthead').value;
if (/^\s*$/g.test(valhead) || valhead.indexOf('\n') != -1)
{var headline = 0};
var valone = document.getElementById('adverttextone').value;
if (/^\s*$/g.test(valone) || valone.indexOf('\n') != -1)
{var oneline = 0};
var valtwo = document.getElementById('adverttexttwo').value;
if (/^\s*$/g.test(valtwo) || valtwo.indexOf('\n') != -1)
{var twoline = 0};
var valweb = document.getElementById('adverttextweb').value;
if (/^\s*$/g.test(valweb) || valweb.indexOf('\n') != -1)
{var webline = 0};
(document.getElementById('webcost').value = "$" + ((headline + oneline + twoline + webline) * 16.50).toFixed(2));
(document.getElementById('totallines').value = headline + oneline + twoline + webline);
}
</script>
HTML
<input name="adverttexthead" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
<br>
<input name="adverttextone" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
<br>
<input name="adverttexttwo" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
<br>
<input name="adverttextweb" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
<input name="totallines" id="totallines" size="4" readonly="readonly" type="text">
<input name="webcost" id="webcost" size="6" readonly="readonly" type="text">
You could put the inputs in a form and do like so:
function countFormElements(formNumber){
var fn = !formNumber ? 0 : formNumber;
var frm = document.getElementsByTagName('form')[fn], n = 0;
for(var i=0,l=frm.length; i<l; i++){
if(frm.elements[i].value !== '')n++;
}
return n;
}
console.log(countFormElements());
You did not set the 'id' attribute on some elements
You reinitialized your variables in the 'if' clauses.
Working code:
<input id="adverttexthead" name="adverttexthead" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
<br>
<input id="adverttextone" name="adverttextone" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
<br>
<input id="adverttexttwo" name="adverttexttwo" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
<br>
<input id="adverttextweb" name="adverttextweb" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
<input id="totallines" name="totallines" size="4" readonly="readonly" type="text">
<input id="webcost" name="webcost" size="6" readonly="readonly" type="text">
function countlines(what) {
var headline = 1;
var oneline = 1;
var twoline = 1;
var webline = 1;
var valhead = document.getElementById('adverttexthead').value;
if (/^\s*$/g.test(valhead) || valhead.indexOf('\n') != -1) {
headline = 0
};
var valone = document.getElementById('adverttextone').value;
if (/^\s*$/g.test(valone) || valone.indexOf('\n') != -1) {
oneline = 0
};
var valtwo = document.getElementById('adverttexttwo').value;
if (/^\s*$/g.test(valtwo) || valtwo.indexOf('\n') != -1) {
twoline = 0
};
var valweb = document.getElementById('adverttextweb').value;
if (/^\s*$/g.test(valweb) || valweb.indexOf('\n') != -1) {
webline = 0
};
(document.getElementById('webcost').value = "$" + ((headline + oneline + twoline + webline) * 16.50).toFixed(2));
(document.getElementById('totallines').value = headline + oneline + twoline + webline);
}
Here is a working jsFiddle: http://jsfiddle.net/YC6J7/1/
You'll need to set the id attribute for the inputs as well as the name, otherwise getElementById works inconsistently cross browser.
For instance:
<input id="adverttexthead" name="adverttexthead" size="46" TYPE="text" onblur="countlines(this)" onkeypress="countlines(this)">
(Technically name is optional for purposes of document.getElementById, since id is accepted pretty universally, but you'll probably want to keep it so your forms submit correctly.)
For more details, see: Document.getElementById() returns element with name equal to id specified

Categories