Currently am having a form which detects the user input text and prints the respective text,but my issue is if user want to input as ctrl key how can i accomplish that
For example :
If user presses key a it will get displayed,but at the same time if user press cntrl key it should also get displayed.
Fiddled here.
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<div ng-app="">
<p>Choose your control</p>
<p>Option : <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>
Thanks
Here is you answer for control key detect with angular JS:
angular.module("mainModule", [])
.controller("mainController", function ($scope)
{
// Initialization
$scope.onKeyDownResult = "";
$scope.onKeyUpResult = "";
$scope.onKeyPressResult = "";
// Utility functions
var getKeyboardEventResult = function (keyEvent, keyEventDesc)
{
return keyEventDesc + " (keyCode: " + (window.event ? keyEvent.keyCode : keyEvent.which) + ")";
};
// Event handlers
$scope.onKeyDown = function ($event) {
if($event.keyCode === 17)
{
$scope.name += " ctrl ";
$scope.onKeyDownResult = getKeyboardEventResult($event, name);
}
else if($event.keyCode === 16)
{
$scope.name += " shift ";
$scope.onKeyDownResult = getKeyboardEventResult($event, name);
}
else if($event.keyCode === 18)
{
$scope.name += " Alt ";
$scope.onKeyDownResult = getKeyboardEventResult($event, name);
}
else
{
$scope.onKeyDownResult = getKeyboardEventResult($event, name);
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script>
</head>
<body ng-app="mainModule">
<div ng-controller="mainController">
<label>Type something:
<input type="text"
ng-keydown="onKeyDown($event)"
ng-model="name" />
</label><br />
<p>KEY DOWN RESULT:<p>{{name}}<br />
</div>
</body>
</html>
Hope it helps.
See AngularJS keyboard events: http://www.angularjshub.com/examples/eventhandlers/keyboardevents/
You can capture keycodes by using these events on input box:
<input type="text"
ng-keydown="onKeyDown($event)"
ng-keyup="onKeyUp($event)"
ng-keypress="onKeyPress($event)" />
Try to use "ng-keypress=check($event)", the $event object have "keyCode", check the keyCode and update your model inside the function.
Ctrl is keycode 17. So inside your function you will check specific keys like this: if($event.keyCode === 17){ $scope.model += " ctrl" };
You can see all keycodes here: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
Related
I'm a beginner and I'm trying to help some special education students with a very basic budget calculator. I've seen similar questions to mine posted, but when I try those methods something always breaks and I'm having some trouble figuring it out.
Basically I need the onclick portion of the button that calls the function into action to actually respond to the enter key and not a click :-( Thank you very much in advance for any help that might be provided!!
<script>
function addTwoNumbers () {
var number1 = document.getElementById('box1').value;
var number2 = Number(document.getElementById('box2').value);
var sum = Number(number1) + number2;
document.getElementById('resultBox').value = sum;
if(sum<0) {
document.getElementById('resultBox').style.color = "red";
}
else{
document.getElementById('resultBox').style.color = "green";
}
document.getElementById('resultBox').style.visibility = 'visible';
document.getElementById('resultBox').value = sum
}
</script>
<script>
function subtractTwoNumbers () {
var number1 = document.getElementById('box1').value;
var number2 = Number(document.getElementById('box2').value);
var difference = Number(number1) - number2;
document.getElementById('resultBox').value = difference;
if(difference<0) {
document.getElementById('resultBox').style.color = "red";
}
else{
document.getElementById('resultBox').style.color = "green";
}
document.getElementById('resultBox').style.visibility = 'visible';
document.getElementById('resultBox').value = sum
}
</script>
<script>
function clearall() {
document.getElementById('box1').value = "";
document.getElementById('box2').value = "";
document.getElementById('resultBox').value = "";
}
</script>
<div id='calc' align="center"></div>
<h1>Calculator</h1>
<p>Enter budget <input type="text" id="box1"></p>
<p>Enter price <input type="text" id="box2"></p>
<p>Press the equation key to see your results</p>
<div class="btn-group" style="width:100%">
<button style="width:33.3%" onclick="addTwoNumbers()">+</button>
<button style="width:33.3%" onclick="subtractTwoNumbers()">-</button>
<p>
<button style="width:67.5%" onclick="clearall()">clear</button>
</div>
<h3>Do you have enough?</h3>
<input type="text" id="resultBox"> <br/>
Instead of using the onclick attribute in the HTML, a more modern approach would be to create an event listener in your javascript.
I would give the buttons an ID. Then do something like this:
document.getElementById("clearBtn").addEventListener("click", clearAll);
There are all kinds of events you can listen for and I would guess you could find one that provides the behavior you are after.
hi on my website i've a comment box,
everytime i post a comment it get posted below the last comment
my question is: how do i place new comments on top of the old ones.
website: kru.run
This is my full code right now,
<textarea id="title1" type="text " rows="1" cols="15" onkeyup="Allow()" placeholder="username"></textarea>
<textarea id="title" type="text " rows="3" cols="125" onkeyup="Allow()" placeholder="write a comment..."></textarea>
<input type="submit" value="Send" onclick="insert()" style="width:50px;" /></form>
</div>
<div id="display"></div>
<script type="text/javascript">
var titles = [];
var titleInput = document.getElementById("title");
var titleInput1 = document.getElementById("title1");
var messageBox = document.getElementById("display");
function Allow() {
if (!user.title.value.match(/[a-zA-Z]$/) && user.title.value != "") {
user.title.value = "";
alert("Please Enter only alphabets");
}
window.location.reload()
}
function insert() {
titles.push(titleInput1.value + ": " + titleInput.value);
clearAndShow();
}
function clearAndShow() {
titleInput.value = "";
messageBox.innerHTML = "";
messageBox.innerHTML += " " + titles.join("<br/> ") + "<br/>";
}
</script>
</div>
</div>
</div>
<br><br>
specifically
i think the insert function is the problem
what can i use instead of push?
function insert () {
titles.push(titleInput1.value + ": " + titleInput.value);
clearAndShow();
}
try:
function insert () {
titles.unshift(titleInput1.value + ": " + titleInput.value);
clearAndShow();
}
to insert as first item.
Please I need help. I have the same need of this post. I followed the instructions but I can't find my error. I'm frustratred.
When I submit with null fields, the script shows me a blank page.
When I submit with complete fields, the script shows me a blank page also and never upload the file.
This is my final code:
code.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(form) {
try {
var dropbox = "NHD Papers";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var blob = form.myFile;
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + form.myName + ", Division: " + form.myDivision + ", School: " + form.mySchool + ", State: " + form.myState);
return "<h2>File uploaded successfully!</h2><p>Copy and paste the following URL into registration:<br /><br /><strong>" + file.getUrl() + '</strong></p>';
} catch (error) {
return error.toString();
}
}
form.html
<p>
<form id="myForm" onsubmit="validateForm();">
<h1>NHD Paper Upload</h1>
<label>Name</label>
<input type="text" name="myName" class="required" placeholder="Enter your full name..">
<label>Division</label>
<input type="text" name="myDivision" class="required" placeholder="(ex. Junior or Senior)">
<label>School</label>
<input type="text" name="mySchool" class="required" placeholder="Enter your school..">
<label>Affiliate</label>
<input type="text" name="myAffiliate" class="required" placeholder="Enter your affiliate..">
<label>Select file to upload. </label>
<input type="file" name="myFile">
<input type="submit" value="Submit File" >
<br />
</form>
</p>
<div id="output"></div>
<script>
function validateForm() {
var x=document.getElementsByClassName('required');
for(var i = 0; i <x.length; i++){
if (x[i].value == null || x[i].value == "")
{
alert("All fields must be filled out.");
return false;
}
this.value='Please be patient while your paper is uploading..';
var myFormObject = document.getElementById('myForm');
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(myFormObject);
}
}
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
<style>
input { display:block; margin: 15px; }
p {margin-left:20px;}
</style>
Regards,
In the IFRAME mode HTML forms are allowed to submit, but if the form has no action attribute it will submit to a blank page.
The solution suggested by the official documentation is to add the following JavaScript code to prevent all form submitions on load:
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
</script>
You can also add a return false; or event.preventDefault() at the end of your validateForm() function.
I've been trying to implement the new "Drag and Drop" file and upload feature, using the code from SitePoint.com. I am using Struts Framework as well. FormFile made my uploads easier, I could just hit on "choose" and click away. But, I just can't seem to get it to work the DnD with Struts. The ActionForm validates and reports that the file size is 0! Here's the code from SitePoint.com (js):
(function() {
// getElementById
function $id(id) {
return document.getElementById(id);
}
// output information
function Output(msg) {
var m = $id("messages");
m.innerHTML = msg + m.innerHTML;
}
// file drag hover
function FileDragHover(e) {
e.stopPropagation();
e.preventDefault();
e.target.className = (e.type == "dragover" ? "hover" : "");
}
// file selection
function FileSelectHandler(e) {
// cancel event and hover styling
FileDragHover(e);
// fetch FileList object
var files = e.target.files || e.dataTransfer.files;
// process all File objects
for (var i = 0, f; f = files[i]; i++) {
ParseFile(f);
UploadFile(f);
}
}
// output file information
function ParseFile(file) {
Output(
"<p>File information: <strong>" + file.name +
"</strong> type: <strong>" + file.type +
"</strong> size: <strong>" + file.size +
"</strong> bytes</p>"
);
// display an image
if (file.type.indexOf("image") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
Output(
"<p><strong>" + file.name + ":</strong><br />" +
'<img src="' + e.target.result + '" /></p>'
);
}
reader.readAsDataURL(file);
}
// display text
if (file.type.indexOf("text") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
Output(
"<p><strong>" + file.name + ":</strong></p><pre>" +
e.target.result.replace(/</g, "<").replace(/>/g, ">") +
"</pre>"
);
}
reader.readAsText(file);
}
else{
var reader=new FileReader();
reader.readAsDataURL(file);
}
}
// upload JPEG files
function UploadFile(file) {
var xhr = new XMLHttpRequest();
if (xhr.upload) {
// create progress bar
var o = $id("progress");
var progress = o.appendChild(document.createElement("p"));
progress.appendChild(document.createTextNode("upload " + file.name));
// progress bar
xhr.upload.addEventListener("progress", function(e) {
var pc = parseInt(100 - (e.loaded / e.total * 100));
progress.style.backgroundPosition = pc + "% 0";
}, false);
// file received/failed
xhr.onreadystatechange = function(e) {
if (xhr.readyState == 4) {
progress.className = (xhr.status == 200 ? "success" : "failure");
}
};
// start upload
xhr.open("POST", $id("upload").action, true);
xhr.setRequestHeader("X_FILENAME", file.name);
xhr.send(file);
}
}
// initialize
function Init() {
var fileselect = $id("fileselect"),
filedrag = $id("filedrag"),
submitbutton = $id("submitbutton");
// file select
fileselect.addEventListener("change", FileSelectHandler, false);
// is XHR2 available?
var xhr = new XMLHttpRequest();
if (xhr.upload) {
// file drop
filedrag.addEventListener("dragover", FileDragHover, false);
filedrag.addEventListener("dragleave", FileDragHover, false);
filedrag.addEventListener("drop", FileSelectHandler, false);
filedrag.style.display = "block";
}
}
// call initialization file
if (window.File && window.FileList && window.FileReader) {
Init();
}
})();
The jsp (just messing around):
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Upload File</title>
<link href="css/styles.css" rel="stylesheet" type="text/css" media="all"/>
</head>
<body>
<form id="upload" action="../Repositore/upload_file.do" method="POST" enctype="multipart/form-data">
<fieldset>
<legend>File Upload Form</legend>
<input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="20000000" />
<div>
<label for="fileselect">File to upload:</label>
<input type="file" id="fileselect" name="file" multiple="multiple" />
<div id="filedrag">or drop files here</div>
</div>
<div>
<table border='0' cellpadding='2'>
<tr><td><label for="ftags">Tags:</label></td><td> <input type='text' id="ftags" name='tags'/></td><td>(Separate by commas)</td></tr>
<tr><td><label for="desc">Description:</label></td><td> <textarea name="description" id="desc" rows="5" cols="30"></textarea></td></tr>
<tr><td><input type="checkbox" name="comment">Yes</input></td></tr>
</div>
<div id="submitbutton">
<button type="submit">Upload file</button>
</div>
</fieldset>
</form>
<div id="progress"></div>
<div id="messages">
<p>Status:</p>
</div>
<script src="js/filedrag.js" type="text/javascript"></script>
What could be wrong? Help?
Here i'm attempting to load a form using ajax and set to "maindiv" upon clicking a button "Add Item".but returns undefined. A servlet named "AddItem" also exists..
html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<input type="button" onclick="loadAddItemForm()" value="Add Item"/>
<div id="maindiv"> </div>
<script>
function loadAddItemForm() {
var x;
if (window.XMLHttpRequest) {
x = new XMLHttpRequest();
}
x.onreadystatechange = function () {
if (x.readyState == 4 && x.status == 200) {
//
var txt = "ItemCode:" + "<input type='text' id='itemcodetxt'><br>" + "ItemName:" + "<input type='text' id='itemnametxt'><br>" + "Description:" + "<input type='text' id='descriptiontxt'><br>" + "QtyOnHand:" + "<input type='text' id='qtyonhandtxt'><br>" + "Reorderlevel:" + "<input type='text' id='reorderleveltxt'><br>" + "Unit price:" + "<input type='text' id='unitpricetxt'><br><input type='button' value='Add' onclick='addItem()'/>";
}
document.getElementById("maindiv").innerHTML = txt;
};
x.open("GET", "AddItem", true);
x.send();
}
</script>
</body>
You're not passing in the page, try
x.open("GET", "AddItem.html", true);
assuming that's the page you waant to open.
it's returning false because it's looking for AddItem, and as it's returning false the txt is undefined as the if block isn't executed