elasticlunr.js not showing results for search query - javascript

I used elasticlunr.js search engine.
I edited their example source code
$('input').bind("enterKey", function (e) {
var value_test = $("#inputSuccess1").val();
if ($(this).val() < 2) return
var config = $('#configuration').val();
config.trim();
var json_config = null;
if (config != '') {
json_config = new elasticlunr.Configuration(config, idx.getFields()).get();
}
var query = value_test;
var results = null;
console.log(query);
if (json_config == null) {
results = idx.search(query).map(function (result) {
console.log(result);
return questions.filter(function (q) {
console.log(q);
return q.page_id === parseInt(result.ref, 10)
})[0]
})
} else {
results = idx.search(query, json_config).map(function (result) {
return questions.filter(function (q) {
return q.page_id === parseInt(result.ref, 10)
})[0]
})
}
renderQuestionList(results);
console.log(results);
});
All stored search results are displayed on load but when I enter a search query, it returns the supposed un-edited search results. Though the search result array is populated (for e.g.) by 2 items , it is still undefined. I tried to put my own result (just 1) on the example_index.json and tried to input tags relevant to it. It still doesn't show.
HTML CODE
<body>
<div id="wrapper">
<main class="main" role="main" style="margin-top: 30px">
<div class="container">
<div class="row">
<header style="margin-left: 15px; margin-right: 15px;">
<h1>Elasticlunr<span>.js</span></h1>
<h2>Lightweight full-text search engine in Javascript for browser search and offline search.</h2>
</header>
</div>
<div class="row">
<div class="col-md-6">
<span><strong><i>Search Configuration:</i></strong></span>
<textarea id="configuration" class="form-control" rows="6" style="font-size: 0.8em;"></textarea>
</div>
<div class="col-md-6" style="margin-left: 0px; margin-right: 0px; padding-right: 0px; padding-left: 0px;">
<span><strong><i>Configuration Example:</i></strong></span>
</div>
</div>
<div class="row" style="margin-left: 0px; margin-right: 0px; border-top-style: solid; border-top-width: 0px; padding-top: 10px;">
<div class="col-md-6" style="padding-left: 0px; padding-right: 50px">
<form>
<div class="form-group has-success">
<div class="col-xs-9" style="padding-left: 0px;">
<input type="search" class="form-control" id="inputSuccess1" >
</div>
</div>
<div><a class="all btn btn-primary btn-block" href="#">All</a></div>
</form>
</div>
<div class="col-md-12" style="margin-bottom: 20px; padding-bottom: 15px; border-bottom: 1px solid rgba(7, 94, 115, 0.3); padding-left: 0px;"></div>
</div>
<div class="row" style="margin-left: 0px; margin-right: 0px;">
<div class="col-md-6" style="margin-left: 0px; margin-right: 0px;">
<div id='question-list-container' style="margin-left: 0px; margin-right: 0px;"></div>
</div>
<div class="col-md-6" style="margin-left: 0px; margin-right: 0px; padding-right: 0px; padding-left: 0px;">
<div id='question-view-container' style="margin-left: 0px; margin-right: 0px; padding-right: 0px; padding-left: 0px;"></div>
</div>
<div class="col-md-12" style="padding-bottom: 15px; border-bottom:1px solid rgba(7,94,115,0.3);"></div>
</div>
</main>
</div>
<!-- end of wrapper -->
<!-- Begin footer -->
<footer class="footer vertical-center">
<div class="container">
<p class="pull-right text-muted">Back to top
</p>
<p class="text-muted">Copyright © Wei Song 2015.
https://github.com/weixsong watkinsong#163.com. Donate by Alipay: watkinsong#163.com</p>
</div>
</footer>
<script>
(function(hijs) {
//
// hijs - JavaScript Syntax Highlighter
//
// Copyright (c) 2010 Alexis Sellier
//
// All elements which match this will be syntax highlighted.
var selector = hijs || 'pre';
var keywords = ('var function if else for while break switch case do new null in with void ' + 'continue delete return this true false throw catch typeof with instanceof').split(' '),
special = ('eval window document undefined NaN Infinity parseInt parseFloat ' + 'encodeURI decodeURI encodeURIComponent decodeURIComponent').split(' ');
// Syntax definition
// The key becomes the class name of the <span>
// around the matched block of code.
var syntax = [
['comment', /(\/\*(?:[^*\n]|\*+[^\/*])*\*+\/)/g],
['comment', /(\/\/[^\n]*)/g],
['string', /("(?:(?!")[^\\\n]|\\.)*"|'(?:(?!')[^\\\n]|\\.)*')/g],
['regexp', /(\/.+\/[mgi]*)(?!\s*\w)/g],
['class', /\b([A-Z][a-zA-Z]+)\b/g],
['number', /\b([0-9]+(?:\.[0-9]+)?)\b/g],
['keyword', new(RegExp)('\\b(' + keywords.join('|') + ')\\b', 'g')],
['special', new(RegExp)('\\b(' + special.join('|') + ')\\b', 'g')]
];
var nodes, table = {};
if (/^[a-z]+$/.test(selector)) {
nodes = document.getElementsByTagName(selector);
} else if (/^\.[\w-]+$/.test(selector)) {
nodes = document.getElementsByClassName(selector.slice(1));
} else if (document.querySelectorAll) {
nodes = document.querySelectorAll(selector);
} else {
nodes = [];
}
for (var i = 0, children; i < nodes.length; i++) {
children = nodes[i].childNodes;
for (var j = 0, str; j < children.length; j++) {
code = children[j];
if (code.length >= 0) { // It's a text node
// Don't highlight command-line snippets
if (!/^\$/.test(code.nodeValue.trim())) {
syntax.forEach(function(s) {
var k = s[0],
v = s[1];
code.nodeValue = code.nodeValue.replace(v, function(_, m) {
return '\u00ab' + encode(k) + '\u00b7' + encode(m) +
'\u00b7' + encode(k) + '\u00bb';
});
});
}
}
}
}
for (var i = 0; i < nodes.length; i++) {
nodes[i].innerHTML =
nodes[i].innerHTML.replace(/\u00ab(.+?)\u00b7(.+?)\u00b7\1\u00bb/g, function(_, name, value) {
value = value.replace(/\u00ab[^\u00b7]+\u00b7/g, '').replace(/\u00b7[^\u00bb]+\u00bb/g, '');
return '<span class="' + decode(name) + '">' + escape(decode(value)) + '</span>';
});
}
function escape(str) {
return str.replace(/</g, '<').replace(/>/g, '>');
}
// Encode ASCII characters to, and from Braille
function encode(str, encoded) {
table[encoded = str.split('').map(function(s) {
if (s.charCodeAt(0) > 127) {
return s
}
return String.fromCharCode(s.charCodeAt(0) + 0x2800);
}).join('')] = str;
return encoded;
}
function decode(str) {
if (str in table) {
return table[str];
} else {
return str.trim().split('').map(function(s) {
if (s.charCodeAt(0) - 0x2800 > 127) {
return s
}
return String.fromCharCode(s.charCodeAt(0) - 0x2800);
}).join('');
}
}
})(window.hijs);
</script>
3rd edit:
I have this code
$('input').keyup(function(e){
if(e.keyCode == 13)
{
$(this).trigger("enterKey");
}
});
I use xampp and when I press enter this is what happens. those "Empty list" are from the previous .json file but with a different id . I can't find that part
it has a lot of codes so i uploaded it here (edited: removed link. fixed now)

The input tag exists in between the form tag. This implies that upon pressing enter the form is submitted and therefore the page reloads thus removing any information you placed and showing the unadulterated results .
In the example provided by the developer, $('input').bind('keyup', debounce(function () { is used. Therefore, upon entering text the tags are searched. However, in your case, the control doesn't even shift to code that you are intending to run.
Please check this
https://jsfiddle.net/kaminasw/rqj68xt5/ where it should show alert upon pressing enter in the input.
$('input').bind("enterKey",function(e){
alert();
});
Try to use the actual code with keyup event and compare the pressed key with enterKey code i.e. 13.
$('input').keyup(function(e) {
// 13 is ENTER
if (e.which === 13)
// Perform action
});

I read the manual and missed and ingnored the node.js part. As you can see the index_builder.js uses fs, which I learned, that uses node.js. You have to use node.js and run index_builder.js. This will build an index.json file from your data.json(stored search results). The code uses the example source code I have to rebuild the index. Also, I am using xampp for local host.
Step 1. Download and Install node.js
Step 2. Run Xampp Shell on elasticlunr project directory
Step 3. Type in node index_builder.js
Step 4. Elastic Search will work with the entered query
This is the code of my index_builder.js
var elasticlunr = require('./elasticlunr.js'),
fs = require('fs');
var idx = elasticlunr(function () {
this.setRef('page_id');
this.addField('title');
this.addField('tags');
this.addField('body');
this.addField('url');
});
fs.readFile('./example_data.json', function (err, data) {
if (err) throw err;
var raw = JSON.parse(data);
var questions = raw.questions.map(function (q) {
return {
page_id: q.page_id,
title: q.title,
body: q.body,
url: q.url,
tags: q.tags.join(' ')
};
});
questions.forEach(function (question) {
idx.addDoc(question);
});
fs.writeFile('./example_index.json', JSON.stringify(idx), function (err) {
if (err) throw err;
console.log('done');
});
});
Thanks!

Related

My WebApp where withSuccessHandler returns undefined

I need help sorting this out. Everything seems to work fine until it gets to receive the results of request, where someting goes wrong. The idea of the project is a Web App, where user gets 2 fields for name and date of birth. After filling them the information is verified by checking in the spreadsheet with relevant information. If everything is okay, the program next obtains appropriate id with getSheetId(), generates <iframe> code for access and should be returning it with HtmlService. However, something makes it return undefined.
Code.gs
function doGet() {
Logger.log("Login is loading")
return HtmlService
.createTemplateFromFile('index')
.evaluate()
//.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function evaluate(name, date) {
var t = SpreadsheetApp.openById('1nQxfaQcNdM6S1roJs6gxTaZPtM5gOublch5jVKDhkho')
.getSheetByName('key');
Logger.log(t.getSheetId());
Logger.log(name);
Logger.log(date);
var v = t.getRange("B2:D200");
var i = 0;
for (i = 1; i < 200; i++) {
if (v.getCell(i, 2).getValue() == name) {
Logger.log(v.getCell(i, 2).getValue());
Logger.log(name & " = the name");
Logger.log(new Date(v.getCell(i,3).getValue()).getTime());
var pdate = date.split(".");
Logger.log(new Date(pdate[2],pdate[1],pdate[0]).getTime());
var t = v.getCell(i,3).getValue();
Logger.log(pdate);
Logger.log(t.getFullYear());
Logger.log(t.getMonth());
Logger.log(t.getDate());
if (new Date(t.getFullYear(),t.getMonth()+1,t.getDate()).getTime() == new Date(pdate[2],pdate[1],pdate[0]).getTime()) {
Logger.log("match found");
include(v.getCell(i,1).getValue());
break;
} else {
Logger.log("Bad date");
return "<h2>Wrong Input. 404.</h2>";}
}
}
if (i >= 199) {
Logger.log("Bad name");
return "<h2>Wrong Input. 404.</h2>";
}
}
var hhtml = "";
function include(name) {
var html = '<iframe src="https://docs.google.com/spreadsheets/d/e/2PACX-1vTeFjXOSsBRAKjbFLUSBGZOXtmjZO_4RtxxrQtXbk9sxZkF5Kdjs9OIs0tSQwekjYbOTn7JJ-_iCdeD/pubhtml?gid='
var t = SpreadsheetApp.openById('1nQxfaQcNdM6S1roJs6gxTaZPtM5gOublch5jVKDhkho').getSheetByName(name);
if (t == null) {
Logger.log("Page not found");
return "<h1>Wrong Input. 404.</h1>"
} else {
html += t.getSheetId();
}
Logger.log(name);
html += '&single=true&widget=true&headers=false" width="80%" height="600"></iframe>'
html += '<br><br><br><h3>Рейтинг групи</h3><iframe src="https://docs.google.com/spreadsheets/d/e/2PACX-1vRF1MobEoKdxvO_SopGTvl-WzqEQ3nQXd6Jo_a7RTAg09yluO32AClwd4krWnVHXGQllPPwOsDeYYzN/pubhtml?gid=2096708929&single=true&widget=true&headers=false" width="80%" height="600"></iframe>'
Logger.log(html);
hhtml = HtmlService.createHtmlOutput(html).getContent();
return HtmlService.createHtmlOutput(html).getContent();
}
function getHtmlCode() {
return hhtml;
}
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<div id="mainForm">
<h2> Будь-ласка введіть своє прізвище українською мовою та дату народження у форматі день.місяць.рік (наприклад: 22.06.2018) </h2>
<form>
<div>
<div class="inline form-group">
<label for="name">Прізвище</label>
<input type="text" id="nameInput" style="width: 150px;">
</div>
<div class="inline form-group">
<label for="date">Дата Народження</label>
<input type="text" id="dateInput" style="width: 150px;">
</div>
</div>
<button class="action" type="button" id="submitButton">Submit</button>
</form>
</div>
<style>
.hidden {
display:none;
}
.form-group {
margin: 2px 0px;
}
#submitButton {
margin: 4px 0px;
}
body {
margin-left: 50px;
}
</style>
<script>
$(function(){
console.log('startup')
$('#submitButton').on('click', function(){
console.log("data get");
function respondent(value)
{
$('#mainForm').toggleClass('hidden');
console.log("script is success");
console.log(value);
document.getElementById('Response').innerHTML = value
}
google.script.run.withSuccessHandler(respondent).evaluate(document.getElementById('nameInput').value, document.getElementById('dateInput').value);
})
})
</script>
<div id="Response">
<h2>Waiting for data...</h2>
</div>
</body>
</html>
After cleaning up your code formatting, it looks like you're only returning a value from evaluate() during the Wrong Input error conditions. Nothing is returned otherwise.
Perhaps you meant to add a line like this at the end of evaluate():
return include(name);
Also, the hhtml global variable and getHtmlCode() functions aren't useful in the context of Apps Script. Each execution is in a separate instance with no state being carried over. Which mean getHtmlCode() will always return an empty string.

How to auto format my textbox in license format?

I tried searching on the internet for answer but the closest I can find is in this jfiddle
What I wanted to do is when the page loads, the textbox is automatically filled with this words Furniture/Chair/Square. In addition, the user can input some text next to the words like this Furniture/Chair/Square/_ _ _/_ _ _. The user cannot erase the automatically filled words.
This is a work around with some reference from jwa's post and RegEx:
$(function() {
$('label.prefilled input[type="text"][placeholder]').on('input', function() {
var fmt = this.placeholder.split('');
var len = this.placeholder.match(/_/g).length;
var val = this.value.replace(/[^a-z]/gi, '').split('').slice(0, len);
var res = '',
v, f;
while ((v = val.shift()) && (f = fmt.shift())) {
if ('_' === f) {
res += v;
} else {
res += f + v;
fmt.shift();
}
}
res += fmt.join('');
this.value = res;
}).trigger('input');
});
label.prefilled input[type="text"] {
border: none;
outline: none;
}
label.prefilled {
border: 1px ridge gray;
}
div.card {
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">
<label class='prefilled'>
Furniture/Chair/Square/<input type="text" placeholder="___/___"/>
</label>
</div>
<div class="card">
<label class='prefilled'>
Electronic/Handheld/<input type="text" placeholder="______/______"/>
</label>
</div>
How do I include numbers?
Use [^a-z0-9] in this line this.value.replace(/[^a-z]/gi, '')
$(function() {
$('label.prefilled input[type="text"][placeholder]').on('input', function() {
var fmt = this.placeholder.split('');
var len = this.placeholder.match(/_/g).length;
var val = this.value.replace(/[^a-z0-9]/gi, '').split('').slice(0, len);
var res = '',
v, f;
while ((v = val.shift()) && (f = fmt.shift())) {
if ('_' === f) {
res += v;
} else {
res += f + v;
fmt.shift();
}
}
res += fmt.join('');
this.value = res;
}).trigger('input');
});
label.prefilled input[type="text"] {
border: none;
outline: none;
}
label.prefilled {
border: 1px ridge gray;
}
div.card {
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">
<label class='prefilled'>
Furniture/Chair/Square/<input type="text" placeholder="___/___"/>
</label>
</div>
<div class="card">
<label class='prefilled'>
Electronic/Handheld/<input type="text" placeholder="______/______"/>
</label>
</div>
You can do this by assigning a label to the input field you create. For example...
#text-input {
border: none;
outline: none;
}
label{
border:solid 1px black;
padding-right: 2px;
}
<label for="text-input">
furniture chair square
<input type="text" id="text-input" />
</label>
Use RegExp to solve your problem.
You may add some css or addition text to notice the user error input.
function checkStr(str){
//check pattern
result = str.match(/^Furniture\/Chair\/Square([a-zA-Z\/]+)?/)
if(result == null || result[0].length !== str.length){
//revert the input field to default
document.getElementById('userText').value = "Furniture/Chair/Square"
}
}
<input type="text" value="Furniture/Chair/Square" id="userText" oninput="checkStr(value)"></input>
<p id='asd'></p>

Count each individual vowel in string upon click

Writing some js for an html file where i input a sentence (string). and when i click a button, it outputs the amount of each individual vowel, excluding y and not paying attention to punctuation. I cannot use var so i am trying to make this work using let. I believe i'm on the right path here,starting with the vowel a, yet if the sentence doesn't contain an a i get an error. I can't think of what to do next. Any thoughts?
'use strict';
let vButton = document.querySelectorAll('#vowels');
vButton.forEach(function(blip) {
blip.addEventListener('click', function(evt) {
evt.preventDefault();
console.log('click');
let vowelString = document.getElementById('roboInput'),
sentence = vowelString.value;
if (sentence !== '') {
let aMatches = sentence.match(/a/gi).length;
alert("a - " + aMatches);
}
vowelString.value = '';
});
});
a {
cursor: pointer;
}
.well-robot {
min-height: 340px;
}
.input-robot {
width: 100%;
min-height: 100px;
}
.output-robot {
border: 1px solid #000000;
min-height: 150px;
margin-top: 10px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">
<div class="container">
<div class="alert alert-info">
Hello! I'm a smart robot. I can do many interesting things. Type something below and click a button to watch me work!
</div>
<div class="row">
<div class="col-sm-4">
<img src="./robot.gif">
</div>
<div class="col-sm-8 well well-robot">
<textarea id="roboInput" placeholder="Input something here!" class="input-robot"></textarea>
<div class="btn-group btn-group-justified">
<a class="btn btn-default" id="vowels">Count Vowels</a>
<a class="btn btn-default" id="anagrams">Count Anagrams</a>
<a class="btn btn-default" id="distance">Word Distance</a>
</div>
<div id="robotResult" class="output-robot">
</div>
</div>
</div>
</div>
When there's no match for the regular expression, .match() returns null, not an empty array, so you can't get the length. You need to check for that.
let matches = sentence.match(/a/gi);
let matchLength = matches ? matches.length : 0;
alert('a - ' + matchLength);
If I understand your question correctly, you may want something like this:
'use strict';
let vButton = document.querySelectorAll('#vowels');
vButton.forEach(function(blip) {
blip.addEventListener('click', function(evt) {
evt.preventDefault();
//console.log('click');
let vowelString = document.getElementById('roboInput'),
sentence = vowelString.value;
if (sentence) {
let result = {a: 0, e: 0, i: 0, o: 0, u: 0 };
for(var i = 0, l = sentence.length; i < l; i++) {
if(result.hasOwnProperty(sentence[i]))
result[sentence[i]]++;
}
console.log(result);
}
vowelString.value = '';
});
});
a {
cursor: pointer;
}
.well-robot {
min-height: 340px;
}
.input-robot {
width: 100%;
min-height: 100px;
}
.output-robot {
border: 1px solid #000000;
min-height: 150px;
margin-top: 10px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">
<div class="container">
<div class="alert alert-info">
Hello! I'm a smart robot. I can do many interesting things. Type something below and click a button to watch me work!
</div>
<div class="row">
<div class="col-sm-4">
<img src="./robot.gif">
</div>
<div class="col-sm-8 well well-robot">
<textarea id="roboInput" placeholder="Input something here!" class="input-robot"></textarea>
<div class="btn-group btn-group-justified">
<a class="btn btn-default" id="vowels">Count Vowels</a>
<a class="btn btn-default" id="anagrams">Count Anagrams</a>
<a class="btn btn-default" id="distance">Word Distance</a>
</div>
<div id="robotResult" class="output-robot">
</div>
</div>
</div>
</div>

For MM/DD/YYYY text, display only that text which is not entered by user

I have a page like below image
According to my requirement, user is allowed to enter digits from the keypad that is provided on the page only. So input field is readonly.
Now I am trying to get is, when user start entering month then other text should remain in text field until user types that. e.g. 05/DD/YYYY like this. And accordingly that text will be hide.
If I placed placeholder then when user starts entering digits all text gone. I don't want that. So I have taken "MM/DD/YYYY" text in seperate span tag.
var 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;
document.calc.display.focus();
} else {
Current = Current + dig;
document.calc.display.focus();
}
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);
document.getElementById("cursor").style.visibility = "hidden";
}
function Clear() { //CLEAR ENTRY
Current = "";
document.calc.display.value = Current;
document.calc.display.focus();
document.getElementById("cursor").style.visibility = "visible";
//setInterval ("cursorAnimation()", 5000);
}
function backspace() {
Current = document.calc.display.value;
var num = Current;
Current = num.slice(0,num.length - 1);
document.calc.display.value = Current;
document.calc.display.focus();
document.getElementById("cursor").style.visibility = "hidden";
}
function cursorAnimation() {
$("#cursor").animate({
opacity: 0
}, "fast", "swing").animate({
opacity: 1
}, "fast", "swing");
}
//--------------------------------------------------------------->
$(document).ready(function() {
document.getElementById("cursor").style.visibility = "visible";
//setInterval ("cursorAnimation()", 1000);
});
.intxt1 {
padding: 16px;
border-radius: 3px;
/* border: 0; */
width: 1017px;
border: 1px solid #000;
font-family: Droid Sans Mono;
background: #fff;
}
.txtplaceholder {
font-family: "Droid Sans Mono";
color: #D7D7D7;
position: relative;
float: left;
left: 219px;
top: 17px;
z-index: 10 !important;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
display: inline-block;
}
#cursor {
position: relative;
z-index: 1;
left: 32px;
top: 2px;
visibility: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<form Name="calc" method="post">
<div style="position:relative">
<span id="cursor">_</span>
<span class="txtplaceholder">MM/DD/YYYY</span>
<span style="z-index:100">
<input class="intxt1" autocomplete="off" id="pt_dob" name="display" value="" type="text" readonly>
</span>
<button class="cancel-icon" type="reset" onClick="Clear()"></button>
</div>
<div class="num_keypad1" style=" margin-top:19px;">
<!-- Screen and clear key -->
<div class="num_keys">
<!-- operators and other keys -->
<span id="key1" onClick="AddDigit('1')">1</span>
<span id="key2" onClick="AddDigit('2')">2</span>
<span id="key3" onClick="AddDigit('3')">3</span>
<span id="key4" onClick="AddDigit('4')">4</span>
<span id="key5" onClick="AddDigit('5')">5</span>
<span id="key6" onClick="AddDigit('6')">6</span>
<span id="key7" onClick="AddDigit('7')">7</span>
<span id="key8" onClick="AddDigit('8')">8</span>
<span id="key9" onClick="AddDigit('9')">9</span>
<span id="key0" onClick="AddDigit('0')" style="width: 200px;">0</span>
<span id="keyback" class="clear" onClick="backspace()"> <div class="num_xBox">X</div></span>
</div>
</div>
</form>
With the above Html code I am getting below result:
Problems coming are below:
My digits are going below the text "MM/DD/YYYY". I am not getting how should I get my digits above that text
How should I hide the text which is entered by user and display other accordingly e.g. "MM" should hide if user enters 05 and display other text like this "05/DD/YYYY".
Can anyone please help me in this?
NOTE: With input type=date or by any other plugins I can achieve above functionality but my requirement is different. I have to achieve this with HTML, CSS, JS only.
I would use a ready built data picker for this kind of thing as it would have all the error checking in built to ensure you enter a date in the correct format.
The way you are doing it, you are not able to check if the day is valid until you have entered the month, by which time the user will have to backspace and it will be a very slow and clunky process which is not very user friendly.
Anyway, if you persist with a number pad, here is how I would do it.
put the date in a global array
have a global index counter
add and remove values based on the index counter
The following is a very quick example of the above
var dateBits = ["D", "D", "M", "M", "Y", "Y", "Y", "Y"],
letters = ["D", "D", "M", "M", "Y", "Y", "Y", "Y"],
input = document.getElementById('pt_dob'),
currentIndex = 0;
function makeDate() {
return dateBits[0] + dateBits[1] + "/" + dateBits[2] + dateBits[3] + "/" + dateBits[4] + dateBits[5] + dateBits[6] + dateBits[7];
}
function AddDigit(number) {
dateBits[currentIndex] = number;
if (currentIndex < 8) {
currentIndex++;
}
input.value = makeDate();
}
function RemoveDigit() {
if (currentIndex > 0) {
currentIndex--;
}
dateBits[currentIndex] = letters[currentIndex];
input.value = makeDate();
}
function Clear() {
for (i = 0; i < letters.length; i++) {
dateBits[i] = letters[i];
}
currentIndex = 0;
input.value = makeDate();
}
input.value = makeDate(); // run this line onload or include this whole script at the bottom of the page to get your input to start with your text
.intxt1 {
padding: 16px;
border-radius: 3px;
/* border: 0; */
width: 1017px;
border: 1px solid #000;
font-family: Droid Sans Mono;
background: #fff;
}
#cursor {
position: relative;
z-index: 1;
left: 32px;
top: 2px;
visibility: hidden;
}
.num_keys > span {
display: inline-flex;
width: 2em;
height: 2em;
align-items: center;
justify-content: center;
cursor: pointer;
border: 1px solid black;
}
<form Name="calc" method="post">
<div style="position:relative"><span id="cursor">_</span>
<span class="txtplaceholder">MM/DD/YYYY</span><span style="z-index:100"><input class="intxt1" autocomplete="off" id="pt_dob" name="display" value="" type="text" autocomplete="off" readonly></span>
<button class="cancel-icon" type="reset" onClick="Clear(); return false;">clear</button>
</div>
<div class="num_keypad1" style=" margin-top:19px;">
<!-- Screen and clear key -->
<div class="num_keys">
<!-- operators and other keys -->
<span id="key1" onClick="AddDigit('1')">1</span>
<span id="key2" onClick="AddDigit('2')">2</span>
<span id="key3" onClick="AddDigit('3')">3</span>
<span id="key4" onClick="AddDigit('4')">4</span>
<span id="key5" onClick="AddDigit('5')">5</span>
<span id="key6" onClick="AddDigit('6')">6</span>
<span id="key7" onClick="AddDigit('7')">7</span>
<span id="key8" onClick="AddDigit('8')">8</span>
<span id="key9" onClick="AddDigit('9')">9</span>
<span id="key0" onClick="AddDigit('0')" style="width: 200px;">0</span>
<span id="keyback" class="clear" onClick="RemoveDigit()"> <div class="num_xBox">X</div></span>
</div>
</div>
</form>
var text = "DD/MM/YYYY";
$(".textbox").on("focus blur", function(){
$(".wrapper").toggleClass("focused");
});
$(".wrapper").click(function (e) {
if (e.target == this) {
var b = $(".textbox", this).focus();
}
}).trigger("click");
$(".wrapper > .textbox").on("input", function(){
var ipt = $(this).text().replace(/\u00A0/g, " ");
$(".gray").text(text.substr(ipt.length, text.length));
}).trigger("input");
check this fiddle http://jsfiddle.net/7sD2r/22/
If ive understood all well. I think the one solution is to store user input in hidden field. Then get this input to split digits and return to visible input value that consists of splitted values etc.

Calling function from anonymous function in JQuery returns undefined

I'm working with this script which needs to call the external function, but the value returned in the log shows 'undefined'.
I have a checkbox that calls the external function successfully, but the anonymous jQuery function is not successful. Could this be a scope issue of some sort?
Thanks for any help.
css:
div.row {
border: 1px solid blue;
width: 100px;
}
div.child {
border: 1px solid red;
display: inline-block;
}
javascript:
function padZeros(ksa) {
getDigits(ksa);
//alert(s);
//document.getElementById("ksa_padded").value=s
}
function getDigits(MyDigits) {
var ksa = MyDigits;
var re4Digit = /^([0-9])([0-9]?)([k|s|a])([0-9])([0-9]?)([A-z]?)$/;
var first2Digits = ksa.replace(re4Digit, "$1$2");
//alert(first2Digits);
//return first2Digits;
pad(first2Digits, '2');
}
function pad(num, size) {
//var s = num+"";
//alert(num);
s = num + "";
//alert(s);
while (s.length < size) s = "0" + s;
return s;
//alert(s);
}
$("#add").click(function () {
var inserted = false;
var newText = $("#addText").val();
var $newItem = $("<div class='child'>" + newText + "</div>");
$(".row:first .child").each(function () {
//alert($(this).text());
xx = $(this).text();
var compare_a = padZeros(xx);
//alert(compare_a);
console.log(xx);
if ($(this).text() > newText) {
$newItem.insertBefore($(this));
inserted = true;
return false;
}
});
if (inserted == false) {
$newItem.appendTo(".row:first");
}
});
html
<div class="row">
<div class="child">3K1</div>
<div class="child">3K3</div>
<div class="child">3K4</div>
<div class="child">1K1</div>
<div class="child">1K2</div>
</div>
<div class="row">
<div class="child">IS2</div>
<div class="child">IS4</div>
</div>
<div class="row">
<div class="child">IA2</div>
<div class="child">IA4</div>
</div>
<br/>
<input id="addText" type="text" />
<input id="add" type="button" value="Insert Element" />
<br>
<input type="checkbox" onClick="padZeros('1k10s')">
<input type="text" id="ksa_padded">
Try
return getDigits(ksa);
return pad(first2Digits,'2');
You have to return things, otherwise they'll come out as undefined.

Categories

Resources