HTML/JS Text recognition variable displayer - javascript

I cannot get the <div id="output"> section to display the variable txtOutput or maybe the variable txtOutput is not being defined or changed.
I would appreciate help on re-defining this variable or how to display it. (the empty text box feature works though)
function smartinput() {
var txtInput = document.forms["form"]["inputA"].value;
var txtOutput;
var input = txtInput.value;
if (txtInput == null || txtInput == "") {
alert("Please put text in Input");
return false;
} else if (txtInput == "Hi") {
return output.value = "Hello";
}
document.getElementByID("Output").innerHTML = txtOutput;
}
<p><strong>Note:</strong> The output element is not supported in Edge 12 or Internet Explorer and earlier versions.</p>
<h1> Smart Responder Test 1 </h1>
<form name="form">
<fieldset>
<label> Input: </label>
<textarea cols="30" rows="2" name="inputA" id="txtInput"></textarea>
<p></p>
<input type="button" value="Submit" onclick="smartinput()" />
<p></p>
<label>Output: </label>
<div id="Output"></div>
</fieldset>
</form>

Firstly, you made a typo for method getElementById, correct that.
Secondly, you are defining variable txtOutput but not using it later, rather you use output. Just change output to txtOutput:
function smartinput() {
var txtInput = document.forms["form"]["inputA"].value;
var txtOutput;
var input = txtInput.value;
if (txtInput == null || txtInput == "") {
alert("Please put text in Input");
return false;
} else if (txtInput == "Hi") {
txtOutput= "Hello";
}
document.getElementById("Output").innerHTML = txtOutput;
}
And you don't need txtOutput.value because it is only a variable for result.

Some errors
you should put getElementById in place to ...byID
If it is empty or null, just put it like this !(elem or value)
The output element is not a text area so value will not work. Change it to innerHTML or innerText
TxtInput and input are the same in your code
function smartinput() {
var txtInput = document.forms["form"]["inputA"];
var input = txtInput.value;
var output = document.getElementById("Output");
if (!input) {
alert("Please put text in Input");
return false;
} else if (input == "Hi") {
return output.innerHTML = "Hello";
}
}
<p><strong>Note:</strong> The output element is not supported in Edge 12 or Internet Explorer and earlier versions.</p><h1> Smart Responder Test 1 </h1><form name="form"><fieldset><label> Input: </label><textarea cols="30" rows="2" name="inputA" id="txtInput"></textarea><p></p><input type="button" value="Submit" onclick="smartinput()" /><p></p><label>Output: </label><div id="Output"></div></fieldset></form>

Related

JavaScript function/event listener not functioning properly

I'm completely new to JavaScript, and don't know why this isn't working. When I click on the input box, and type in less than 5 characters, i want a message to display. The message is simply not showing. Source code: https://jsfiddle.net/015por64/
<html>
<body>
<form id="form>">
<input id="input">
<div id="text"> Test </div>
</input>
</form>
</body>
</html>
<script>
function checkUserName(e, minLength) {
var username = document.getElementById("input");
var usernameLength = username.textContent;
if (usernameLength.value.length < 5) {
msg = "Your username must consist of at least five characters."
};
else {
msg = "";
text.innerHTML=msg
};
}
var text = document.getElementById("text");
text.addEventListener("blur", function(e) {checkUserName(e, 5)}, false)
</script>
Few issues with your code:
you need to attach the event to #input and not the div#text.
you need to read value of #input and not textcontent
; after if is wrong because then else will give syntax error.
<html>
<body>
<form id="form>">
<input id="input">
<div id="text"> Test </div>
</input>
</form>
</body>
</html>
<script>
function checkUserName(e, minLength) {
var username = document.getElementById("input");
var usernameLength = username.value;
if (usernameLength.length < 5) {
msg = "Your username must consist of at least five characters.";
text.innerHTML=msg;
}else {
msg = "";
text.innerHTML=msg;
};
}
var text = document.getElementById("text");
document.getElementById('input').addEventListener("blur", function(e) {checkUserName(e, 5);}, false)
</script>
It should be the input where you have to put the blur event listener.
var input = document.getElementById("input");
And since you have no use for text outside the function, better define it inside.

