<body>
<div class="container">
<div class="row">
<h1 class="mx-auto">Secured Data Cypher</h1>
</div>
<div class="row">
<h5 class="mx-auto desc"><br><br>Enter Your Desired Message which you want Encrypted <br><br> For example: ****_***123 </h5>
</div>
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<h4>Plain Text</h4>
<textarea class="form-control" id="plain-text" rows="7"></textarea>
</div>
<div class="input-group mb-3">
<input type="number" min="0" max="25" class="form-control" id="my-key" placeholder="Key (Digits Only)">
<div class="input-group-append">
<button class="btn btn-outline-success" type="button" onclick="encrypt()">Encrypt</button>
</div>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<h4>Cipher Text</h4>
<textarea readonly class="form-control" id="cipher-text" rows="7"></textarea>
</div>
<button type="button" class="btn btn-outline-danger" onclick="decrypt()">Decrypt</button>
</div>
<div class="col-sm-4">
<div class="form-group">
<h4>Original Text</h4>
<textarea readonly class="form-control" id="original-text" rows="7"></textarea>
</div>
</div>
</div>
</div>
</body>
<!- JS for Cypher Starts here ->
<script>
function encrypt() {
// Empty Original Text
document.getElementById("original-text").value = "";
var k = document.getElementById("my-key").value;
var p = document.getElementById("plain-text").value;
if (!(k >= 0 && k < 26)) {
alert("Key should be between 0 and 25");
return;
}
if (p.length === 0) {
alert("Plain Text is empty");
}
p = p.toLowerCase();
var cipher = "";
var alphabet = "abcdefghijklmnopqrstuvwxyz";
for (var i = 0; i < p.length; i++) {
var current = p.charAt(i);
if (!isLetter(current)) {
cipher += current;
continue;
}
var index = 0;
index = alphabet.indexOf(current);
var shifted = (parseInt(index) + parseInt(k)) % 26;
cipher += alphabet.charAt(shifted);
}
document.getElementById("cipher-text").value = cipher;
}
function decrypt() {
var k = document.getElementById("my-key").value;
var cipher = document.getElementById("cipher-text").value;
if (!(k >= 0 && k < 26)) {
alert("Key should be between 0 and 25");
return;
}
var original = "";
var alphabet = "abcdefghijklmnopqrstuvwxyz";
for (var i = 0; i < cipher.length; i++) {
var current = cipher.charAt(i);
if (!isLetter(current)) {
original += current;
continue;
}
var index = 0;
index = alphabet.indexOf(current);
var num = parseInt(index) - parseInt(k);
var shifted = (num + 26) % 26;
original += alphabet.charAt(shifted);
}
document.getElementById("original-text").value = original;
}
function isLetter(str) {
return str.length === 1 && str.match(/[a-z]/i);
}
</script>
<!- JS for Cypher Ends here ->
This code above only encrypts texts in lowercase
For example:
Result: Leo_123 -(with shift number of 2)-> ngq_123 -(after decryption)-> leo_123
but my expected result is:
Leo_123 -(with shift number of 2)-> Ngq_123 -(after decryption)-> Leo_123
the first part of the code is from my body tag and I am using bootstrap to make this happen
The javascript code follows the main principal but I want to modify it to get the expected results.
Make these changes:
Make alphabet a global variable that is initialised only once, and includes also the capital letters
Define a SIZE variable that is the length of this alphabet, and use that variable instead of the hard-coded 26, where ever you had used it.
Remove the statement that makes p lowercased.
Here is the adapted code:
// Make this global and add CAPITALS
var alphabet = "abcdefghijklmnopqrstuvwxyz";
alphabet += alphabet.toUpperCase();
var SIZE = alphabet.length; // Use this instead of 26
function encrypt() {
// Empty Original Text
document.getElementById("original-text").value = "";
var k = +document.getElementById("my-key").value;
var p = document.getElementById("plain-text").value;
if (!(k >= 0 && k < SIZE)) {
alert("Key should be between 0 and " + (SIZE-1));
return;
}
if (p.length === 0) {
alert("Plain Text is empty");
}
// Don't lowercase!
// p = p.toLowerCase();
var cipher = "";
for (var i = 0; i < p.length; i++) {
var current = p.charAt(i);
if (!isLetter(current)) {
cipher += current;
continue;
}
var index = alphabet.indexOf(current);
var shifted = (index + k) % SIZE;
cipher += alphabet.charAt(shifted);
}
document.getElementById("cipher-text").value = cipher;
}
function decrypt() {
var k = +document.getElementById("my-key").value;
var cipher = document.getElementById("cipher-text").value;
if (!(k >= 0 && k < SIZE)) {
alert("Key should be between 0 and " + (SIZE-1));
return;
}
var original = "";
for (var i = 0; i < cipher.length; i++) {
var current = cipher.charAt(i);
if (!isLetter(current)) {
original += current;
continue;
}
var index = alphabet.indexOf(current);
var num = index - k;
var shifted = (num + SIZE) % SIZE;
original += alphabet.charAt(shifted);
}
document.getElementById("original-text").value = original;
}
function isLetter(str) {
return str.length === 1 && str.match(/[a-z]/i);
}
<div class="container">
<div class="row">
<h1 class="mx-auto">Secured Data Cypher</h1>
</div>
<div class="row">
<h5 class="mx-auto desc"><br><br>Enter Your Desired Message which you want Encrypted <br><br> For example: ****_***123 </h5>
</div>
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<h4>Plain Text</h4>
<textarea class="form-control" id="plain-text" rows="7"></textarea>
</div>
<div class="input-group mb-3">
<input type="number" min="0" max="51" class="form-control" id="my-key" placeholder="Key (Digits Only)">
<div class="input-group-append">
<button class="btn btn-outline-success" type="button" onclick="encrypt()">Encrypt</button>
</div>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<h4>Cipher Text</h4>
<textarea readonly class="form-control" id="cipher-text" rows="7"></textarea>
</div>
<button type="button" class="btn btn-outline-danger" onclick="decrypt()">Decrypt</button>
</div>
<div class="col-sm-4">
<div class="form-group">
<h4>Original Text</h4>
<textarea readonly class="form-control" id="original-text" rows="7"></textarea>
</div>
</div>
</div>
</div>
Related
I am having a problem with the array of an array. I need the function clickMe() to allow me to output an array such as [[1,1,1,1,1],[2,2,2,2,2],etc].
My problem is that right now the values come up as [1,1,1,1,1,2,2,2,2,2,etc]. I know a for loop inside a for loop would be the best way for this, but how would I get the inputs in sections of five?
Once I can figure this out, I should be able to pull from those arrays without any issues. I would prefer to keep this completely in Javascript.
var qNumber;
function onEnter() {
var qNumber = document.getElementsByName("numberBox")[0].value;
if(event.keyCode == 13) {
if (typeof(Storage) !== "undefined") {
localStorage.setItem("qNumber", qNumber);
console.log(qNumber + " stored successfully");
} else {
console.log("Sorry, your browser does not support Web Storage...");
}
var qID = document.getElementById("numBox");
var submitBtn = document.getElementById("submitButton");
var a = qNumber - 1;
var b = 0;
while (b < a) {
var formClone = document.getElementsByClassName("formBox")[0];
var listClone = formClone.cloneNode(true);
var text =b+2;
document.getElementById("forms").append(listClone);
b++;
}
return qID.parentNode.removeChild(qID);
}
return qNumber;
}
function clickMe() {
var q = localStorage.getItem("qNumber");
console.log(q);
var inputNow = [];
var allInputs = [];
var eachArray = [];
var inputNow = document.getElementsByTagName("input");
for(x=0; x < inputNow.length; x++) {
allInputs.push(inputNow[x].value);
console.log(allInputs);
}
localStorage.clear();
}
input{
display: block;
}
<div id="forms">
<span id="numBox">
<label for="numberBox">Number of Forms</label>
<input type="number" name="numberBox" onkeydown="onEnter()" />
</span>
<form id="formBox" name="formBox" action="#" onsubmit="return false;">
<label for="info1">Input 1:</label>
<input type="text" name="info1" />
<label for="info2">Input 2:
</label>
<input type="text" name="info2" />
<label for="info3">Input 3:
</label>
<input type="text" name="info3" />
<label for="info4">Input 4:
</label>
<input type="text" name="info4" />
<label for="info5">Input 5:
</label>
<input type="text" name="info5" />
</form>
</div>
<input type="submit" value="Submit" id="submitButton" onclick="clickMe()" />
<div id="content">
<span id="info1">input1</span>
<br/>
<span id="info2">input2</span>
<br/>
<span id="info3">input3</span>
<br/>
<span id="info4">input4</span>
<br/>
<span id="info5">input5</span>
</div>
You can always do something like:
var allInputs = [];
var groupInputs = [];
for (x=0; x < inputNow.length; x++) {
groupInputs.push(inputNow[x].value);
if (groupInputs.length === 5 || x === inputNow.length - 1) {
allInputs.push(groupInputs);
groupInputs = [];
}
}
I'm trying to build a currency converter. I'm using javascript and I have a good foundation but I want to know how to make the converter update in real-time without having to click a button.
How do I make it so that my converter converts from a base currency of M without needing be be within a select element & how do I make the converter update as the user types the number in, rather than having to click a button?
I've tried removing all of the available options for the .currency-1 class and only leaving M, but that still leaves a drop down menu. I want to convert from M to X (USD, GBP, CAD, EUR, etc.)
var crrncy = {
'M': {
'USD': 0.80,
'GBP': 0.65,
'EUR': 0.77,
'CAD': 0.95,
'M': 1
},
};
var btn = document.querySelector('.calculate-btn');
var baseCurrencyInput = document.getElementById('currency-1');
var secondCurrencyInput = document.getElementById('currency-2');
var amountInput = document.getElementById('amount');
var toShowAmount = document.querySelector('.given-amount');
var toShowBase = document.querySelector('.base-currency');
var toShowSecond = document.querySelector('.second-currency');
var toShowResult = document.querySelector('.final-result');
function convertCurrency(event) {
event.preventDefault();
var amount = amountInput.value;
var from = baseCurrencyInput.value;
var to = secondCurrencyInput.value;
var result = 0;
try{
if (from == to){
result = amount;
} else {
result = amount * crrncy[from][to];
}
} catch(err) {
result = amount * (1 / crrncy[to][from]);
}
toShowAmount.innerHTML = amount;
toShowBase.textContent = from + ' = ';
toShowSecond.textContent = to;
toShowResult.textContent = result;
}
btn.addEventListener('click', convertCurrency);
<div class="jumbotron">
<div class="container">
<form class="form-inline">
<div class="form-group mb-2">
<input type="number" class="form-control" id="amount"/>
</div>
<div class="form-group mx-sm-3 mb-2">
<select class="form-control" id="currency-1" required>
<option>M</option>
</select>
</div>
<div class="form-group mx-sm-3 mb-2">
<select class="form-control" id="currency-2" required>
<option>USD</option>
<option>GBP</option>
<option>EUR</option>
<option>CAD</option>
</select>
</div>
<button class="btn calculate-btn btn-primary mb-2">Sum</button>
</form>
<div class="result">
<p>
<span class="given-amount"></span>
<span class="base-currency"></span>
<span class="final-result"></span>
<span class="second-currency"></span>
</p>
</div>
</div>
</div>
Any help would be appreciated!
I need the user to be able to input X amount (in currency M, no dropdown), select their native currency & have the page calculate the rate as soon as they type in the number.
Add another eventListner which is keyup so that whenever user types in the required field, it will call the convertCurrency function as below:
amountInput.addEventListener('keyup', convertCurrency);
Edit:
To remove the selection box for M, remove the select element and replace by either <p> or <span> tag. After this, you would have to get the this value by using innerText as var from = baseCurrencyInput.innerText; in the currency converter function.
var crrncy = {
'M': {
'USD': 0.80,
'GBP': 0.65,
'EUR': 0.77,
'CAD': 0.95,
'M': 1
},
}
var btn = document.querySelector('.calculate-btn');
var baseCurrencyInput = document.getElementById('currency-1');
var secondCurrencyInput = document.getElementById('currency-2');
var amountInput = document.getElementById('amount');
var toShowAmount = document.querySelector('.given-amount');
var toShowBase = document.querySelector('.base-currency');
var toShowSecond = document.querySelector('.second-currency');
var toShowResult = document.querySelector('.final-result');
function convertCurrency(event) {
event.preventDefault();
var amount = amountInput.value;
var from = baseCurrencyInput.innerText;
var to = secondCurrencyInput.value;
var result = 0;
try {
if (from == to) {
result = amount;
} else {
result = amount * crrncy[from][to];
}
} catch (err) {
result = amount * (1 / crrncy[to][from]);
}
toShowAmount.innerHTML = amount;
toShowBase.textContent = from + ' = ';
toShowSecond.textContent = to;
toShowResult.textContent = result;
}
btn.addEventListener('click', convertCurrency);
amountInput.addEventListener('keyup', convertCurrency);
<div class="jumbotron">
<div class="container">
<form class="form-inline">
<div class="form-group mb-2">
<input type="number" class="form-control" id="amount"/>
</div>
<div class="form-group mx-sm-3 mb-2">
<p id="currency-1">M</p>
</div>
<div class="form-group mx-sm-3 mb-2">
<select class="form-control" id="currency-2" required>
<option>USD</option>
<option>GBP</option>
<option>EUR</option>
<option>CAD</option>
</select>
</div>
<button class="btn calculate-btn btn-primary mb-2">Sum</button>
</form>
<div class="result">
<p>
<span class="given-amount"></span>
<span class="base-currency"></span>
<span class="final-result"></span>
<span class="second-currency"></span>
</p>
</div>
</div>
</div>
var crrncy = {
'M': {
'USD': 0.80,
'GBP': 0.65,
'EUR': 0.77,
'CAD': 0.95,
'M': 1
},
};
var btn = document.querySelector('.calculate-btn');
var baseCurrencyInput = document.getElementById('currency-1');
var secondCurrencyInput = document.getElementById('currency-2');
var amountInput = document.getElementById('amount');
var toShowAmount = document.querySelector('.given-amount');
var toShowBase = document.querySelector('.base-currency');
var toShowSecond = document.querySelector('.second-currency');
var toShowResult = document.querySelector('.final-result');
function convertCurrency(event) {
event.preventDefault();
var amount = amountInput.value;
var from = baseCurrencyInput.value;
var to = secondCurrencyInput.value;
var result = 0;
try{
if (from == to){
result = amount;
} else {
result = amount * crrncy[from][to];
}
} catch(err) {
result = amount * (1 / crrncy[to][from]);
}
toShowAmount.innerHTML = amount;
toShowBase.textContent = from + ' = ';
toShowSecond.textContent = to;
toShowResult.textContent = result;
}
btn.addEventListener('click', convertCurrency);
$('#amount').keyup(function(event){
convertCurrency(event);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="jumbotron">
<div class="container">
<form class="form-inline">
<div class="form-group mb-2">
<input type="number" class="form-control" id="amount"/>
</div>
<div class="form-group mx-sm-3 mb-2">
<select class="form-control" id="currency-1" required>
<option>M</option>
</select>
</div>
<div class="form-group mx-sm-3 mb-2">
<select class="form-control" id="currency-2" required>
<option>USD</option>
<option>GBP</option>
<option>EUR</option>
<option>CAD</option>
</select>
</div>
<button class="btn calculate-btn btn-primary mb-2">Sum</button>
</form>
<div class="result">
<p>
<span class="given-amount"></span>
<span class="base-currency"></span>
<span class="final-result"></span>
<span class="second-currency"></span>
</p>
</div>
</div>
</div>
I am generating a default header for a given file and I want the sender ID to have 4 characters and the sender Name to have 45 characters. if they are less than 4 and 45 respectfully, I need to enter spaces to have the 4 or 45 characters. How can I do this?
In the figure below as you can see there are not filled in the necessary spaces for when I do blank file. And even if I write something on the sender ID or the sender Name nothing is added.
What am I doing wrong?
function download(fileName, text) {
let element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', fileName);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
document.getElementById("generate").addEventListener("click", function(){
// Generate .txt file header
//force 4 chars
let id = document.getElementById("senderID");
if (id.textContent.length < 4) {
id.textContent += ' ';
}
//force 45 chars
let name = document.getElementById("senderName");
if (name.textContent.length < 45) {
name.textContent += ' ';
}
let header = "HDRPB" + id.textContent + name + "01.10";
let body = document.getElementById("fileContents").textContent;
let text = header;
let fileName = document.getElementById("fileName").value + ".txt";
download(fileName, text);
}, false);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="css/site.css">
<title>Generator</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-2 p-0 mt-2">
<label for="senderID" class="font-weight-bold">Sender ID:</label>
<input id="senderID" type="text" maxlength="4" size="4"/>
</div>
<div class="col-6 p-0 mt-2">
<label for="senderName" class="font-weight-bold">Sender Name:</label>
<input id="senderName" type="text" maxlength="45" size="45"/>
</div>
</div>
<div class="row mt-5">
<div class="col-10">
<label for="fileName" class="font-weight-bold">File Name:</label>
<input id="fileName" type="text"/>
</div>
<div class="col-2">
<button id="generate" type="button" class="btn btn-light font-weight-bold mx-auto">Generate File</button>
</div>
</div>
<div id="fileContents" class=""></div>
</div>
<script src="js/app.js"></script>
</body>
</html>
Consider the following code:
function genId(seed) {
var result = new Array(4);
for (var i = 0; i < 4; i++) {
result[i] = seed[i] || " ";
}
return result.join("");
}
function genName(seed) {
var result = new Array(45);
for (var c = 0; c < 45; c++) {
result[c] = seed[c] || " ";
}
return result.join("");
}
document.getElementById("genHead").addEventListener("click", function() {
var i = document.getElementById("hid").value;
var n = document.getElementById("hname").value;
var header = genId(i) + genName(n);
document.getElementById("results").innerHTML = header;
});
#results {
font-family: monospace;
border: 1px solid #ccc;
display: inline-block;
}
<p>ID: <input type="text" id="hid" /></p>
<p>Name: <input type="" id="hname" /></p>
<button id="genHead">Generate Header</button>
<div id="results"></div>
In this example, I am creating an Array of the specific number of characters. String is considered an Array of Characters anyway. I am using $nbsp; to represent spaces in HTML but you can use ' ' or " ".
There will always be a result due to result[c] = seed[c] || " "; If seed has a character in that position, it will be entered into result at the same position. Otherwise it will enter the No Break Space or the character you want.
You can also do this:
function formatText(t, n, c) {
if(t == undefined){
return "";
}
if(n == undefined){
n = 45;
}
if(c == undefined){
c = " ";
}
var r = new Array(n);
for (var i = 0; i < n; i++) {
r[i] = t[i] || c;
}
return r.join("");
}
Then use like so:
var i = formatText("12", 4, " ");
var n = formatText("test", 45, " ");
Hope this helps.
I am making a Leetspeak converter program, but the second textarea does not show any output. Here is my rudimentary code:
<!DOCTYPE html>
<html>
<body>
<h1>Leetspeak Converter</h1>
<script language="JavaScript">
function convert(){
var x = document.getElementById("myTextArea").value;
var result='';
for (var i = 0, len = x.length; i < len; i++) {
if (x.charAt(i)=='A'){
result = result + '4';
}
}
document.getElementById('resultTextarea').value = result ;
}
</script>
<div class="input">
<textarea id = "myTextArea" rows = "6" cols = "80">
</textarea>
</div>
<div class="push">
<button onclick="convert">Convert</button>
</div>
<div class="result">
<textarea id = "resultTextArea" rows = "6" cols = "80">
</textarea>
</div>
It does not produce any output at all. I have tried using console.log(), but it shows no output.
I have also used a debugger, but no dice.
You have syntax errors, in 2 parts, so change this
<button onclick="convert">Convert</button> // this does not represent a method
with this
<button onclick="convert()">Convert</button>
and in addition, this
document.getElementById('resultTextarea').value = result ; // a small typo in id
with this
document.getElementById('resultTextArea').value = result ;
function convert(){
var x = document.getElementById("myTextArea").value;
var result=0;
for (var i = 0, len = x.length; i < len; i++) {
if (x.charAt(i)=='A'){
result = result + 4;
}
}
document.getElementById('resultTextArea').value = result ;
}
<div class="input">
<textarea id = "myTextArea" rows = "6" cols = "80">
</textarea>
</div>
<div class="push">
<button onclick="convert()">Convert</button>
</div>
<div class="result">
<textarea id = "resultTextArea" rows = "6" cols = "80">
</textarea>
</div>
You have syntax error in:
<button onclick="convert">Convert</button>
Fixed this as:
<button onclick="convert()">Convert</button>
try this
<!DOCTYPE html>
<html>
<body>
<h1>Leetspeak Converter</h1>
<script language="JavaScript">
function convert(){
var x = document.getElementById("myTextArea").value;
var result='';
for (var i = 0,len = x.length ; i < len; i++) {
if (x.charAt(i)=='A'){
result = result + '4';
}
}
document.getElementById('resultTextArea').value = result ;
}
</script>
<div class="input">
<textarea id = "myTextArea" rows = "6" cols = "80">
</textarea>
</div>
<div class="push">
<button onclick="convert()">Convert</button>
</div>
<div class="result">
<textarea id = "resultTextArea" rows = "6" cols = "80">
</textarea>
</div>
</body>
</html>
I created below form: when you enter a name in first text box, it dynamically adds the names to another field below after pressing the + button. The function is implemented on the + button.
Now I want to add a validation logic within the same script, so that same name shouldn't be added twice. Please advise, only want to implement using javascript.
function promptAdd(list){
var text = "";
var inputs = document.querySelectorAll("input[type=text]");
for (var i = 0; i < inputs.length; i++) {
text += inputs[i].value;
}
var li = document.createElement("li");
var node = document.createTextNode(text);
li.appendChild(node);
document.getElementById("list").appendChild(li);
}
<!doctype html>
<html>
<div class="row">
<div class="col-lg-6 mb-1">
<div class="card h-100 text-left">
<div class="card-body">
<h4 class="card-title">Add Resources</h4>
<input type="text" class="form-control" name="employee" placeholder="Enter Name" />
<small id="message" class="form-text text-muted">Press + to add to your list</small>
<button id="bd1" class="btn add-more" onclick="promptAdd(list)" type="button">+</button>
<br></br>
<h5>List of Resources added</h5>
<div class="form-control" id="list">
<span id="list">
</div>
</div>
</div>
</div>
</div>
</html>
The validation could be implemented simply by looping through all the li's and comparing the text of every li with the value of the input and if the values matches just return false, like :
var lis = document.querySelectorAll('#list li');
for (var i = 0; i < lis.length; i++) {
if (lis[i].innerText == text) {
return false;
}
}
Hope this helps.
function promptAdd(list) {
var text = "";
var inputs = document.querySelectorAll("input[type=text]");
for (var i = 0; i < inputs.length; i++) {
text += inputs[i].value;
}
var lis = document.querySelectorAll('#list li');
for (var i = 0; i < lis.length; i++) {
if (lis[i].innerText == text ){
resetInputs();
return false;
}
}
var li = document.createElement("li");
var node = document.createTextNode(text);
li.appendChild(node);
document.getElementById("list").appendChild(li);
resetInputs();
}
function resetInputs(){
var inputs = document.querySelectorAll("input[type=text]");
for (var i = 0; i < inputs.length; i++) {
inputs[i].value = "";
}
}
<div class="row">
<div class="col-lg-6 mb-1">
<div class="card h-100 text-left">
<div class="card-body">
<h4 class="card-title">Add Resources</h4>
<input type="text" class="form-control" name="employee" placeholder="Enter Name" />
<small id="message" class="form-text text-muted">Press + to add to your list</small>
<button id="bd1" class="btn add-more" onclick="promptAdd(list)" type="button">+</button>
<br><br>
<h5>List of Resources added</h5>
<div class="form-control" id="list">
<span id="list"></span>
</div>
</div>
</div>
</div>
</div>
Loop though all li elements and check their innerText with the new text.
If you want to ignore capitalization you can use innerText.toUpperCase() === newText.toUpperCase()
function promptAdd(list) {
var text = "";
var inputs = document.querySelectorAll("input[type=text]");
for (var i = 0; i < inputs.length; i++) {
text += inputs[i].value;
}
if (textAlreadyExistsInList(text)) {
return;
};
var li = document.createElement("li");
var node = document.createTextNode(text);
li.appendChild(node);
document.getElementById("list").appendChild(li);
};
function textAlreadyExistsInList(text) {
var itemExists = false;
var items = document.getElementById("list").querySelectorAll('li');
for (var i = 0; i < items.length; i++) {
if (items[i].innerText === text) { //to ignore casing: items[i].innerText.toUpperCase() === text.toUpperCase()
itemExists = true;
break;
}
}
return itemExists;
}
<div class="row">
<div class="col-lg-6 mb-1">
<div class="card h-100 text-left">
<div class="card-body">
<h4 class="card-title">Add Resources</h4>
<input type="text" class="form-control" name="employee" placeholder="Enter Name" />
<small id="message" class="form-text text-muted">Press + to add to your list</small>
<button id="bd1" class="btn add-more" onclick="promptAdd(list)" type="button">+</button>
<br></br>
<h5>List of Resources added</h5>
<div class="form-control" id="list">
</div>
You need one input text so given that id is better . Here I set insert_name as id ! Get all li by querySelectAll and check text with innerHTML and input value .
function promptAdd(list){
var inputs = document.getElementById("insert_name").value;
if(checkDuplicate(inputs)) return; // check duplicate
var li = document.createElement("li");
var node = document.createTextNode(inputs);
li.appendChild(node);
document.getElementById("list").appendChild(li);
}
function checkDuplicate(name) {
var flag = false;
var lis = document.querySelectorAll("li");
for(var i = 0 ;i < lis.length;i++) {
if(name == lis[i].innerHTML) {
flag = true;
break;
}
}
return flag;
}