HTML/Javascript keypad function isn't working - javascript

I am making a page for a school project, and I am trying to make a keypad for a passcode system. However, I don't know how to get the keys to work. Looking it up, I have found multiple working keypads, however, I don't know what parts of their code I would have to add to my page to make it work.
The code that follows is currently what I have attached to the onclick part of each of the buttons:
<script>
function kpclick(){
var current = document.getElementById("tbInput").value;
var append = this.innerHTML;
if (current.length < 4) {
if (current=="0") {
document.getElementById("tbInput").value = append;
} else {
document.getElementById("tbInput").value += append;
}
}
}
</script>
The "tbInput" mentioned is a textbox underneath the keypad in the same div that later will be hidden and (hopefully) disabled. If there is no solution that allows the keypad to be used while the textbox is disabled, I will likely move it outside of the div the keypad is in.
When I press any of the buttons currently, nothing happens. What's happening here?

I'm assuming this is meant to be the button context. You can pass it with onclick="kpclick(this)".
function kpclick(target) {
var current = document.getElementById("tbInput").value;
var append = target.innerHTML;
if (current.length < 4) {
if (current == "0") {
document.getElementById("tbInput").value = append;
} else {
document.getElementById("tbInput").value += append;
}
}
}
<button onclick="kpclick(this)">0</button>
<button onclick="kpclick(this)">1</button>
<input id="tbInput">

Related

How can I simulate a keypress event specifically inside of a JS textbox?

