I am calling .keyup function of Search Textbox, and in that keyup(), I am refreshing the GRID from the database.
Problem:
But the grid is getting refreshed for (special keys too ) arrow keys, number lock,function keys and all other keys and refreshing for those keys are unnecessary. Except backspace, return,tab,space,delete.
I want to construct a regular expression such that it filters out all the control keys.
Sample code:
$('#searchContent').keyup(function (e) {
var key = e.which;
if ( /*condition*/ ) {
return;
}
//my code goes here...
}
What I have done:
Searched net thoroughly and I came up with hotkey, but that doesn't solved my purpose. So, any smart regular expression are there?
Try this HTML to see which codes match up with which keys (taken from Mozilla):
<html>
<head>
<title>charCode example</title>
<script type="text/javascript">
function showChar(e)
{
alert("Key Pressed: " + String.fromCharCode(e.charCode) + "\n"
+ "charCode: " + e.charCode);
}
</script>
</head>
<body onkeypress="showChar(event);">
<p>Press any 'character' type key.</p>
</body>
</html>
Try this trick:
function checkForChanges(){
var txt = $('#searchContent');
if(txt.val() != txt.attr('xvalue') {
//do referesh grid content here
}
}
$('#searchContent').keyup(function (e) {
$(this).attr('xvalue') = this.value;
clearTimeout(this.changeTimer);
this.changeTimer = setTimeout(checkForChanges, 20);
}
Related
I have an assignment in school but I'm totally stuck.
My assignment:
Make a program that ask for a text and then write out the text several times. First with just one letter, then with two and so on. For example, if the user write "Thomas", your program should write out "T", "Th, "Tho, "Thom", and so on.
My hopeless attempt
I been trying to use "Substring" and a loop to make it work but I'm not sure I'm on the right path or not. Right now my code look like this:
<head>
<meta charset= "UTF-8"/>
<title> assignment14 - Johan </title>
<script type="text/javascript">
var text= test.length;
for (i=0;i< test.length;i++)
function printit()
{
var str = test;
var res = str.substring (i, 2);
document.getElementById("test").innerHTML = res;
}
</script>
</head>
<body>
<h1>Assignment 14</h1>
<form name="f1">
<input type="text" id="test" value="" />
<input type="button" value="Hämta" onclick="printit(document.getElementById('test'))" />
</form>
</body>
Just need some kind of hint If I'm going in the right direction or not, should I use some other functions? Very thankful for help.
You have to rewrite a script.When you want to extract one by one you can use substring(); function.
How to Call : StringObject.substring (StartPoint,endPoint);
Solution:
<script type="text/javascript">
function printit(){
var test=document.getElementById("test").value;
var text= test.length;
for (i=0;i<= text;i++)
{
var res = test.substring (i, 0);
document.write(res);
document.write("<br/>");
}
}
</script>
You are on the right way. substring(start,end) in javascript gives you the consecutive part of the string letters from start index to end. You just use it in a wrong way for your case. You have to call it like this:
substring(0,i)
You need to make few changes to your code:
1) use document.getElementById('test').value in printit function call at onclick as you have to send the value of the textbox instead of innerHTML.
2) Modify the printif function-
function printit(test)
{
document.getElementById('test').value=''; /*remove existing text from textbox*/
for (i=0;i< test.length;i++) {
var res = str.substring (0, i+1);
document.getElementById("test").value += ' '+res;
}
}
In printit function empty the text box and then append each substring to the existing text to get "T Th Tho Thom.." and so on
Hope this helps.
I don't use for-loop for this (whenever possible, I prefer functional style). Instead, I write a function that returns an array of substrings:
const substrings = string =>
Array.from(string).map((_, i) => string.slice(0, i + 1))
And here's a working codepen
Output several time using substring() method can be done as below, create a function which performs this task of extracting the user inputted string on button click using forloop and substring() method.
var intp = document.querySelector("input");
var btn = document.querySelector("button");
var dv = document.querySelector("div");
btn.onclick = function() {
var b = intp.value;
for (var i = 1; i <= b.length; i++) {
var c = b.substring(0, i);
dv.innerHTML += c + "<br/>";
}
}
div{
width:400px;
background:#111;
color:yellow;
}
<input type="text">
<button>Click</button>
<br/><br/>
<div></div>
You have used a correct way for doing this, but as one of user suggest the start and end value of substring() was not correct.
I have a paragraph from which i want to delete a complete one string when user press single backspace.
For example like in yahoo mail. when we compose an email and write email address at "To or CC or BCC" section(s), when user press single backspace the complete email address is deleted.
I want that functionality but in paragraph.
Removing e-mail addresses on backspace is just a deletion of characters until you hit a space (or ; depends on your use case) char.
So basically what you are really asking here is:
How to substring the last portion of a string while the space character is the delimiter.
Here is a simple snippet as example:
EDIT:
I've updated the snippet to support caret (cursor) position while clicking the backspace or delete keys.
$('#delete').on('click', function(){
var $input = $('#mystring');
var nextStr = deleteUpToSpace($input.val());
$input.val(nextStr);
});
$('#mystring').on('keyup', function(e){
var currentCursorPoisitoin = this.selectionStart;
if(e.keyCode == 8 || e.keyCode == 46){ // backspace or delete keys
var $input = $(this);
var nextStr = deleteBasedOnPosition($input.val(), currentCursorPoisitoin);
$input.val(nextStr);
}
});
function deleteUpToSpace(str){
var index = str.lastIndexOf(" ");
var nextStr = str.substring(0, index);
return nextStr;
}
function deleteBasedOnPosition(str, position){
var strUpToPosition = str.slice(0, position);
var lastIndexOfSpace = strUpToPosition.lastIndexOf(" ");
var strToRemove = strUpToPosition.substring(lastIndexOfSpace, position);
var nextStr = str.replace(strToRemove, "");
return nextStr;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="mystring" value="this is a test string">
<button id="delete">Delete</button>
You probably want to remove a word when backspace is clicked.
You can use this code.
<!doctype html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
</head>
<body>
<textarea id="foo"></textarea>
<script type="text/javascript">
document.getElementById('foo').addEventListener("keydown",function(event){
if(event.code=="Backspace"){
var text=document.getElementById('foo').value;
var lastspace = text.lastIndexOf(" ");
var updateStr=text.substring(0,lastspace);
document.getElementById('foo').value=updateStr;
}
});
</script>
</body>
</html>
Firstly, you need to identify the separator that separates these different entities. For instance, if you need to remove the last sentence in a paragraph, the separator is the period (or full-stop, as some may call it).
Then, you can split the string by the separator, remove the last two elements (because the last element is essentially a non-completed) and then rejoin.
text.split('.').slice(0,-2).join('.') + '.'
If your separator was a period. Or generally,
text.split(separator).slice(0,-2).join(separator) + separator
See this JS Fiddle I made for demonstration: https://jsfiddle.net/tt24kfng/1/
An interesting thing you could try out would be to remove the last completed entity and keeping the last incompleted intact.
I have a similar problem to this post when trying to convert my apps script web app to use IFRAME Sandbox. I have converted to 'input = "button"' as suggested.
My web app is a simple form for students to use to sign in and out of a school library. The idea for the app is for it to be as easy as possible for students to use. Students should enter their id number and be able to either click the submit button or hit the enter key. Their ID is then validated before being stored in a spreadsheet and they get a message back saying thanks for signing in or out, or please enter a valid ID Number. Then focus should return to the text box and be cleared, ready for the next student to enter their id.
I had it working as described above using NATIVE mode. When I tried to convert it to IFRAME mode, clicking the button works, but if you hit the enter key everything just disappears and no data goes to the spreadsheet. How can I get hitting the enter key to work the same as clicking the submit button?
index.html code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<body>
<h3>Please Sign In & Out</h3>
<div id="box" class="frame">
<form id="signSheet" onsubmit="google.script.run
.withSuccessHandler(updateInfo)
.validateID(this.parentNode)">
<input type="text" name="myID" id="myID" placeholder="Enter your student ID" autocomplete="off">
<input type="button" value="Submit" onmouseup="google.script.run
.withSuccessHandler(updateInfo)
.validateID(this.parentNode)">
</form>
<span id="thank_you" hidden="true"></span>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<?!= include('javascript'); ?>
</body>
</html>
javascript.html code:
<script>
function updateInfo(ret){
if(ret[0]){
$( "#thank_you" ).removeClass("error");
$( "#thank_you" ).addClass("valid");
}
else{
$( "#thank_you" ).removeClass("valid");
$( "#thank_you" ).addClass("error");
}
$( "#thank_you" ).text(ret[1]);
$( "#thank_you" ).show("slow");
$( "#signSheet" )[0].reset();
$( "#myID" ).focus();
console.log(ret);
}
</script>
Code.gs code:
//spreadsheet key is needed to access the spreadsheet.
var itemSpreadsheetKey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
//Open the spreadsheet and get the sheet objects
var openedSS = SpreadsheetApp.openById(itemSpreadsheetKey);
var studentList = openedSS.getSheetByName("Student List");//Spreadsheet must match with sheet name
var studentRecord = openedSS.getSheetByName("Sign In-Out Record");
function doGet() {
var html = HtmlService.createTemplateFromFile('index').evaluate()
.setTitle('Sign In/Out Sheet')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
return html;
}
function include(filename) {
Logger.log('enter include');
Logger.log(filename);
var html = HtmlService.createHtmlOutputFromFile(filename).getContent();
Logger.log(html);
return html;
}
function validateID(form){
var idNum = form.myID;
var valid = false;
var numIdList = studentList.getLastRow()-1; //-1 is to exclude header row
//get the item array
var idArray = studentList.getRange(2,1,numIdList,1).getValues();
i= idArray.length;
while(i--){
if(idArray[i][0]==idNum & idNum!='') {
valid=true;
break;
}
}
if(valid)
return [1, updateRecord(idNum)];
else return [0, "ID number " + idNum + " not recognized. Please enter a valid ID number."];
}
function updateRecord(idNum){
studentRecord.appendRow([idNum]);
var formulas = studentRecord.getRange("B2:D2").getFormulasR1C1();
var lRow = studentRecord.getLastRow();
var range = studentRecord.getRange(lRow, 2, 1, 3);
range.setFormulas(formulas);
var vals = range.getValues();
var now = new Date();
studentRecord.getRange(lRow, 5, 1, 1).setValue(now);
now = Utilities.formatDate(now, "EST", "HH:MM a");
idNum = "Thanks " + vals[0][0] + ", you have signed " + vals[0][2] + " at " + now;
return idNum;
}
Update: I found this post and added the following code to javascript.html:
$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) {
var idVal = $("#myID").val();
google.script.run.withSuccessHandler(updateInfo).validateID(idVal);
return false;
}
});
})
This solved the the problem for me with a little more tweaking to parts of index.html and Code.gs
I found this post and added the following code to javascript.html:
$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) {
var idVal = $("#myID").val();
google.script.run.withSuccessHandler(updateInfo).validateID(idVal);
return false;
}
});
})
This listens for the enter key and sends the value of the text field to the apps script function. In this case I didn't need to use `event.preventDefault();'
Then I had to adjust the button's onmouseup function to take this.parentNode.myID and change my apps script function to take a value instead of a form object.
You must remove the onsubmit attribute from the <form> tag:
Currently you have:
<form id="signSheet" onsubmit="google.script.run
.withSuccessHandler(updateInfo)
.validateID(this.parentNode)">
Change it to this:
<form id="signSheet">
You already have a call to google.script.run in your button, so leave that.
I'm trying to make a program where if you for example type in "less" in the textarea the output should show "<". What is the best way to do this?
This is how far I've gotten:
<!doctype html>
<html lang="en">
<head>
<title>Group 7 - Deckcode to JavaScript</title>
</head>
<body>
<h1>Group 7 - Deckcode to JavaScript</h1>
<p>Input your deckode below:</p>
<textarea id="myTextarea"></textarea>
<button type="button" onclick="myFunction()">Translate</button>
<p id="demo"></p>
<script>
function myFunction() {
var input
if (myTextarea == "less") {
console.log("<");
}
}
</script>
</script>
</body>
</html>
You're trying to fish values out of the DOM incorrectly. Use document.getElementById to locate the element in the DOM, and take its value for the value you require.
function myFunction() {
var textAreaValue = document.getElementById("myTextarea").value;
if (textAreaValue == "less") {
console.log("<");
}
}
I suggest using an object like this:
var translations = {};
translations["less"] = "<";
translations["greater"] = ">";
And then in your function you do like this:
function myFunction() {
var value = document.getElementById("myTextarea").value;
console.log(translations[value] ? translations[value] : "No translation found");
}
It would also be easy to add more translations e.g. based on data from a database or similar.
as and alternative to IF-condition, you can use
if (textAreaValue.indexOf("less") > -1) {
console.log("<");
}
so if the text area contains "less" text then the console prints "<"
indexOf method
I don't know why search() function returns 0 for any input with SPECIAL CHARACTER, I wanted to find position of 1st occurrence of special character. When I am hardcoding the value for search() method it is working fine, but when I am taking value from text box it is not working properly.
Following is my HTML code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<input type="text" id="txt" onkeyup="return checkLength();"/>
<input type="button" id="btn" value="Verify" onclick="getValue()"/>
</body>
</html>
Following is the script where I have implemented the use of search() of Javascript, but don't know why I am getting 0 value for any input. Actually I wanted to find the position of first special character occurrence.
$(document).ready(function() {
$('#btn').attr('disabled',true);
$("#txt").bind({
paste : function(){
$('#btn').attr('disabled',false);
checkLength();
},
cut : function(){
checkLength();
}
});
});
function checkLength(){
var txtLength = $("#txt").val().length;
var banTxt = document.getElementById("txt").value;
if (txtLength != 0) {
if(isAlphaNumeric(document.getElementById("txt").value)) {
$('#btn').attr('disabled',false);
} else {
var str=banTxt;
//Here I am using search() to find position of Special Character.
var n=banTxt.search(/[^a-zA-Z ]/g);
alert("position of special char is: " + n);
var preTxt = banTxt.substring(0,(txtLength - 1));
var preTxtLength = preTxt.length;
alert("Special characters are not allowed!");
if(preTxtLength == 0){
$('#btn').attr('disabled',true);
document.getElementById("txt").value = "";
}else if(preTxtLength != 0){
document.getElementById("txt").value = preTxt;
$('#btn').attr('disabled',false);
}
}
} else {
$('#btn').attr('disabled',true);
}
}
function isAlphaNumeric(inputString) {
return inputString.match(/^[0-9A-Za-z]+$/);
}
function getValue(){
var txtValue = document.getElementById("txt").value;
alert("Value submitted is: " + txtValue);
}
var n=banTxt.search(/[^a-zA-Z ]/g);
I tried with string with special characters like 123#4$5 , 12#4 , etc. and I am getting alert as position of special char is: 0
That's just what your regex matches: No alphabet characters and no blanks - that includes digits. In contrast, your isAlphaNumeric function matches against /^[0-9A-Za-z]+$/ - you probably want to align them with each other.
Actually i have used the following line var n=banTxt.search(/[^a-zA-Z ]/g); for getting the position of special char, at the same time please note that i have used onkeyup event so if i am copy pasting the code i.e first ctrl then v, ctrl + v then ctrl itself is keyup event i think this might be the reason i am getting 0 as position of special char, as after pressing ctrl no text is pasted but onkeyup event is triggered.
I am looking for the solution of it.