Replicate user's input as typing effect in Javascript - javascript

I am trying to capture a sentence from a user's input and replicate it as a typing effect. I am using JavaScript to perform the task.
I am able to capture the input and display it with console.log(), but when I add the typing effect function, it doesn't seem to work.
My code are as follow. What's going wrong?
var getInput = document.getElementById("input");
getInput.onkeyup = function(e) {
if (e.keyCode == 13) {
var i = 0;
var text = input.value;
function typing() {
if (i < text.length) {
document.getElementById('output').innerHTML += text.charAt(i);
i++;
setTimeout(typeWriter, 200);
}
}
e.currentTarget.value = "";
}
}
<link href="https://fonts.googleapis.com/css?family=Francois+One" rel="stylesheet">
<div class="background"></div>
<div class="input"></div>
<div class="typing">
<div class="input-group">
<div class="form-group">
<label for="text">Please Type Here:</label>
<input type="text" class="form-control" id="input">
</div>
</div>
</div>
<div class="output" id="output">
</div>

You have defined the typing function, but haven't called it.
Plus, in the setTimeout, you've called typeWriter function which is undefined. You wanted calling typing instead:
var getInput = document.getElementById("input");
getInput.onkeyup = function(e) {
if (e.keyCode == 13) {
var i = 0;
var text = input.value;
function typing() {
if (i < text.length) {
document.getElementById('output').innerHTML += text.charAt(i);
i++;
setTimeout(typing, 200);
}
}
typing();
e.currentTarget.value = "";
}
}
<div class="background"></div>
<div class="input"></div>
<div class="typing">
<div class="input-group">
<div class="form-group">
<label for="text">Please Type Here:</label>
<input type="text" class="form-control" id="input">
</div>
</div>
</div>
<div class="output" id="output">
</div>

You can use the keyup event in Javascript and listen to that event and update your DOM element on each keyboard stroke.
window.onload = function() {
let myInputElement = document.querySelector(`#myInput`);
if (myInputElement) {
myInputElement.addEventListener('keyup', function(event) {
let myTextElement = document.querySelector(`#myText`);
myTextElement.innerText = myInputElement.value;
});
}
}
<html>
<head>
</head>
<body>
<input id="myInput" />
<br>
<hr>
<p id="myText"></p>
</body>

Related

HTML Form Validation Logic in JavaScript or jQuery

