Simple Javascript text box verification error - javascript

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()">

Related

HTML/Javascript keypad function isn't working

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">

Toggle div display in search bar

I'm trying to toggle a div display property using a search input. So far everything is working, however, when the search bar is empty, I want it to toggle back to display:none. I can't seem to get it to work, and do not want to use a button to achieve this. Is there a way to fire a function when the input becomes empty? Right now, the function is firing when the page loads, so my divs are starting out hidden. I'd like them to display when a their relative tag is input into the search bar, but to hide again when the input is empty or their exact tag is not in the input. Any help would be great!
Code:
function myFunction() {
var input = document.getElementById("Search");
var filter = input.value.toLowerCase();
var nodes = document.getElementsByClassName('connect-cat');
for (i = 0; i < nodes.length; i++) {
if (nodes[i].innerHTML.toLowerCase().includes(filter)) {
nodes[i].style.display = "block";
} else {
nodes[i].style.display = "none";
}
}
};
function check()
{
var isEmpty = $('Search').is(":empty");
$('#silent').toggle(isEmpty);
};
Input bar:
<input type="text" id="Search" onKeyup="myFunction();" Placeholder="Please enter a search term...">
The check function is firing at the top of the page:
$(document).ready(function()
{
check();
}
You should attach the event on the input field instead.
Try something like this:
$('#Search').change(function() {
var length = $(this).val().length;
if (length == 0) {
// hide div
}
});

Change color using querySelector

I'm following a Javascript tutorial using a book.
The exercise is change the background color in a <input type="search"> using document.querySelector. When I try to search something with no text in the search box, the background from <input> changes to red. I did it using onsubmit and some conditional. But in the next part, it must returns to white bckground using onfocus and I'm not getting.
The code that I tried is
document.querySelector('#form-busca').onsubmit = function() {
if (document.querySelector('#q').value == '') {
document.querySelector('#q').style.background = 'red';
return false;
}
}
document.querySelector('#form-busca').onfocus = function() {
document.querySelector('#q').style.background = 'white';
}
Can someone help me? Thanks a lot!
almost got it dude.
change:
document.querySelector('#form-busca').onfocus
to:
document.querySelector('#q').onfocus
revised code:
correct sample:
document.querySelector('#form-busca').onsubmit = function() {
if (document.querySelector('#q').value == '') {
document.querySelector('#q').style.background = 'red';
return false;
}
}
document.querySelector('#q').onfocus = function() {
document.querySelector('#q').style.background = 'white';
}
It sounds like you want the input's background color to change to white when the input element is focused.
Try changing your onfocus selector to:
document.querySelector('#q').onfocus ...
You want the onfocus handler to be on the #q element, not on #form-busca; the form's focus doesn't matter, you want to clear the background when the input element gains focus:
document.querySelector('#q').onfocus = function() { ... }
Try the following code:
// select
var h1 = document.querySelector("h1");
// manipulate
h1.style.color = "red";
This will make the color of h1 red.

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.

making text boxes visible

I have a drop down if i click it will retrieve values from db.If thre are 4 values that has to pass into text box and make it visible.If 5 values then 5 values has to get visible.There will be a count if 4 boxes count has to get into 5th box.if 5 values then count has to get int0 6th box.
How do i do it?
If the text boxes are in the markup and you've just hidden them (e.g., style="display: none"), you can show them again by setting their style.display property to "":
textBoxElement.style.display = "";
For example, here's a button click handler that looks for a text field to show and shows it; if there aren't any more to show, it hides the button:
var myForm = document.getElementById('myForm');
document.getElementById('btnShowField').onclick = function() {
var index, field, foundOne, foundMore;
foundOne = foundMore = false;
for (index = 0; index < myForm.elements.length; ++index) {
field = myForm.elements[index];
if (field.type === "text" && field.style.display === "none") {
if (!foundOne) {
// Found one, show it
field.style.display = "";
foundOne = true;
}
else {
// Found more, so we don't need to hide the button
foundMore = true;
break;
}
}
}
if (!foundMore) {
// No more hidden fields, hide the button
this.style.display = "none";
}
};
Live example
If you want to add more text boxes to a form at runtime when they aren't in the markup, you can easily do that:
var textBox = document.createElement('input');
textBox.type = "text";
textBox.name = "somename";
formElement.appendChild(textBox);
Live example
Usually the structure will be a bit more complex than that, but that's the general idea.
Off-topic: A lot of these things can be made dramatically easier by leveraging a JavaScript library like jQuery, Prototype, YUI, Closure, or any of several others. They'll smooth over browser differences and provide a lot of value-add functionality, so you can focus on what you're actually trying to do rather than browser quirks and such.

Categories

Resources