new input replace Instead of append - javascript

Here is the html that I wrote for program
It's working but append is not working.
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container m-5">
<div class="row">
<div class="col-md-6 justify-content-center">
<span>Full Name :</span>
<input id="name" type="name" class="d-flex mb-3">
<span>Email :</span>
<input id="email" type="email" name="email" class="d-flex mb-3">
<span>Comment :</span>
<input id="comment" type="text" class="d-flex mb-3">
<button id="btn" class="mt-3">Submit</button>
</div>
<div class="col-md-6">
<p id="demo"></p>
</div>
</div>
</div>
name and comment are inputs.
I type some text but append doesn't working and the new text that entered replace the first one.
function SubmitComment(name, comment) {
let newComment = censor(comment)
for (let i = 0; i < name.length; i++) {
let demo = $("#demo");
demo.html("")
demo.append(`
<h4>${name.val()} :</h4>
<br>
<p>${newComment}</p>
`)
}
}
function censor(comment) {
var splitString = comment.val().split(" ")
for (let b = 0; b < splitString.length; b++) {
if (splitString[b] == "duck") {
splitString[b] = '****';
}
if (splitString[b] == "swan") {
splitString[b] = '****';
}
}
var joinArray = splitString.join(" ");
return joinArray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Am not sure why your looping the name property, but here is a working example!
function Submit() {
SubmitComment($('.name'), $('.comment'));
}
function SubmitComment(name, comment) {
let newComment = censor(comment)
let demo = $("#demo");
demo.html("")
for (let i = 0; i < name.length; i++) {
demo.append(`
<h4>${name.val()} :</h4>
<br>
<p>${newComment}</p>
`)
}
}
function censor(comment) {
var splitString = comment.val().split(" ")
for (let b = 0; b < splitString.length; b++) {
if (splitString[b] == "duck") {
splitString[b] = '****';
}
if (splitString[b] == "kilt") {
splitString[b] = '****';
}
}
var joinArray = splitString.join(" ");
return joinArray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="name" />
<input class="comment" />
<button onClick="Submit()">Submit</button>
<div id="demo"></div>

Related

Search <div> for text using, javasccript

I don't know javascript but I want to use, search on my site. I found a good example on stackoverflow link
I joined all the parts and received the following code:
function SearchName() {
var input = document.getElementById("Search");
var filter = input.value.toLowerCase();
var nodes = document.getElementsByClassName('target');
var card = document.getElementsByClassName('card');
for (i = 0; i < nodes.length; i++) {
if (nodes[i].innerText.toLowerCase().includes(filter)) {
card[i].style.display = "block";
} else {
card[i].style.display = "none";
}
}
}
<input id="Search" onkeyup="SearchName();" class="form-control dsh191" type="text" placeholder="search" name="" />
<div class="d-flex m-0 p-0">
<div class="card">
Abc Def
<p class="dsh185">Code: <span class="code">1234</span></p>
</div>
<div class="card">
Qwr Tyu
<p class="dsh185">Code: <span class="code">5678</span></p>
</div>
<div class="card">
Iop Klj
<p class="dsh185">Code: <span class="code">9000</span></p>
</div>
</div>
Everything works fine, but I need to search by class = 'code'. My question is:
How do I search for Qwr Tyu and <p class="dsh185">Code: <span class="code">5678</span></p> ? What did I try?
I duplicated javascript function code and changed the class from target to code, but nothing was received, now the search goes after the first function in the input.
I added a new function to the input SearchCode();;
In <span>5678</span> I added class="code"
And as I said above I dubbed javascript code and I changed 2 variables: from nodes to code new class name and from card to profilecard, only the new variable but the html tag remains the same.
function SearchName() {
var input = document.getElementById("Search");
var filter = input.value.toLowerCase();
var nodes = document.getElementsByClassName('target');
var card = document.getElementsByClassName('card');
for (i = 0; i < nodes.length; i++) {
if (nodes[i].innerText.toLowerCase().includes(filter)) {
card[i].style.display = "block";
} else {
card[i].style.display = "none";
}
}
}
function SearchCode() {
var input = document.getElementById("Search");
var filter = input.value.toLowerCase();
var code = document.getElementsByClassName('code');
var profilecard = document.getElementsByClassName('card');
for (i = 0; i < code.length; i++) {
if (code[i].innerText.toLowerCase().includes(filter)) {
profilecard[i].style.display = "block";
} else {
profilecard[i].style.display = "none";
}
}
}
<input id="Search" onkeyup="SearchName(); SearchCode();" class="form-control dsh191" type="text" placeholder="search" name="" />
<div class="d-flex m-0 p-0">
<div class="card">
Abc Def
<p class="dsh185">Code: <span class="code">1234</span></p>
</div>
<div class="card">
Qwr Tyu
<p class="dsh185">Code: <span class="code">5678</span></p>
</div>
<div class="card">
Iop Klj
<p class="dsh185">Code: <span class="code">9000</span></p>
</div>
</div>
My question: How can I search the site after 2 html tags (Search by text in tags)?
Any idea how I can change the code, or where I went wrong etc ... Thanks
one idea can be to use innerText on parent tag profileCard
function SearchName() {
var input = document.getElementById("Search");
var filter = input.value.toLowerCase();
var nodes = document.getElementsByClassName('target');
var card = document.getElementsByClassName('card');
for (i = 0; i < nodes.length; i++) {
if (nodes[i].innerText.toLowerCase().includes(filter)) {
card[i].style.display = "block";
} else {
card[i].style.display = "none";
}
}
}
function SearchCode() {
var input = document.getElementById("Search");
var filter = input.value.toLowerCase();
var code = document.getElementsByClassName('code');
var profilecard = document.getElementsByClassName('card');
for (i = 0; i < code.length; i++) {
if (profilecard[i].innerText.toLowerCase().includes(filter)) {
profilecard[i].style.display = 'block';
} else {
profilecard[i].style.display = 'none';
}
}
}
<input id="Search" onkeyup="SearchName(); SearchCode();" class="form-control dsh191" type="text" placeholder="search" name="" />
<div class="d-flex m-0 p-0">
<div class="card">
Abc Def
<p class="dsh185">Code: <span class="code">1234</span></p>
</div>
<div class="card">
Qwr Tyu
<p class="dsh185">Code: <span class="code">5678</span></p>
</div>
<div class="card">
Iop Klj
<p class="dsh185">Code: <span class="code">9000</span></p>
</div>
</div>

Input's onclick event is not responding when i declare the name="band[ ]"

I want to limit the selection of checkboxes through limit_checkbox() function but when i declare the name of input to an array it is not responding. The error shows " Uncaught ReferenceError: limit_checkbox is not defined at HTMLInputElement.onclick"
<div class="form-group w-25" id="ch1">
<input type="checkbox" value="delta" name="band[]" onclick="limit_checkbox(2,this)">
<label>Delta</label>
</div>
<div class="form-group w-25">
<input type="checkbox" value="theta" name="band[]" onclick="limit_checkbox(2,this)">
<label>Theta</label>
</div>
<div class="form-group w-25">
<input type="checkbox" value="alpha" name="band[]" onclick="limit_checkbox(2,this)">
<label>Alpha</label>
</div>
<script>
var a, b = false;
function limit_checkbox(max, obj) {
var x = document.getElementsByName("band");
var count = 0;
for (var i = 0; i < x.length; i++) {
if (x[i].checked) {
count += 1;
}
}
if (count > max) {
alert('You can select only ' + max + ' checkboxes.');
obj.checked = false;
}
}
</script>
Add[] in band i.e : document.getElementsByName("band[]") because javascript is not able to find that inputs .
Working Code :
var a, b = false;
function limit_checkbox(max, obj) {
//getting element by name
var x = document.getElementsByName("band[]");
var count = 0;
for (var i = 0; i < x.length; i++) {
if (x[i].checked) {
//incrementing
count++;
}
}
if (count > max) {
alert('You can select only ' + max + ' checkboxes.');
obj.checked = false;
}
}
<div class="form-group w-25" id="ch1">
<input type="checkbox" value="delta" name="band[]" onclick="limit_checkbox(2,this)">
<label>Delta</label>
</div>
<div class="form-group w-25">
<input type="checkbox" value="theta" name="band[]" onclick="limit_checkbox(2,this)">
<label>Theta</label>
</div>
<div class="form-group w-25">
<input type="checkbox" value="alpha" name="band[]" onclick="limit_checkbox(2,this)">
<label>Alpha</label>
</div>

Linking two pages

I am working on trying to link pages together so if a person were to login using the login page, they would be redirected to a specific created page, and if a user clicked the register button, they would be redirected to the register page and from there, after inputting in information, they would be directed to another page. The button for login or register does not work. Is there a way to fix this?
So far I have this for my login page.
function login() {
var users = ["admin1", "admin2", "admin3", "admin4"];
var pass = ["pass1", "pass2", "pass3", "pass4"];
ivar aUser = document.getElementById("user_name").value;
var aPass = document.getElementById("password").value;
for (i = 0; i < users.length; i++) {
if (users[i] == aUser && pass[i] == aPass) {
window.location = "dashboard.php";
break;
}
}
var myOut = document.getElementById("output");
myOut.innerHTML = "Who Are You? / Incorrect Password";
myOut.className = "error";
function init() {
var login_button = document.getElementById("login_button");
if (login_button !== null) {
login_button.onclick = login;
}
var register_button = document.getElementById("register_button");
if (register_button !== null) {
register_button.onclick = validation;
}
for (i = 1; i <= 10; i++) {
var myErr = document.getElementById("err" + i);
if (myErr !== null) {
myErr.className = "error";
}
}
}
<h1>
Please Login
</h1>
<form id="order_form">
<fieldset>
<legend>Login</legend>
<div class="tab">
<div class="tRow">
<div class="tRow">
<div class="tCell">
<label for="user_name">User Name:</label>
</div>
<div class="tCell">
<input type="text" id="user_name" maxlength="50" />
</div>
</div>
<!-- END OF THIS SELECTION -->
<div class="tRow> <div class=">
<label for="password">Password:</label>
</div>
<div class="tCell">
<input type="text" id="password" required="" maxlength="50" />
</div>
</div>
<!-- END OF THIS SELECTION -->
<div class="tRow">
<div class="tCell">
</div>
<div class="tCell">
<input type="button" id="login_button" value="Login" />
</div>
</div>
<!--END OF THIS SELECTION-->
<div class="tRow">
<div class="tCell">
</div>
<div class="tCell">
<input type="button" id="register_button" value="Register Now!" />
</div>
</div>
<!--END OF THIS SELECTION-->
</div>
<!-- END OF THE TABLE -->
<br />
<div id="output" class="error"></div>
</fieldset>
</form>
Validation function:
function validation() {
for (i=1; i<=10; i++) {
var myErr = document.getElementById("err" + i);
myErr.innerHTML = "";
}
document.getElementById("output").innerHTML = "";
var dept_name = document.getElementById("dept_name").value;
var user_email = document.getElementById("user_email").value;
var user_password = document.getElementById("user_password").value;
var phone_number = document.getElementById("phone_number").value;
var first_name = document.getElementById("first_name").value;
var last_name = document.getElementById("last_name").value;
var office_location = document.getElementById("office_location").value;
var valid = true;
if (dept_name == "") {
document.getElementById("err1").innerHTML = "Invalid!";
valid = false;
}
if ((user_email) =="") {
valid = false;
document.getElementById("err2").innerHTML = "Invalid!";
}
if ((user_password) =="") {
valid = false;
document.getElementById("err3").innerHTML = "Invalid!";
}
if ((first_name) =="") {
valid = false;
document.getElementById("err4").innerHTML = "Invalid!";
}
if ((last_name) =="") {
valid = false;
document.getElementById("err5").innerHTML = "Invalid!";
}
if (isNaN(phone_number) || card_number.length !==11) {
valid = false;
document.getElementById("err6").innerHTML = "Invalid!";
}
if ((office_location) =="") {
valid = false;
document.getElementById("err7").innerHTML = "Invalid!";
}
}
window.onload=init;
Several errors
missing brackets
no execution of init
missing validation function
This works:
function login() {
var myOut = document.getElementById("output");
var users = ["admin1", "admin2", "admin3", "admin4"];
var pass = ["pass1", "pass2", "pass3", "pass4"];
var aUser = document.getElementById("user_name").value;
var aPass = document.getElementById("password").value;
for (i = 0; i < users.length; i++) {
if (users[i] == aUser && pass[i] == aPass) {
myOut.innerHTML = "Correct - you will be redirected";
setTimeout(function() {
window.location = "dashboard.php";
},1000);
return;
}
}
myOut.innerHTML = "Who Are You? / Incorrect Password";
myOut.className = "error";
}
function init() {
var login_button = document.getElementById("login_button");
if (login_button !== null) {
login_button.onclick = login;
}
var register_button = document.getElementById("register_button");
if (register_button !== null) {
register_button.onclick = validation;
}
for (i = 1; i <= 10; i++) {
var myErr = document.getElementById("err" + i);
if (myErr !== null) {
myErr.className = "error";
}
}
}
function validation() { /* you need some code here */ }
window.onload=init;
<h1>
Please Login
</h1>
<form id="order_form">
<fieldset>
<legend>Login</legend>
<div class="tab">
<div class="tRow">
<div class="tRow">
<div class="tCell">
<label for="user_name">User Name:</label>
</div>
<div class="tCell">
<input type="text" id="user_name" maxlength="50" />
</div>
</div>
<!-- END OF THIS SELECTION -->
<div class="tRow> <div class=">
<label for="password">Password:</label>
</div>
<div class="tCell">
<input type="text" id="password" required="" maxlength="50" />
</div>
</div>
<!-- END OF THIS SELECTION -->
<div class="tRow">
<div class="tCell">
</div>
<div class="tCell">
<input type="button" id="login_button" value="Login" />
</div>
</div>
<!--END OF THIS SELECTION-->
<div class="tRow">
<div class="tCell">
</div>
<div class="tCell">
<input type="button" id="register_button" value="Register Now!" />
</div>
</div>
<!--END OF THIS SELECTION-->
</div>
<!-- END OF THE TABLE -->
<br />
<div id="output" class="error"></div>
</fieldset>
</form>
You can make the test simpler:
var userPos = users.indexOf(aUser);
if (userPos !=-1 && userPos === pass.indexOf(aPass)) {
...
}

Replicate user's input as typing effect in 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>

Getting ID of checked rows on a grid in javascript

I am displaying a grid with some data fetched from a csv file along with a checkbox before each row. I am also saving unique ID in the value property of checkbox. Now I want to get the value of ID`s of all checked check boxes in alert() when 'Cancel' button is clicked.
html-
<div class="panel panel-primary">
<div class="panel-heading">DIS Automation</div>
<div class="panel-body">
<div class="field_row">
<input type="file" accept=".csv" id="fileUpload" name="fileUpload1" />
</div>
<br />
<div class="field_row">
<div class="col-lg-12">
<div class="form-group">
<center><div class="col-lg-3"><div class="input-append" id="filterDev" style="visibility: hidden">
<input name="search" id="inputFilter" placeholder="Enter comma separated ID" />
<input type="button" value="Filter" id="filter" class="btn btn-primary" />
</div></div></center>
<div class="col-lg-6"></div>
<input type="button" id="upload" value="Upload" class="btn btn-primary" />
<input type="button" id="cancel" value="Cancel/Save" style="visibility: hidden" class="btn btn-primary" />
<input type="button" id="process" value="Process" style="visibility: hidden" class="btn btn-primary" />
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default" style="align-self: center">
<div class="panel-body" style=" max-height:600px; min-height: 400px; overflow-y: scroll;">
<div class="row">
<div class="col-sm-12" id="dvCSV">
<table id="my-table">
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<p id="download" style="color: cornflowerblue; visibility: hidden"><strong>Please click the below links to download the processed file..</strong></p>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="col-sm-3">
<p id="File1" style="color: cornflowerblue; text-decoration: underline; visibility: hidden">File1 Download</p>
</div>
<div class="col-sm-3">
<p id="File2" style="color: cornflowerblue; text-decoration: underline; visibility: hidden">File2 Download</p>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$("#cancel").on("click", function () {
$('input:checked').each(function () {
//$(this).closest("tr").remove();
});
});
$(function () {
$("#process").bind("click", function () {
document.getElementById("File1").style.visibility = "visible";
document.getElementById("File2").style.visibility = "visible";
document.getElementById("download").style.visibility = "visible";
});
});
$("#filter").click(function () {
ids = $("#inputFilter").val();
if (ids != "") {
idsArray = ids.split(",");
$("#my-table tr:gt(0)").hide();
$.each(idsArray, function (i, v) {
$("#my-table tr[data-id=" + v + "]").show();
})
} else {
$("#my-table tr").show();
}
});
/* $("#File1").click(function () {
window.location = "Files/CommitteeMembers.xlsx";
});
$("#File1").click(function () {
window.location = "Files/GSD_Offering_Completion.xlsx";
});*/
</script>
Javascript-
$(function () {
$("#upload").bind("click", function () {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test($("#fileUpload").val().toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
//var table = $("<table id='name'/>");
var lines = e.target.result.split("\n");
//alert(lines);
var result = [];
var headers = lines[0].split(",");
for (var i = 1; i < headers.length; i++) {
var header = headers[i];
header = header.replace(/(\r\n|\n|\r)/gm, "");
headers[i] = header;
}
for (var i = 1; i < lines.length; i++) {
var obj = {};
var currentline = lines[i].split(",");
//alert(currentline);
for (var j = 0; j < headers.length; j++) {
obj[headers[j]] = currentline[j];
//alert(obj[headers[j]]);
}
result.push(obj);
//alert(JSON.stringify(result));
}
//alert(result[0].NAME + ' '+ result[0].ADDRESS+" "+result[0].CITY);
populateTable(result);
document.getElementById("cancel").style.visibility = "visible";
document.getElementById("process").style.visibility = "visible";
document.getElementById("filterDev").style.visibility = "visible";
}
reader.readAsText($("#fileUpload")[0].files[0]);
}
}
});
});
$(function () {
$("#process").bind("click", function () {
document.getElementById("File1").style.visibility = "visible";
document.getElementById("File2").style.visibility = "visible";
});
});
function populateTable(finalObject) {
var obj = finalObject;
var table = $("<table id='my-table' />");
table[0].border = "1";
var columns = Object.keys(obj[0]);
columns.unshift('');
//alert(columns);
var columnCount = columns.length;
var row = $(table[0].insertRow(-1));
for (var i = 0; i < columnCount; i++) {
var headerCell = $("<th />");
headerCell.html([columns[i]]);
row.append(headerCell);
}
$.each(obj, function (i, obj) {
row = '<tr data-id="' + obj.ID + '"><td><input type="checkbox" value='+obj.ID+'/></td>
table.append(row);
});
var dvTable = $("#dvCSV");
dvTable.html("");
dvTable.append(table);
}
How can this be implemented??
This is a sample code of how you can do it:
$(".btnCancel").click(function(){
var alertText="";
$("[type='checkbox']:checked").each(function(){
alertText+= $(this).attr("value") + " ";
});
alert(alertText);
});
Here is the JSFiddle demo

Categories