I have a form for which I should write validation logic.
Let's say there's an input field like this.
<div class="group1"><label>Product code</label> <input id="code" name=""code" type="text" class="control1"></div>
If I want to make it a required field how do I write the logic?
I don't have access to the CSS files. But there's an input like this which I can use which has a red outline.
<div class="group1 row has-error">
<div><input type="text" class="control1"></div>
</div>
I have to give the code in JavaScript or jQuery.
Get an element and set true on required property.
const input1 = document.getElementById('code');
input1.required = true;
const input2 = document.querySelector('div.group1>div>input.control1');
input2.required = true;
<form>
<div class="group1"><label>Product code</label>
<input id="code" name="code" type="text" class="control1">
</div>
<div class="group1 row has-error">
<div>
<input type="text" class="control1">
</div>
</div>
<input type="submit">
</form>
I think this is what you need
$("#formSubmit").submit(function(e) {
e.preventDefault();
var error_text = "<div class='text-danger error_val'>Cannot be empty</div>"
var data = $("#formSubmit").serializeArray();
var allInputs = $("#formSubmit input");
for(var i=0; i<data.length; i++){
if(data[i].value.length == 0){
$(".group1").addClass('has-error');
var errorDiv = $(allInputs)[i].closest('.has-error');
$(error_text).insertAfter( errorDiv );
}
}
});
.has-error input{
border: 1px solid #f00;
}
.text-danger{
color:#f00;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="formSubmit">
<div class="group1 row">
<label>Product code</label>
<input id="code" name="code" type="text" class="control1" >
</div>
<button type="submit" id="submitButton">Save</button>
</form>
I know it`s too late but you can use these functions to make an input required/optional
function makeFieldRequired(element, elementName) {
let jqueryObj = $(element);
jqueryObj.attr('title', `${elementName} is required`);
jqueryObj.attr('required', 'true');
if (jqueryObj.closest("form").length)
refreshFormValidtion(jqueryObj.closest("form"));
}
function makeFieldOptional(element) {
let jqueryObj = $(element);
jqueryObj.removeAttr('required');
jqueryObj.removeAttr('title');
if (jqueryObj.closest("form").length)
refreshFormValidtion(jqueryObj.closest("form"));
}
function refreshFormValidtion(form) {
$(form).removeData("validator").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse($(form));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Connect clicked button value and function in JS

I'm beginner in JS.
I have 2 functions. How to do :
if I click first button, make first function work, if I click second button, make second function work?
Apply pressed button value to function and then apply it to input field.
Example: when I type 'ABC' using Caesar Cipher , it would return 'NOP', when I type 'ABC' using my cipher (or any other), it would return 'BCD' (or any other value, it depends on which cipher is selected). Thanks everyone in advance
My Js and Html code below:
<div class="container">
<div class="row">
<form class="col s12 m12 l12">
<h2>JS Encription</h2>
<div class="row">
<div class="input-field col s5 m5 l5">
<input id="field1" placeholder="Type you text here" id="first_name" type="text" class="validate">
<label for="first_name">Input</label>
</div>
<div class="input-field col s5 m5 l5">
<input id="field2" disabled placeholder="Result is shown here" id="first_name" type="text" class="validate">
<label for="first_name">Output</label>
</div>
</div>
</form>
</div>
<div class="row switchBtns">
<div class="col s12 m12 l12">
<div id="caesarButton" class="col s3 m3 l3 ">
<a class="waves-effect waves-light btn-small">Caesar Cipher</a>
</div>
<div id="mineButton" class="col s3 m3 l3 ">
<a class="waves-effect waves-light btn-small">My Cipher</a>
</div>
<div class="col s3 m3 l3 ">
<a class="waves-effect waves-light btn-small">3rd Variant</a>
</div>
<div class="col s3 m3 l3 ">
<a class="waves-effect waves-light btn-small">4th Variant</a>
</div>
</div>
</div>
</div>
and JS code
// CAESAR
$("#caesarButton").click(function() {
var clicked = $(this).val();
$('#field1').val(encryp(clicked)).val();
});
$('#field1').on('keyup keypress blur', function () {
var textvalue = $(this).val();
$('#field2').val(encryp(textvalue)).val();
});
function encryp(tekst) {
var result = "";
var str = tekst.toUpperCase();
for (var i=0; i<str.length ; i++) {
var ascii = str[i].charCodeAt();
if(ascii>=65 && ascii<=77) {
result+=String.fromCharCode(ascii+13);
}
else if(ascii>=78 && ascii<=90) {
result+=String.fromCharCode(ascii-13);
}
else {
result+=" ";
}
}
return result ;
}
//MINE
$("#mineButton").click(function() {
var clicked = $(this).val();
$('#field1').val(encryp(clicked)).val();
});
$('#field1').on('keyup keypress blur', function () {
var textvalue = $(this).val();
$('#field2').val(encryp(textvalue)).val();
});
function encryp(tekst) {
var result = "";
var str = tekst.toUpperCase();
for (var i=0; i<str.length ; i++) {
var ascii = str[i].charCodeAt();
if(ascii>=65 && ascii<=77) {
result+=String.fromCharCode(ascii+3);
}
else if(ascii>=78 && ascii<=90) {
result+=String.fromCharCode(ascii-3);
}
else {
result+=" ";
}
}
return result ;
}
I whipped up a simplified example of contextually switching input handler functions for you, here ya go:
// use an object as a key-value store for your functions
var funcs = {
caesar: encryp1, // i dont know if i got these the right way around :D
mine: encryp2
}
// store which funciton is currently selected in a variable
var selected = "caesar"
// call this function just to show the default selected function
determineOutput()
// CAESAR
$("#caesarButton").click(function() {
console.log("caesar button clicked!")
// here assign which function to use
selected = "caesar"
determineOutput()
});
//MINE
$("#mineButton").click(function() {
console.log("mine button clicked!")
// here assign which function to use
selected = "mine"
determineOutput()
});
$('#field1').on('keyup keypress blur', function () {
// this function is alled every time one of the events
// listed happens on the #field1 element
determineOutput()
});
function determineOutput(){
var textvalue = $('#field1').val();
//use the function currently selected by addressing it with
// [] on the funcs object
var correctFunction = funcs[selected]
// then call the selected function with the input text
$('#field2').val(correctFunction(textvalue));
// show the user which cipher we're using
$("#currentCipher").html("current cipher:" + selected)
}
function encryp1(tekst) {
var result = "";
var str = tekst.toUpperCase();
for (var i=0; i<str.length ; i++) {
var ascii = str[i].charCodeAt();
if(ascii>=65 && ascii<=77) {
result+=String.fromCharCode(ascii+13);
}
else if(ascii>=78 && ascii<=90) {
result+=String.fromCharCode(ascii-13);
}
else {
result+=" ";
}
}
return result ;
}
function encryp2(tekst) {
var result = "";
var str = tekst.toUpperCase();
for (var i=0; i<str.length ; i++) {
var ascii = str[i].charCodeAt();
if(ascii>=65 && ascii<=77) {
result+=String.fromCharCode(ascii+3);
}
else if(ascii>=78 && ascii<=90) {
result+=String.fromCharCode(ascii-3);
}
else {
result+=" ";
}
}
return result ;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input id="field1" placeholder="Type you text here" type="text">
<label for="field1">Input</label>
</div>
<div>
<input id="field2" disabled placeholder="Result is shown here" type="text" class="validate">
<label for="field2">Output</label>
</div>
<p id="currentCipher"></p>
<button id="caesarButton">
Caesar Cipher
</button>
<button id="mineButton">
My Cipher
</button>

Writing single JS script for assigning ID's to output in HTML

I am creating a website that has a list of user inputs, however at a certain stage I want users to see a summarized page of all their inputs. If the input was not chosen it should not show as part of the summary (as in the script example below).
Here is my problem: there will be multiple user inputs and to write a JS script to achieve what I had done in an example script below will be lots of work and unfeasible. Is there a way the two JS scripts for the individual ID's can be combined into one as in the script below?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div>
<label>For the first test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test1" required>
</div>
<div>
<label>For the second test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test2" required>
</div>
<button id="myBtn">Test</button>
<div style="color:blue;">
<p id="result1"></p>
</div>
<div style="color:red">
<p id="result2"></p>
</div>
<script>
function getUserName() {
var test1 = document.getElementById('test1').value;
var result1 = document.getElementById('result1');
if (test1.length > 0) {
result1.textContent = 'Test1: ' + test1;
} else {
null;
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
</script>
<script>
function getUserName() {
var test2 = document.getElementById('test2').value;
var result2 = document.getElementById('result2');
if (test2.length > 0) {
result2.textContent = 'Test2: ' + test2;
} else {
null;
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
</script>
</body>
</html>
P.s. I would also like to know if a user were to press the test button with an input, remove the input and press the test button again, that the first input would be removed?
You can get all inputs and loop throw the result and create an dom element which will contain the value of the input
and each created element will be added to lets say a result element
See code snippet
function getUserName() {
var inputList = document.getElementsByTagName("INPUT");
var res = document.getElementById("result");
res.innerHTML = "";
var indx = 1;
for (i = 0; i < inputList.length; i++) {
if (inputList[i].value != "") {
var ele = document.createElement("p");
ele.innerHTML ="test " + indx + " : " + inputList[i].value
res.appendChild(ele);
indx++;
}
}
}
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', getUserName, false);
<div>
<label>For the first test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test1" required>
</div>
<div>
<label>For the second test</label>
<input type="text" placeholder="Enter Number" name="clientinfo" id="test2" required>
</div>
<button id="myBtn">Test</button>
<div id="result">
</div>

Why javascript not run line by line

Below are html/javascript code, but when call function calc(), its output a <ol>
tag first, but bot run script orderly.
I have remove the settimeout() function to make it running sync.
Can some one give explain will be appreciated.
function $(id) {
return document.getElementById(id);
}
regex_field = $('regx');
content = $('content');
output = $('output');
flag_field = $('flag')
flag_field.addEventListener('input', function() {
calc();
});
content.addEventListener('input', function() {
calc();
});
regex_field.addEventListener('input', function() {
calc();
});
function calc() {
//setTimeout(function () {
var re = new RegExp(regex_field.value, flag_field.value)
console.log(re);
found = content.value.match(re);
if (found) {
$('output').innerHTML = "<ol>";
for (let i = 0; i < found.length; i++) {
$('output').innerHTML += '<li>' + found[i] + '</li>';
}
$('output').innerHTML += "</ol>";
} else {
$('output').innerHTML = "Nothing Found!";
}
// }, 500);
}
<html>
<head>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
</head>
<body>
<div class="row">
<div class="col-sm-6 form-inline">
RegExp
<input class="col-sm-4 form-control form-control-sm" type="text" id="regx" placeholder="Regex Input"> Flag
<input class="col-sm-1 form-control form-control-sm" type="text" id="flag">
<br>
<div>
<p>Input Content</p>
<textarea class="form-control col-sm-12" name="input" placeholder="Text" id="content" cols="30" rows="10"></textarea>
</div>
</div>
<div class="col-sm-6">
<p>Content get</p>
<div id="output"></div>
</div>
</div>
</body>
</html>
Output is like below. I don't understand why 'ol' tage go above the 'li' tag.
<div id="output">
<ol></ol> // <--- question here
<li>12</li>
<li>34</li>
</div>
When you do $('output').innerHTML = "<ol>"; it immediately adds the ol tag to #output. Since an <ol> without a closing </ol> is invalid, the DOM automatically closes it. So you get:
<div id="output">
<ol></ol>
</div>
Then, you do $('output').innerHTML += '<li>' + found[i] + '</li>';, so it adds that line to #output (which is also invalid, since an li can't belong to a div, but it doesn't know how to fix it):
<div id="output">
<ol></ol>
<li>12</li>
</div>
What you want to do it build up the innerHTML, then set it all at once, so more like:
if (found) {
var output = '';
output = "<ol>";
for (let i = 0; i < found.length; i++) {
output += '<li>' + found[i] + '</li>';
}
output += "</ol>";
} else {
output = "Nothing Found!";
}
$('output').innerHTML = output;

How do you add functions to an assortment of buttons sequentially

I have several div tags with the class of opt that have an input and button element inside them. I am trying to create a function that will take the value from the input tag and when you click the button, the next input and button field will pop up and ask you to enter different information, while the previous input and button tags will hide itself. However, the function is not working here is the jsfiddle.
HTML
<div id="container">
<div class="opt active"> <input type="text" placeholder ="Enter Name"name="name"> <button>OK</button>
</div>
<div class="opt">
<input type="text" placeholder ="Enter Age" name="age"> <button>OK</button>
</div>
<div class="opt">
<input type="text" placeholder ="Enter Race" name="race"> <button>OK</button>
</div>
<div class="opt">
<input type="text" placeholder ="Enter Sex" name="sex"> <button id="done">Done</button>
</div>
</div>
Javascript
function init(){
var opt = document.getElementsByClassName('opt');
var num = 0;
var prop = [];
var propVal = [];
for (var i = 0 ; i < opt.length; i++)
{
opt[i].querySelector('input').value = "";
}
opt[num].querySelector('button').onclick = function()
{
prop[num] = opt[num].querySelector('input').name;
propVal[num]= opt[num].querySelector('input').value;
opt[num].className = "opt";
opt[num+1].className ="opt active";
console.log(prop +" "+ propVal);
num++;
};//button function
}
init();
You need bind the click handlers in the loop as well. You also don't need to use parallel arrays to store the properties when you could use an object instead.
Make sure that there is a "next input" before trying to change the class of the next one.
var opt = document.getElementsByClassName('opt'),
num = 0, prop = {};
function nextInput() {
var input = opt[num].querySelector('input');
prop[input.name] = input.value;
console.log(prop);
opt[num].className = "opt";
if (num + 1 < opt.length) {
opt[num + 1].className = "opt active";
num++;
} else {
// submit?
}
}
for (var i = 0; i < opt.length; i++) {
opt[i].querySelector('input').value = "";
opt[i].querySelector('button').onclick = nextInput;
}
.opt { display: none }
.opt.active { display: block }
<div id="container">
<div class="opt active">
<input type="text" placeholder="Enter Name" name="name">
<button>OK</button>
</div>
<div class="opt">
<input type="text" placeholder="Enter Age" name="age">
<button>OK</button>
</div>
<div class="opt">
<input type="text" placeholder="Enter Race" name="race">
<button>OK</button>
</div>
<div class="opt">
<input type="text" placeholder="Enter Sex" name="sex">
<button id="done">Done</button>
</div>
</div>

Categories