I am working on a cheat/tweak program for online school. Currently am trying to fix the "vocab completer".
Essentially the problem is that I cannot get the text box to submit the word it contains. I can have it typed in but until I personally click and press enter on the textbox it will not submit. I believe all of the selectors are correct, I am just not sure how I can convince the textbox to submit. I do not think that this is a very difficult thing to do, just that I am not understanding something about events.
How can I simulate a keypress event specifically inside of a JS textbox such that it's indistinguishable from actually having done it.
Find what word is meant to be typed
function vocabCompleter() {
var i = 0;
try{
var txt = window.frames[0].document.getElementsByClassName("word-background")[0].value
} catch{txt=""}
var speed = 50;
Types word out, could be just value = txt but this looks better
function typeWriter() {
if (window.frames[0].document.getElementsByClassName("word-textbox")[0].value.length <
txt.length) {
window.frames[0].document.getElementsByClassName("word-textbox")[0].value += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
}
if (txt.length > 3){
typeWriter();
Ways I have tried to get the textbox to submit (also, .focus, .trigger)
window.frames[0].document.getElementsByClassName("word-textbox")[0].click()
window.frames[0].document.getElementsByClassName("word-textbox")[0].dispatchEvent(new
KeyboardEvent('keypress',{'key':'Enter'}));
}
Other buttons to be clicked
output += ("Vocab Completer, ")
if (document.getElementById("activity-title").innerText == "Vocabulary") {
$("#stageFrame").contents().find(".playbutton.vocab-play")[0].click()
$("#stageFrame").contents().find(".playbutton.vocab-play")[1].click()
try {
if (window.frames[0].document.getElementsByClassName("word-textbox")[0].value.length = txt.length){
$("#stageFrame").contents().find(".uibtn.uibtn-blue.uibtn-arrow-next")[0].click()
}
} catch (TypeError) {}
}
}

Simple Javascript text box verification error

I'm trying to check whether the length of characters typed into the text box is less than 6, and if it is, I want its background to be red. Unfortunately, I can't seem to figure out where I'm going wrong with this simple problem.
var textBox = getElementsByName('random');
function checkLength() {
if (textBox.value.length < 6) {
textBox.style.backgroundColor = "red";
}
}
<input type="text" name="random" onfocus="checkLength();">
A few issues in your code:
you need to put <script> code at the end, so that DOM is loaded and ready before you access elements in it.
getElementsByName('random') needs to document.getElementsByName('random'), which will actually return a list so you need to get first element from the list.
Also logically, you need to remove the red background once the text
length in input exceeds 6 and it would be better if you attach function to oninput event.
<input type="text" name="random" oninput="checkLength();">
<script type="text/javascript">
var textBox = document.getElementsByName('random')[0];
function checkLength() {
if (textBox.value.length < 6) {
textBox.style.backgroundColor = "red";
} else {
textBox.style.backgroundColor = "white";
}
}
</script>
When the page first loads, the element with a name of random doesn't exist.
You will need to initialise your textBox global after the page loads.
You can do this by replacing
var textBox = document.getElementsByName("random")[0]
with
var textBox;
window.onload = function() {
textBox = document.getElementsByName("random")[0]
}
Try this
// add an id of "random" to your input
function checkLength() {
const textBox = document.getElementById("random")
if (textBox.value.length < 6) {
textBox.style.backgroundColor = "red";
} else {
textBox.style.backgroundColor = "white";
}
}
Working example: http://jsbin.com/caseqekusi/1/edit?html,js,output
Note: If you want the box to be red right away, you'll have to modify it a bit, let me know if you have questions.
I would suggest to use oninput as well, so it updates as you type and marks the field as "valid" as soon as you have reached a certain length.
You could also get rid of var textbox = ... by using document.activeElement. It makes your function reusable for other input fields. And it no longer matters when your code is loaded.
function checkLength() {
// Get current focused element
const textBox = document.activeElement;
if ( !textBox.value || textBox.value.length < 6 ) {
textBox.style.backgroundColor = "red";
}
else {
textBox.style.backgroundColor = "#fff";
}
}
<input type="text" name="random" onfocus="checkLength()" oninput="checkLength()">

Getting Text out of HTML into Javascript as a Function with Input Changing IDs

I am trying to create an if/else statement that checks the text of a button that the user presses. If there is no text in that button, it continues the function, if there is pre-existing text then it gives an alert stating that there is already an entry there.
Essentially, the user clicks a button and the code checks to see if that button is empty or not. However, since the button's ID is constantly changing, I don't know how to tell the code to check the pressed button. I feel that using 'this' is part of the solution to this problem, but I am too new to JavaScript to use it correctly.
This is my entire JavaScript code, off it works fine except for the two lines that have comments in them. I am trying to make the variable "inSquare" to equal the text from the button that triggered the function. Then it goes on to check the text of the variable, but currently all it does is fail the if and head straight to the else.
var turnNumber = 9;
var whoseTurn;
var inSquare;
function currentTurn(id) {
inSquare = this.innerHTML; /*This Line*/
if (inSquare === "") { /*This Line*/
if (whoseTurn === 0) {
id.innerHTML = "X";
turnNumber -= 1;
whoseTurn = turnNumber % 2;
} else {
id.innerHTML = "O";
turnNumber -= 1;
whoseTurn = turnNumber % 2;
}
} else {
window.alert("Something is already in that square!");
}
}
Also, here is an example of what the HTML buttons look like. (There are nine total, but they are all formatted the same).
<button id="topLeft" onclick="currentTurn(this)"></button>
<button id="topMid" onclick="currentTurn(this)"></button>
<button id="topRight" onclick="currentTurn(this)"></button>
inSquare = this.innerHTML; should be inSquare = id.innerHTML;
this in your function refers to the window object, but you want to refer to the element you passed, which you provided as the id argument of the function.

Shift + Click to Select a Range of Checkboxes

I have large tables being generated and each row has a checkbox, class "chcktbl".
In the table header, there is a Select All checkbox, class "chckHead".
The select/deselect all function works fine, as does the count of selected charts I have displayed in the table heading.
The function to enable shift+click capability to select a range of checkboxes also works, but in its current format, only selects 10 checkboxes before generating an error message in a popup window:
"Stop running this script? A script on this page is causing your web browser to run slowly. If it continues to run, your computer might become unresponsive."
<script type=text/javascript>
//select all button
$('#chckHead').click(function() {
if (this.checked === false) {
$('.chcktbl:checked').attr('checked', false);
}
else {
$('.chcktbl:not(:checked)').attr('checked', true);
}
countSelected();
});
//count number of boxes checked
function countSelected() {
var numCharts = $('input.chcktbl:checked').length;
$('#numCharts').html(numCharts);
}
//SHIFT+Click to select a range of checkboxes:
// this variable stores the most recently clicked checkbox
// it is used for shift-clicks
var lastClickedBox = 0;
// the checkbox functionality is default to the browser
$('.chcktbl').click(function(event) {
var clickedBox = $('.chcktbl').index(event.target);
if(event.shiftKey) {
setCheckboxes(lastClickedBox, clickedBox);
};
lastClickedBox = clickedBox;
countSelected();
});
// sets all the checkboxes between the specified indices to true
function setCheckboxes(end, start) {
if(start > end) {
var temp = start;
start = end;
end = temp;
};
for(var i = start; i < end; i++) {
$('.chcktbl').eq(i).prop('checked', true);
};
countSelected();
};
</script>
This is a really common feature for selecting a range of items with one click, but I can't find an efficient way to do it. If anyone knows a better way of approaching this or can spot some inefficiency in the code then please let me know.
How about using jquery nextUntil?
I didn't actually test this but this should give you the basic idea and it removes the for loop. I created similar functionality to this before using nextUntil/prevUntil and never got an unresponsive page.
function setCheckboxes(end, start) {
if(start > end) {
var temp = start;
start = end;
end = temp;
};
$('.chcktbl').eq(start).nextUntil(':eq('+(end+1)+')').add().prop('checked', true);
countSelected();
};
I tried you code and it worked well for me. You might want to try this jquery plugin
https://gist.github.com/DelvarWorld/3784055

Calling a function when checking a checkbox, onclick event doesn't fire when unchecking

I should probably start by mentioning that I am using Internet Explorer 6. I am calling a JavaScript function (tabModifiedHighlight) from an onChange event. The function works perfectly other places however, I have a couple of places on the page where it works when I check the checkbox, but the event doesn't even seem to fire when I uncheck it.
Here is the JavaScript function:
function tabModifiedHighlight(){
alert("alert");
var div, i, input, inputIndex, selects, selectIndex, selectedTab, highlighted;
var tabs = new Array("admissioninformation","diet","vitalsigns","activities","nursing","ivfluids","medications1","medications2","labs","respiratory","diagnostic","consultations");
for(i=0; i<(tabs.length); i++){
selectedTab = tabs[i]+'tab';
if (document.getElementById(selectedTab).className == "selectedtab"){
div = document.getElementById(tabs[i]),
input = div.getElementsByTagName('input'),
selects = div.getElementsByTagName('select');
break;
}
}
highlighted = false;
for (inputIndex = 0; inputIndex < input.length; inputIndex++){
if (input[inputIndex].checked == true){
highlighted = true;
}
}
for (inputIndex = 0; inputIndex < input.length; inputIndex++){
if (input[inputIndex].type == 'text' && input[inputIndex].value != ""){
highlighted = true;
}
}
for (selectIndex = 0; selectIndex < selects.length; selectIndex++){
if (selects[selectIndex].value != ""){
highlighted = true;
}
}
if (highlighted == true){
document.getElementById(selectedTab).style.backgroundColor = "#FF0";
}
else {
document.getElementById(selectedTab).style.backgroundColor = "#F0F0F0";
}
}
And here is the input that is calling it:
<input name="cbMedTylenolPO" id="cbMedTylenolPO" type="checkbox" value="PO" onClick="tylenolPoShowHide(); checkBoxHighlight(this, 'MedicationsRow2'); tabModifiedHighlight();" />
This page has multiple "tabs" which are just divs that are set to visible or hidden based on which one is selected. It seems consistent in that it works everywhere except for 2 of the tabs, and nowhere on those tabs. The only other difference I can see is that the ones that are not working are also showing or hiding divs within the tab, based on whether the checkbox is checked or not. I have added the alert at the very beginning of the function to see if it is firing or not, and it does when checking the checkbox, but not when unchecking.
I hope I made this clear, and any thoughts are appreciated!
As your code is not working only for two tabs, and working for all others its not an browser compatibility issue.
onClick if checkbox you are calling these 3 methods
tylenolPoShowHide(); checkBoxHighlight(this, 'MedicationsRow2');tabModifiedHighlight()
Note tabModifiedHighlight is last one..
if any of first two methods tylenolPoShowHide or checkBoxHighlight fails... then tabModifiedHighlight will not be called.
I will suggest to add alert as first and last line in both tylenolPoShowHide and checkBoxHighlight ...
It will help you find which one is actually failing then you can add that code here and we will be able to help you further

Categories

Resources