i just modified simple dinamically onChange code and added some input text below select option. theres 3 input text under it, soon after finished some modification im try it running. then why 3rd input text unchanged on first hit, it work only on next hit.
let say we pick a date : 17/08/1945 (datepicker inputtext)
1rst inputfield show only name of day :Friday
2nd inputfield returning value month : August
3rd inputfield date written in words : seventeen august one thousand nine hundred and forty-five
i know that doesn't sound like a very useful way to display a date in english, but here in Indonesia, writing the date in a word usually used for credit agreements or agreements handover and required by law
I'm making a small application and on a menu provides a feature to print a letter of agreement, automatically. that's why I need a date written in words.snippet and jsfiddle been replaced using the international language.
$( function() {
$( "#pickyDate" ).datepicker({format: "dd/mm/yyyy"});
daylocal = ['Minggu', 'Senin', 'Selasa', 'Rabu', 'Kamis', 'Jumat', 'Sabtu' ];
monthlocal = ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni','Juli','Agustus','September','Oktober','November','Desember' ];
$('#pickyDate').datepicker()
.on("change", function () {
var today = new Date($('#pickyDate').datepicker('getDate'));
var date = today.getDate();
var daysnumber = today.getDay();
var monthnumber = today.getMonth();
var years = today.getFullYear();
numbers = $('#dateinword').val();
var number = new Array('0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0');
var words = new Array('','Satu','Dua','Tiga','Empat','Lima','Enam','Tujuh','Delapan','Sembilan');/*1 to 9 */
var level = new Array('','Ribu','Juta','Milyar','Triliun'); /*hundred,thousand,billion,trillion */
var length_numbers = numbers.length;
/* long test numbers */
if (length_numbers > 15) {
sentences = "Out of Limit";
return sentences;
}
/* get numbers set to array */
for (i = 1; i <= length_numbers; i++) {
number[i] = numbers.substr(-(i),1);
}
i = 1;
j = 0;
sentences = "";
/* iteration array number */
while (i <= length_numbers) {
subsentences = "";
words1 = "";
words2 = "";
words3 = "";
/* hundred */
if (number[i+2] != "0") {
if (number[i+2] == "1") {
words1 = "Seratus"; /*Seratus mean One hundred */
} else {
words1 = words[number[i+2]] + " Ratus"; /* Ratus mean hundred */
}
}
/* tens or dozen */
if (number[i+1] != "0") {
if (number[i+1] == "1") {
if (number[i] == "0") {
words2 = "Sepuluh"; /* sepuluh mean ten */
} else if (number[i] == "1") {
words2 = "Sebelas"; /* sebelas mean eleven */
} else {
words2 = words[number[i]] + " Belas"; /* >10 - 19 using suffix Belas */
}
} else {
words2 = words[number[i+1]] + " Puluh"; /* puluh is suffix like ty in english [20,30,40,...90] */
}
}
/* single number */
if (number[i] != "0") {
if (number[i+1] != "1") {
words3 = words[number[i]];
}
}
/* zero cheking, add level */
if ((number[i] != "0") || (number[i+1] != "0") || (number[i+2] != "0")) {
subsentences = words1+" "+words2+" "+words3+" "+level[j]+" ";
}
/* join var sentences (as one blok 3 digit 000) into var sentences */
sentences = subsentences + sentences;
i = i + 3;
j = j + 1;
}
/* replace Satu Ribu(one thousand) will be Seribu if needed */
if ((number[5] == "0") && (number[6] == "0")) {
sentences = sentences.replace("Satu Ribu","Seribu"); /* Ribu = thousand we use prefix se for one */
}
//return sentences;
//alert(local[today.getDay()]);
//alert(kalimat);
$('#daypk').val(daylocal[today.getDay()]);
$('#dateinword').val(date);
$('#worddate').val(sentences);
//document.getElementById("terbilang").innerHTML=kalimat;
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<div class="row">
<div class="col-lg-12">
<div class="col-lg-3">
<div class="form-group">
<input type="text" class="form-control" placeholder="specify the date of the loan agreement" name="pickyDate" id="pickyDate" />
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="name of the day" name="daypk" id="daypk" disabled/>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="dateinword" name="dateinword" id="dateinword" disabled/>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="will be dd/mm/yy in word" name="worddate" id="worddate" disabled/>
</div>
</div>
</div>
</div>
https://jsfiddle.net/ariowishnu/vLeqLkj6/1/
Unfortunately I can say that I don't speak Indonesian, and so it's difficult to tell what exactly your code intends to do and why your logic might be structured the way it is. However, I might be able to give you a few pointers based on my testing of your code that might change the results for the first change event:
You set some variable bilangan = $('#nominal').val() towards the beginning of your event handler. This will always be the empty string '' on the first iteration, because nothing has been inputted into that field yet.
You base your while loop off of a variable panjang_bilangan = bilangan.length. That loop will never run the first time, because bilangan is the empty string and thus has a length of zero.
Your third input (the one that is having the error) seems to be updated entirely based off of a variable called kaLimat. From what I can tell, the only places where this variable is updated to include some meaningful value are inside your while loop, and that is why for the first event kaLimat ends up being empty, and your <input id="terbilang"> doesn't change.
Edit: I think I found a solution
The problem was with numbers = $('#dateinwords').val(). That line should be:
var numbers = date + ''
...which sets numbers to the string-equivalent of the selected day of the month ("date").
I also prefixed a few of your variables with var when you set them initially so that they don't leak into the global namespace.
I did not take a look at the correctness of your algorithm to turn dates into strings, since I don't fully understand the rules by which that should be done in Indonesian. Let me know if the snippet doesn't function as intended.
Snippet:
$(function() {
daylocal = ['Minggu', 'Senin', 'Selasa', 'Rabu', 'Kamis', 'Jumat', 'Sabtu'];
monthlocal = ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
$('#pickyDate').datepicker({ format: 'dd/mm/yyyy' })
.on("change", function() {
var today = new Date($('#pickyDate').datepicker('getDate'));
var date = today.getDate();
var daysnumber = today.getDay();
var monthnumber = today.getMonth();
var years = today.getFullYear();
var numbers = date + ''
var number = ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0'];
var words = new Array('', 'Satu', 'Dua', 'Tiga', 'Empat', 'Lima', 'Enam', 'Tujuh', 'Delapan', 'Sembilan'); /*1 to 9 */
var level = new Array('', 'Ribu', 'Juta', 'Milyar', 'Triliun'); /*hundred,thousand,billion,trillion */
var length_numbers = numbers.length;
/* long test numbers */
if (length_numbers > 15) {
var sentences = "Out of Limit";
return sentences;
}
/* get numbers set to array */
for (i = 1; i <= length_numbers; i++) {
number[i] = numbers.substr(-(i), 1);
}
i = 1;
j = 0;
sentences = "";
/* iteration array number */
while (i <= length_numbers) {
var subsentences = "";
words1 = "";
words2 = "";
words3 = "";
/* hundred */
if (number[i + 2] != "0") {
if (number[i + 2] == "1") {
words1 = "Seratus"; /*Seratus mean One hundred */
} else {
words1 = words[number[i + 2]] + " Ratus"; /* Ratus mean hundred */
}
}
/* tens or dozen */
if (number[i + 1] != "0") {
if (number[i + 1] == "1") {
if (number[i] == "0") {
words2 = "Sepuluh"; /* sepuluh mean ten */
} else if (number[i] == "1") {
words2 = "Sebelas"; /* sebelas mean eleven */
} else {
words2 = words[number[i]] + " Belas"; /* >10 - 19 using suffix Belas */
}
} else {
words2 = words[number[i + 1]] + " Puluh"; /* puluh is suffix like ty in english [20,30,40,...90] */
}
}
/* single number */
if (number[i] != "0") {
if (number[i + 1] != "1") {
words3 = words[number[i]];
}
}
/* zero cheking, add level */
if ((number[i] != "0") || (number[i + 1] != "0") || (number[i + 2] != "0")) {
subsentences = words1 + " " + words2 + " " + words3 + " " + level[j] + " ";
}
/* join var sentences (as one blok 3 digit 000) into var sentences */
sentences = subsentences + sentences;
i = i + 3;
j = j + 1;
}
/* replace Satu Ribu(one thousand) will be Seribu if needed */
if ((number[5] == "0") && (number[6] == "0")) {
sentences = sentences.replace("Satu Ribu", "Seribu"); /* Ribu = thousand we use prefix se for one */
}
//return sentences;
//alert(local[today.getDay()]);
//alert(kalimat);
$('#daypk').val(daylocal[today.getDay()]);
$('#dateinword').val(date);
$('#worddate').val(sentences);
//document.getElementById("terbilang").innerHTML=kalimat;
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<div class="row">
<div class="col-lg-12">
<div class="col-lg-3">
<div class="form-group">
<input type="text" class="form-control" placeholder="specify the date of the loan agreement" name="pickyDate" id="pickyDate" />
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="name of the day" name="daypk" id="daypk" disabled/>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="dateinword" name="dateinword" id="dateinword" disabled/>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="will be dd/mm/yy in word" name="worddate" id="worddate" disabled/>
</div>
</div>
</div>
</div>
Related
I have no JS or other language background. I have learned everything in the code for this particular problem so bear with me if things aren't clean and clever. I have done a lot of searching before resulting to asking here, so hopefully ALMOST everything is accounted for.
I have a conditional statement I just CANNOT get to run correctly. (entire code for context at the bottom)
if (pyramid < 1 || pyramid > 8) {
var dennis = document.getElementById("dennis");
var showdennis = "#ahahah{display: block}";
dennis.appendChild(document.createTextNode(showdennis));
document.getElementById("giza").innerHTML = "";
return;
}
I am most concerned with (pyramid < 1 || pyramid > 8) but if you can help me account for an input value of zero (due to complexities with 0 being false-y), bonus points.
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<style id="dennis">
#ahahah {
display: none;
}
</style>
</head>
<body>
<h1>Text Box Input and Output</h1>
<form action="">
<fieldset>
<label>write how tall </label>
<input type="number" id="numberin" min="" max="" step="1" />
<input type="button" value="Make the Pyramid" onclick="makepyramid()" />
</fieldset>
</form>
<script type="text/javascript">
function makepyramid() {
var numberin = document.getElementById("numberin");
var pyramid = numberin.value;
var spaceincrement = numberin.value;
var octoincrement = numberin.value;
var spaces;
var octothorps;
var bringittogether = "";
//WHY YOU NO WORK?! I'd like to make 0 work as well but I am more concerned with the range first.
//first if statement is the ideal, second is bare minimum.
//if (pyramid === null || pyramid < 1 || pyramid > 8) {
//if (pyramid < 1 || pyramid > 8) {
//Put in this if statement to show what SHOULD happen
if (pyramid > 8) {
var dennis = document.getElementById("dennis");
var showdennis = "#ahahah{display: block}";
dennis.appendChild(document.createTextNode(showdennis));
document.getElementById("giza").innerHTML = "";
return;
} else {
document.getElementById("ahahah").innerHTML = "";
//decide how many lines to make
for (var a = 0; a < pyramid; a++) {
//number of spaces loop
for (var b = 1, spaces = ""; b < spaceincrement; b++) {
spaces += "_";
}
//number of octothorps in one line loop
for (var c = pyramid, octothorps = ""; c >= octoincrement; c--) {
octothorps += "#";
}
//print spaces, hashes, 2 spaces, start new line
bringittogether += spaces + octothorps + "__" + octothorps + "<br/>";
document.getElementById("giza").innerHTML = bringittogether;
//increment to change next line's number of spaces (one less) and octothorps (one more)
spaceincrement = [spaceincrement - 1];
octoincrement = [octoincrement - 1];
}
}
}
</script>
<hr />
<div id="giza"></div>
<div id="ahahah">
<p><img src="https://i.imgur.com/1A8Zgnh.gif" /> You must select a number between 1 and 8
</p>
</div>
</body>
</html>
I am looking for a way to search for all results that fall between two dates. I have a simple html page with a text input that serves as a search and currently one date input. As is, it searches for all results that match the text on the given date, if no text is input, then it searches just for the date and vice versa. I can't figure out how to filter it between two dates in the same way. I've tried to get the values and use .filter for all results between those two dates, which works, however the results are not returned in a range array, but instead an array of values (strings). My code gets the row of each result and arrays other values from that row together. Therefore, I believe my result needs to be a range not a value.
current code.gs
function getValuesFromSS(search) {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('FormResponse');
var lastRow = ss.getLastRow();
var ranges = [];
if ("name" in search && search.name != "") {
var ranges = ss.getRange(2, 4, lastRow - 1, 2).createTextFinder(search.name).findAll();
if (ranges == "") {
ranges = ss.getRange(2, 8, lastRow - 1, 1).createTextFinder(search.name).findAll();
if (ranges == "") {
ranges = ss.getRange(2, 50, lastRow - 1, 1).createTextFinder(search.name).findAll();
}
}
}
if ("date" in search && search.date != "") {
var dateRanges = ss.getRange(2, 6, lastRow - 1, 1).createTextFinder(search.date).findAll();
if (ranges.length > 0) {
ranges = ranges.filter(function(r1) {return dateRanges.some(function(r2) {return r1.getRow() == r2.getRow()})});
}
else if (search.name == null) {
ranges = dateRanges;
}
}
I've tried this:
function filterTest(startdate, enddate) {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('FormResponse');
var lastRow = ss.getLastRow();
var dates = ss.getRange(2, 6, lastRow - 1, 1).getDisplayValues();
dates= dates.filter(function(date) {
if (date >= startdate && date <= enddate){
return true;
}
});
return dates;
Logger.log(dates);
}
Which returns an array of values, but does not let me get row numbers of the results. Here is the rest of my code, if anyone cares:
var issues = '<td style="font-weight:bold;border-bottom:2px solid black;text-align:center">Issues</td>';
var names = '<td style="font-weight:bold;border-bottom:2px solid black;text-align:center">Name</td>';
var nums = '<td style="font-weight:bold;border-bottom:2px solid black;text-align:center">Emp#</td>';
var dates = '<td style="font-weight:bold;border-bottom:2px solid black;text-align:center">Date</td>';
var tnums = '<td style="font-weight:bold;border-bottom:2px solid black;text-align:center">Truck</td>';
var trnums = '<td style="font-weight:bold;border-bottom:2px solid black;text-align:center">Trailer</td>';
var urls = '<td style="font-weight:bold;border-bottom:2px solid black;text-align:center">Link</td>';
//loop through each range
for (i = 0; i < ranges.length; i++) {
var row = ranges[i].getRow();
var lastCol = ss.getLastColumn();
var values = ss.getRange(row, 1, 1, lastCol).getDisplayValues(); //get all values for the row
var empname = values[0][3].replace(/["']/g, ""); //column C
var empnum = values[0][4].replace(/["']/g, ""); //column D
var date = values[0][5]; //column E
var tnum = values[0][7].replace(/["']/g, "");
var trnum = values[0][49].replace(/["']/g, "");
var url = values[0][66];
var tkissue = values[0][48].replace(/["']/g, "");
var trissue = values[0][63].replace(/["']/g, "");
var mechveri = values[0][67];
var issue = '';
if (trissue !== "" || tkissue !==""){
if (trissue !== "" && tkissue !== ""){
issue = "<b>Truck:</b> <br>" + tkissue + "<br><br><b>Trailer:</b> <br>" + trissue}
else if (tkissue !== "") {
issue = "<b>Truck:</b> <br>" + tkissue}
else if (trissue !== "") {
issue = "<b>Trailer:</b> <br>" + trissue}
if (mechveri == "") {
issue += "<br><br><b>Status:</b><br> This issue has not been resolved yet. Please see a mechanic for further information."}
else if (mechveri !== "") {
issue += "<br><br><b>Status:</b><br> This issue has been resolved. Please see the DVIR for further information."}
}
if (trnum == "") {trnum = "N/A"};
if (issue !== "") {
issues+=Utilities.formatString("<td><input type='button' value='VIEW' class='issbtn' onclick='alert2(\"" + issue + "\",\"Known Issues:\")'></button></td>");
}
else if (issue == "") {
issues+=Utilities.formatString("<td>None</td>");
}
names+=Utilities.formatString("<td>" + empname + "</td>");
nums+=Utilities.formatString("<td>" + empnum + "</td>");
dates+=Utilities.formatString("<td>" + date + "</td>");
tnums+=Utilities.formatString("<td>" + tnum + "</td>");
trnums+=Utilities.formatString("<td>" + trnum + "</td>");
urls+=Utilities.formatString("<td><a class='button' href='https://drive.google.com/uc?export=view&id=" + url + "' target='_blank'>DVIR</a></td>");
}
return {
nth: issues,
first: names,
second: nums,
third: dates,
fourth: tnums,
fifth: trnums,
sixth: urls
}
}
Basically, it's just setting table information for my html page so I can call it up.
I've also tried regex, but I am not as skilled with it.
Once again, I'm trying convert this to return all results between two dates as input from my html page. Any help is welcome. Thank you!
Searching for a String contained in row with first column date between from and to dates
String in the cell must be an exact match. It doesn't search from substrings. In fact all of my testing just involved numbers.
Code.gs:
function lauchSearchDialog() {
var userInterface=HtmlService.createHtmlOutputFromFile('aq5').setWidth(1000);
SpreadsheetApp.getUi().showModelessDialog(userInterface, "Search");
}
function search(sObj) {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('LogSheet');
var rg=sh.getRange(4,1,sh.getLastRow()-1,sh.getLastColumn());
var vA=rg.getValues();
var found=[];
for(var i=0;i<vA.length;i++) {
for(var j=1;j<vA[i].length;j++) {
if(vA[i][j]==sObj.string && new Date(vA[i][0]).valueOf()>=new Date(sObj.from).valueOf() && new Date(vA[i][0]).valueOf()<=new Date(sObj.to).valueOf()) {
var ds=Utilities.formatDate(new Date(vA[i][0]), Session.getScriptTimeZone(), "E MMM dd,yyyy");
vA[i].splice(0,1,'Row:' + Number(i+4),ds);//Had to remove Dates() so that it could be returned to the client
found.push(vA[i]);
}
}
}
if(found) {
Logger.log(found);
return found;
}
}
aq5.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function() {
});
function search() {
var from=String($('#b').val().replace(/-/g,'/'));
var to=String($('#a').val().replace(/-/g,'/'));
var searchfor=$('#srchtxt').val();
console.log('from: %s to: %s searchfor: %s',from,to,searchfor);
google.script.run
.withSuccessHandler(function(fA){
var html="";
if(fA.length) {
fA.forEach(function(r){
console.log(r.join(','));
html+=r.join(',')+ '<br />';
})
}else{
html="No Results Found";
}
$('#results').html(html);
})
.search({from:from,to:to,string:searchfor});
}
console.log("My Code");
</script>
</head>
<h1>Search</h1>
<textarea cols="40" rows="5" id="srchtxt"></textarea><br />
From: <input type="date" id="b"/><br />
To: <input type="date" id="a" /><br />
<input type="button" value="Search" onClick="search();" />
<div id="results"></div>
</html>
Search Sheet:
I have one textbox and keypad design to take date of birth by user.
HTML code
Memory = "0"; // initialise memory variable
Current = "0"; // and value of Display ("current" value)
Operation = 0; // Records code for eg * / etc.
MAXLENGTH = 8; // maximum number of digits before decimal!
function format(input, format, sep) {
var output = "";
var idx = 0;
for (var i = 0; i < format.length && idx < input.length; i++) {
output += input.substr(idx, format[i]);
if (idx + format[i] < input.length) output += sep;
idx += format[i];
}
output += input.substr(idx);
return output;
}
function AddDigit(dig) //ADD A DIGIT TO DISPLAY (keep as 'Current')
{ if (Current.indexOf("!") == -1) //if not already an error
{ if ( (eval(Current) == 0)
&& (Current.indexOf(".") == -1)
) { Current = dig;
} else
{ Current = Current + dig;
};
Current = Current.toLowerCase(); //FORCE LOWER CASE
} else
{ Current = "Hint! Press 'Clear'"; //Help out, if error present.
};
if (Current.length > 0) {
Current = Current.replace(/\D/g, "");
Current = format(Current, [2, 2, 4], "/");
}
document.calc.display.value = Current.substring(0, 10);
}
function Clear() //CLEAR ENTRY
{ Current = "0";
document.calc.display.value = Current;
}
<form Name="calc" method="post">
<input class="intxt1" autocomplete="off" id="ptdob" maxlength="6" name="display" type="tel" value="" placeholder="MM/DD/YYYY"><button class="cancel-icon" type="reset" OnClick="Clear()"></button>
<div class="calculator" style="margin: 30px auto;">
<!-- Screen and clear key -->
<div class="keys">
<!-- operators and other keys -->
<span OnClick="AddDigit('1')">1</span>
<span OnClick="AddDigit('2')">2</span>
<span OnClick="AddDigit('3')">3</span>
<span OnClick="AddDigit('4')">4</span>
<span OnClick="AddDigit('5')">5</span>
<span OnClick="AddDigit('6')">6</span>
<span OnClick="AddDigit('7')">7</span>
<span OnClick="AddDigit('8')">8</span>
<span OnClick="AddDigit('9')">9</span>
<span OnClick="AddDigit('0')" style="width: 166px;">0</span>
<span class="clear" OnClick="Clear()">
<div class="xBox">X</div>
</span>
</div>
</div>
</form>
I am taking date in MM/DD/YYYY format. Above code is working fine. It takes digits by automatically adding / in between digits. But when user wants to enter date like 05/11/2016, for month it does not allowing to take 0 at start. when user clicks 0 from keypad and then 5 for example, it coverts 0 to 5. It does not take 0 at the beginning. And it adds next clicked digit to month. e.g. 51/11/2016 like this.
How should I allow 0 at the beginning for month?
NOTE: I have my web page design for above is like below image:
User should not type directly in textbox. Textbox should have inputs from the keypad that I have design. So no use of applying date functionality on textbox like type="date" or using datepicker or any plugins as user is not directly using textbox.
You're quite close, but there are definitely better ways of doing this, as suggested in the comments (DatePicker, moment.js(), etc.).
However, looking at your code, you have a few problems.
Current = "0"; - why are we setting the default value to '0'? It should be Current = "";.
if(eval(Current) == 0) - I have no idea what this is doing. However, if the first digit is '0', then you're doing if(eval(0) == 0). i.e. if(false == false). i.e. if(true).
eval is evil, but if you insist on doing it that way, then you can switch that line to if(eval(Current) === undefined).
Lastly, in Clear, Current = "0"; - same as before. Current = "";.
What you have isn't a bad first attempt at JS, so keep practicing. Some tips:
Lose the Title Case var/function names.
Use var whenever defining variables (unless using ES6 - then use let/const)
Don't recreate the wheel - use libraries that already exist.
Use correct HTML attributes - onClick over OnClick.
Memory = "0"; // initialise memory variable
Current = ""; // and value of Display ("current" value)
Operation = 0; // Records code for eg * / etc.
MAXLENGTH = 8; // maximum number of digits before decimal!
function format(input, format, sep) {
var output = "";
var idx = 0;
for (var i = 0; i < format.length && idx < input.length; i++) {
output += input.substr(idx, format[i]);
if (idx + format[i] < input.length) output += sep;
idx += format[i];
}
output += input.substr(idx);
return output;
}
function AddDigit(dig) //ADD A DIGIT TO DISPLAY (keep as 'Current')
{ if (Current.indexOf("!") == -1) //if not already an error
{ if ( (eval(Current) === undefined)
&& (Current.indexOf(".") == -1)
) { Current = dig;
} else
{ Current = Current + dig;
};
Current = Current.toLowerCase(); //FORCE LOWER CASE
} else
{ Current = "Hint! Press 'Clear'"; //Help out, if error present.
};
if (Current.length > 0) {
Current = Current.replace(/\D/g, "");
Current = format(Current, [2, 2, 4], "/");
}
document.calc.display.value = Current.substring(0, 10);
}
function Clear() //CLEAR ENTRY
{ Current = "";
document.calc.display.value = Current;
}
<form Name="calc" method="post">
<input class="intxt1" autocomplete="off" id="ptdob" maxlength="6" name="display" type="tel" value="" placeholder="MM/DD/YYYY"><button class="cancel-icon" type="reset" OnClick="Clear()"></button>
<div class="calculator" style="margin: 30px auto;">
<!-- Screen and clear key -->
<div class="keys">
<!-- operators and other keys -->
<span OnClick="AddDigit('1')">1</span>
<span OnClick="AddDigit('2')">2</span>
<span OnClick="AddDigit('3')">3</span>
<span OnClick="AddDigit('4')">4</span>
<span OnClick="AddDigit('5')">5</span>
<span OnClick="AddDigit('6')">6</span>
<span OnClick="AddDigit('7')">7</span>
<span OnClick="AddDigit('8')">8</span>
<span OnClick="AddDigit('9')">9</span>
<span OnClick="AddDigit('0')" style="width: 166px;">0</span>
<span class="clear" OnClick="Clear()">
<div class="xBox">X</div>
</span>
</div>
</div>
</form>
I have a textbox and onkeyup event I have to mask (with asterisk (*) character) a portion of the string (which is a credit card number) when user enter the values one after the other. e.g. say the value that the user will enter is 1234 5678 1234 2367.
But the textbox will display the number as 1234 56** **** 2367
I general if the user enters XXXX XXXX XXXX XXXX, the output will be XXXX XX** **** XXXX where X represents any valid number
The program needs to be done using jQuery. I have already made the program (and it is working also) which is as follows:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script>
$(document).ready(function() {
$("#txtCCN").keyup(function(e) {
var CCNValue = $(this).val();
var CCNLength = CCNValue.length;
$.each(CCNValue, function(i) {
if (CCNLength <= 7) {
$("#txtCCN").val(CCNValue);
} //end if
if (CCNLength >= 8 && CCNLength <= 14) {
$("#txtCCN").val(CCNValue.substring(0, 7) + CCNValue.substring(7, CCNLength).replace(/[0-9]/g, "*"));
} //end if
if (CCNLength >= 15) {
$("#txtCCN").val(CCNValue.substring(0, 7) + CCNValue.substring(7, 15).replace(/[0-9]/g, "*") + CCNValue.substring(15));
} //end if
});
});
});
</script>
</head>
<body>
<input type="text" id="txtCCN" maxlength=19 />
</body>
</html>
But I think that the program can be optimized/re-written in a much more elegant way.
N.B. I don't need any validation at present.
No need of any condition of length, substring and replace can be directly used on the string of any length safely.
$(document).ready(function() {
$("#txtCCN").keyup(function(e) {
var CCNValue = $.trim($(this).val());
$(this).val(CCNValue.substring(0, 7) + CCNValue.substring(7, 15).replace(/\d/g, "*") + CCNValue.substring(15));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<input type="text" id="txtCCN" maxlength=19 />
val can also be used
$(document).ready(function() {
$("#txtCCN").keyup(function(e) {
$(this).val(function(i, v) {
return v.substring(0, 7) + v.substring(7, 15).replace(/\d/g, "*") + v.substring(15);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<input type="text" id="txtCCN" maxlength=19 />
The same can be done in VanillaJS
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('txtCCN').addEventListener('keyup', function() {
var value = this.value.trim();
this.value = value.substring(0, 7) + value.substring(7, 15).replace(/\d/g, '*') + value.substring(15);
}, false);
});
<input type="text" id="txtCCN" required maxlength="19" />
Try It: Its 100% workable...
$(document).ready(function () {
$("#txtCCN").keyup(function (e) {
var CCNValue = $(this).val();
CCNValue = CCNValue.replace(/ /g, '');
var CCNLength = CCNValue.length;
var m = 1;
var arr = CCNValue.split('');
var ccnnewval = "";
if (arr.length > 0) {
for (var m = 0; m < arr.length; m++) {
if (m == 4 || m == 8 || m == 12) {
ccnnewval = ccnnewval + ' ';
}
if (m >= 6 && m <= 11) {
ccnnewval = ccnnewval + arr[m].replace(/[0-9]/g, "*");
} else {
ccnnewval = ccnnewval + arr[m];
}
}
}
$("#txtCCN").val(ccnnewval);
});
});
One thing you might consider is deleting the first two if statements. All of the work your function does is contained within the last one, so you could just change it from
if(CCNLength >= 15)
to
if(CCNLength >= 8)
This seems to maintain the functionality while cutting out some repetition in your code.
Adding a generic routine for customizing space points and mask range in the input data. This will also respect the space characters as you originally asked for.
$(function () {
$("#cardnum").keyup(function (e) {
var cardNo = $(this).val();
//Add the indices where you need a space
addSpace.call(this, [4, 9, 14], cardNo );
//Enter any valid range to add mask character.
addMask.call(this, [7, 15], $(this).val()); //Pick the changed value to add mask
});
function addSpace(spacePoints, value) {
for (var i = 0; i < spacePoints.length; i++) {
var point = spacePoints[i];
if (value.length > point && value.charAt(point) !== ' ')
$(this).val((value.substr(0, point) + " "
+ value.substr(point, value.length)));
}
}
function addMask(range, value) {
$(this).val(value.substring(0, range[0])
+ value.substring(range[0], range[1]).replace(/[0-9]/g, "*")
+ value.substring(range[1]));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="cardnum" maxlength="19" />
I need to make a box so that when the user enters a value of one through 6, it rolls that many dice. I'm a complete beginner to javascript and any help would be greatly appreciated.
Here's my function:
function NumberValue() {
for (i = 0; i <['randNumber']; i++){
var numberRoll = Math.floor(Math.random() * 6) + 1;
var userNumber = '../images/die' + numberRoll + '.gif';
myNewTag = "<img id='dieImgRandom' src='" + userNumber + "'>"
document.getElementById('dieDivRandom').innerHTML += myNewTag;
And here is my body element:
<h1>Why don't you pick please?</h1>
<div id="dieDivRandom" style="text-align:center">
<p>
<div id="dieImageRand">
<img id="dieImgRandom" alt="die image" src="../images/die1.gif">
<br>
<input type="text" id="randNumber" size=20 value="Enter 1 through 6">
<input type="button" value="Click to Roll" onclick="NumberValue();">
</div>
The function needs to allow a user to submit the number one, two, three, four, five, or six, and that many images need to display on the screen. The images a relocated in my images folder, so relative links will work just fine. That's actually what I need to use. Thank you.
Replace:
for (i = 0; i <['randNumber']; i++){
With:
for (i = 0; i <document.getElementById('randNumber').value; i++) {
The <input /> tag can be accessed by using either of the following:
document.getElementById('inputId').value;
document.formName.inputName.value
Finally, your code becomes:
function NumberValue() {
for (i = 0; i < document.getElementById('inputId').value; i++) {
var numberRoll = Math.floor(Math.random() * 6) + 1;
var userNumber = '../images/die' + numberRoll + '.gif';
myNewTag = "<img id='dieImgRandom' src='" + userNumber + "'>"
document.getElementById('dieDivRandom').innerHTML += myNewTag;
}
}
Use this to read values from textbox
function NumberValue() {
var ranNum = document.getElementById('randNumber').value;
for (i = 0; i <ranNum ; i++){
}
}
EDIT:
If you want to validate the Entered number
add this block of code
function NumberValue() {
var ranNum = document.getElementById('randNumber').value;
if(ranNum < 1 || ranNum > 6) {
alert("Please enter number from 1 to 6 only");
return false;
}
for (i = 0; i <ranNum ; i++){
}
return true;
}