what is the correct way to validate form with javascript

should i put "submit" instead "form_name" in the last block of code? what is the correct way?
thanks!
function check() {
var title = document.getElementById("title");
var content = document.getElementById("content");
if (title == "") {
alert("title is required");
return false;
}
if (content == "") {
alert("content is required");
return false;
}
var submit = document.getElementById("form_name");
submit.submit();
}
this is my form
<form action="#" method="post" id="form_name" name="form_name">
<input type="text" name="title" id="title" />
<textarea name="content" id="content" cols="30" rows="10"></textarea>
<input type="submit" value="Submit" id="submit" name="submit" onclick="return check();"/>
</form>
First you are selecting an element and acting like it is the value
var title = document.getElementById("title"); <-- DOM element
if (title == "") { <-- checking the DOM against a string.
You should be using .value to get what was entered.
Next you are submitting the form.... but you clicked on a submit button inside of the form so that will submit the form. So that is not needed.
function check() {
var title = document.getElementById("title").value;
var content = document.getElementById("content").value;
if (!title.trim().length) {
alert("title is required");
return false;
else if (!content.trim().length) {
alert("content is required");
return false;
}
return true
}
And never name anything submit, it just leads to problems.
In most recent browsers you have more power to use
function myFunction() {
var inpObj = document.getElementById("id1");
if (inpObj.checkValidity() == false) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
}else{
document.getElementById("demo").innerHTML = "";
}
}
<input id="id1" type="number" min="100" max="300" required>
<button onclick="myFunction()">OK</button>
<p id="demo"></p>
Reference:
https://www.w3schools.com/js/js_validation_api.asp

Autofocus on input and accept letters, digits and scanned barcodes

I have to accept either input from keyboard or 2d barcode scanner.
The input is mixture of alpha numeric, also I want user to be able to use Ctrl+v to paste their input. Currently if I try Ctrl+v, only v key is detected and shown.
Also my cursor autofocus does not work, no matter what I try.
See below the javascript.
<script>
var codes = "";
var codes_el = document.getElementById('codes');
var output_el = document.getElementById('output');
function process_key(event) {
var letter = event.key;
if (letter === 'Enter') {
event.preventDefault();
letter = "\n";
event.target.value = "";
}
// match numbers and letters for barcode
// if (letter.match(/^[a-z0-9]$/gi)){
if (letter.match(/^[a-z0-9\n-]$/gi)) {
codes += letter;
}
codes_el.value = codes;
output_el.innerHTML = codes;
}
</script>
<script>
function testAttribute(element, attribute) {
var test = document.createElement(element);
if (attribute in test) {
return true;
} else
return false;
}
window.onload = function() {
if (!testAttribute('input', 'autofocus'))
document.getElementById('codes').focus();
//for browser has no autofocus support, set focus to Text2.
}
</script>
and here is the html part.
Formatted HTML:
<div class="barcode_box">
<br>
<form method="POST" action="scanned.php">
<input onkeydown="process_key(event)" />
<input type="submit" value="Submit" />
<input type="hidden" name="codes" id="codes" autofocus/>
</form>
<pre id="output">
</pre>
<br>
</div>

Javascript form validation highlight invalid character

I'm just working on some really basic form validation with JS. I don't want users to be able to use any special characters on input fields as a layer of defense against XSS exploits.
I've got the basic validation down and it seems to work ok but it just says there is an error and I would like to highlight the invalid character. here is my code.
HTML
<head><meta charset="UTF-8"><script src="script.js"></script></head>
<body>
<form method="post" action="test.php" onsubmit="return validate()">
<p><input type="text" id="userName" placeholder="Username or Email"></p>
<p><input type="password" id="userEmail" placeholder="Password"></p>
<p><input type="submit" id="submit" value="Login"></p>
</form>
<input type="button" value="debug" onclick="debug()">
<p id="errorText"></p>
<p id="debug"></p>
</body>
Javascript
<script>
function validate() {
var userName = document.getElementById('userName').value;
var userEmail = document.getElementById('userEmail').value;
var invalidChars = "!,#,#,$,%,^,&,*,(,),<,>,/,~,`";
var mergeFields = userName.concat(userEmail);
var found = "false";
var invCharsArr = invalidChars.split(",");
var fieldsArr = mergeFields.split("");
var nameErr = "false";
var emailErr = "false";
for (var i = 0; i < fieldsArr.length; i++) {
if (invCharsArr.indexOf(fieldsArr[i]) > -1) {
found = "true";
break;
}
}
if (found == "true") {
document.getElementById('errorText').innerHTML = "You used an invalid character";
return false;
}
else {
if (userName == "" || userName == null) {
document.getElementById('userName').style.backgroundColor = "red";
document.getElementById('errorText').innerHTML = "Field Errors are Highlighted in Red";
nameErr = "true";
return false;
}
else if (userEmail == "" || userEmail == null) {
document.getElementById('userEmail').style.backgroundColor = "red";
document.getElementById('errorText').innerHTML = "Field Errors are Highlighted in Red";
emailErr = "true";
return false;
}
else {
return true;
}
}
}
</script>
On a side note I am still a beginner with javascript, if there is anything here that I can do better please let me know I would like to learn. Thanks
You can show an error message under the input marking some chars by wrapping them in spans. Doing this on a input field is not possible as far as I know.
<div class="error">Invalid chars in: <span class="mark">#</span>test</div>.
As already mentioned you should not rely on javascript validation only. It mainly helps to prevent sending unnecessary false requests to the server.

Get input from textbox and write it below

I need to take the value from an input box and write it below the input box on the click of a button. I thought to use a label but if there is another way I am open to suggestions.
My code so far:
<h1>Test</h1>
<form name="greeting">
Type your name here: <input type = "Text" name="fullname" id="name"> <button onclick="getName()">Create</button><br>
Hello <label id="greet">Hello</label>
</form>
<script lang="javascript">
function getName() {
var inputVal = document.getElementById("name").value;
if (inputVal == "") {
document.getElementById("name").style.backgroundColor = "red";
}
else {
document.write("Hello " + document.getElementById("name"));
}
First of all, you don't want to submit a form, so change button type from "submit" (default) to "button".
Then you should not use document.write almost never, it's used in very specific cases. Use proper DOM manipulation methods like appendChild. I would use convenient insertAdjacentHTML:
function getName() {
var input = document.getElementById("name");
if (input.value == "") {
input.style.backgroundColor = "red";
} else {
input.insertAdjacentHTML('afterend', '<div>' + input.value + '</div>');
}
}
<form name="greeting">Type your name here:
<input type="Text" name="fullname" id="name" />
<button type="button" onclick="getName()">Create</button>
<br>Hello
<label id="greet">Hello</label>
</form>
First you need to stop your form from submitting. Second you should not use document.write, since it will not append the text as wanted after the input field. And last you need to validate the elements value and not the element itself.
<html>
<head>
<script>
//First put the function in the head.
function getName(){
var input = document.getElementById("name");
input.style.backgroundColor = ''; //Reseting the backgroundcolor
if (input.value == ''){ //Add the.value
input.style.backgroundColor = 'red';
}
else{
//document.write('Hello ' + input.value); //This would overwrite the whole document, removing your dom.
//Instead we write it in your greeting field.
var tE = document.getElementById('greet');
tE.innerHTML = input.value;
}
return false //Prevent the form from being submitted.
}
</script>
</head>
<body>
<h1>Test</h1>
<form name = 'greeting'>
Type your name here: <input type = "Text" name="fullname" id="name"> <button onclick="return getName()">Create</button><br>
Hello <label id="greet">Hello</label>
</form>
</body>
</html>
You need to cancel the submit event which makes the form submit, alternatively you could not wrap everything inside a form element and just use normal div that way submit button wont submit.
Demo : https://jsfiddle.net/bypr0z5a/
Note reason i attach event handler in javascript and note onclick attribute on button element is because jsfiddle works weird, on ordinary page your way of calling getName() would have worked.
byId('subBtn').onclick = function (e) {
e.preventDefault();
var i = byId('name'),
inputVal = i.value;
if (inputVal == "") {
i.style.backgroundColor = "red";
} else {
byId('greet').innerText = inputVal;
i.style.backgroundColor = "#fff";
}
}
function byId(x) {
return document.getElementById(x);
}

Categories

Resources