Let's say I want to append a pattern like this in the DOM:
*
* *
* * *
* * * *
My JavaScript code looks like this:
function tri1()
{
let rows=document.getElementById("upperTri").value;
for(let i=1; i<=rows; i++)
{
for (let j=1; j<=i; j++)
{
document.getElementById("resTri1").appendChild(document.createTextNode(star));
}
document.getElementById("resTri1").appendChild(document.createElement("br"));
}
}
var star="*";
The thing is that I want to insert em space after each asterisk printed in the pattern, but HTML doesn't let one add more than one space unless it's an , etc. But I couldn't find any way to appendChild() the emspace in the DOM. It just prints the text instead of the em space.
Any solution to this?
My HTML code:
<html>
<head>
<title>Pattern</title>
<script type="text/javascript" src="PB220322.js"></script>
</head>
<body>
<h1>JS Lab Session 22-03-22</h1>
<fieldset>
<legend><h2>Left Triangle</h2></legend>
<label for="upperTri">Enter the number of rows:</label>
<input type="number" name="upperTri" id="upperTri" onchange="tri1()">
<input type="submit" value="Enter" onsubmit="tri1()">
<div id="resTri1"></div>
</fieldset>
</body>
</html>
Append to the innerHTML of the parent element after appending the text node:
function tri1()
{
let rows=document.getElementById("upperTri").value;
for(let i=1; i<=rows; i++)
{
for (let j=1; j<=i; j++)
{
let elem = document.getElementById("resTri1")
elem.appendChild(document.createTextNode(star));
elem.innerHTML += " "
}
document.getElementById("resTri1").appendChild(document.createElement("br"));
}
}
var star="*";
<html>
<head>
<title>Pattern</title>
</head>
<body>
<h1>JS Lab Session 22-03-22</h1>
<fieldset>
<legend><h2>Left Triangle</h2></legend>
<label for="upperTri">Enter the number of rows:</label>
<input type="number" name="upperTri" id="upperTri" onchange="tri1()">
<input type="submit" value="Enter" onsubmit="tri1()">
<div id="resTri1"></div>
</fieldset>
</body>
</html>
Really quick:
Inline event handlers are garbage so in the example that onchange and onsubmit have been replaced with .addEventListener().
.createTextNode() is quite antiquated, albiet very stable, it renders text not HTML. .innerHTML and .textContent can destroy content if it isn't appended with a += operand. There is a method that isn't destructive and very versatile: .insertAdjacentHTML(). The Unicode characters you are trying to use can be in different formats:
// HTML Decimal & Hexidecimal
*
// CSS
\00002a\002003
// JavaScript
\u002a\u2003
* needs to be rendered as HTML so methods such as .insertAdjacentHTML() is ideal, but more often you'll see .innerHTML being used despite it's limitations.
The example below employs some useful interfaces from the HTML DOM API. There are extensive details commented in the example -- the following list are references pertaining to those comments:
HTMLFormElement
HTMLFormControlsCollection
HTMLFormElement Submit Event
Event.preventDefault()
Events
Event Delegation
Note: in the example the "stars" are just a fancier asterisk ❉.
// Event handler passes the Event Object
function tri(e) {
/*
Stop the default behavior of form#UI✺ during a "submit" event.
*/
e.preventDefault();
// Create a HTMLFormControlsCollection🞲 (>this< is form#UI)
const IO = this.elements;
/*
The value of input#rQty coerced into a real number
(prefixed with a plus '+' will coerce a string into number)
*/
const rows = +IO.rQty.value;
// ❉ and emspace in HTML decimal format;
const star = '❉ ';
for (let i = 1; i <= rows; i++) {
for (let j = 1; j <= i; j++) {
/*
iAHTML() renders htmlString into real HTML without destroying
content (unlike .innerHTML)
*/
IO.box.insertAdjacentHTML('beforeEnd', star);
}
IO.box.insertAdjacentHTML('beforeEnd', '<br>');
}
}
/*
Bind form#UI to the "submit" event.
When "submit" event fires, the event handler tri(e) will be invoked.
Note the terse syntax of the DOM Object:
document.forms.UI
this is from the HTMLFormElement interface.
*/
document.forms.UI.addEventListener('submit', tri);
/*
✺ form#UI is also >this< within the event handler because it is registered
to the "submit" event.
*/
/*
🞲 HTMLFormControlsCollection is part of the HTMLFormElement interface. It
is an array-like object consisting of all form controls under form#UI. Form
controls are:
<button>, <fieldset>, <input>, <object>, <output>, <select>, <textarea>
form controls may be referrenced by id or by name.
*/
html {
font: 2ch/1.15 'Segoe UI';
}
header {
margin-bottom: -12px;
}
h1 {
margin-bottom: 0;
}
fieldset {
min-width: max-content;
}
legend {
margin-bottom: -12px;
}
label,
input {
display: inline-block;
font: inherit;
margin-bottom: 4px;
}
#rQty {
width: 5ch;
text-align: right;
}
.box {
font-family: Consolas;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>JS Lab Session 22-03-22</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<style>
/* Any CSS here has second highest priority */
</style>
</head>
<body>
<form id='UI'>
<header>
<h1>JS Lab</h1>
<p>Session 22-03-22</p>
</header>
<fieldset>
<legend>
<h2>Left Triangle</h2>
</legend>
<label for="rQty">Enter the number of rows: </label>
<input id="rQty" type="number" min='3' max='100' value='3'>
<input type="submit" value="Enter">
<fieldset name="box" class='box'></fieldset>
</fieldset>
</form>
<script>
/*
JavaScript can go here.
Place all external script tags directly above/before this
script tag.
*/
</script>
</body>
</html>
Related
So basically I was trying to make an error message that is hidden by default be displayed when the user inputs incorrect information. However, the message wasn't appearing. So I used the debugger and found out that the error node element at the top of the js. code was successfully finding the element in the HTML and also successfully changing it's properties. And yet nothing was happening. So after a bit of research I found out that there is a property called isConnected which shows if the Node is connected to the Document. Turns out mine was connected(true) immediately after finding the element, but it was disconnected(false) by the time it entered the errorHandler() func. So again after a bit of debugging I found out that the bottom line of the onPageLoad func was causing the problem. It used to be rootUl.innerHTML += template(countriesObj); but that was breaking it. However, when I moved my error element in the HTML from the ul to outside the id="root" div, it was working fine. It was only breaking when the element was inside the ul. At the end of the day I fixed it by using Element.insertAdjacentHTML() instead, which wouldnt sever the connection between the error element and Document. So after about an hour of struggle, I am curious why that happens and what the difference is between rootUl.innerHTML += template(countriesObj); and rootUl.insertAdjacentHTML('beforeend', template(countriesObj));
Just to add, rootUl.innerHTML+=template(countriesObj) breaks the connection even when used by other function which are not shown here.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>List Towns</title>
<script src="../handlebars.min.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<p style="text-align: center; font-size: 18px; font-weight: 700; font-family: Arial, Helvetica, sans-serif;">
Input in the following format: "{Country}: {town}, {town} {Country}: {town}, {town}" and so on. Matching is case-insensitive. Non-english characters are not supported. Numbers are not supported. Check regex for more info. Reset button deletes entire database and refreshes page.
</p>
<form action="#" class="content">
<label for="towns">Towns</label>
<input id="towns" type="text" placeholder="ex. Bulgaria: Burgas, Varna Turkey: Ankara"/>
<button id="btnLoadTowns">Load</button>
</form>
<div id="root">
<ul>
<!--When the element was here, innerHTML wasn't working correctly-->
<h4 id="error" style="color: rgb(136, 9, 0); display: none;" >Error. Input string not in correct format. Look at instructions above.</h4>
</ul>
</div>
<!--When the element was here, innerHTML was working fine-->
<!-- <h4 id="error" style="color: rgb(136, 9, 0); display: none;" >Error. Input string not in correct format. Look at instructions above.</h4> -->
<button id="reset">Reset</button>
<h4 id="empty-database" style="color: rgb(136, 9, 0); display: none;" >Database is currently empty.</h4>
</body>
<script src="./app.js"></script>
</html>
async function pageApp(){
//Misc
let error = document.querySelector('#error');
let emptyDatabase = document.getElementById('empty-database');
// Grab the unordered list of countries
let rootUl = document.querySelector('#root ul');
// Extract(GET request) data from database
let database = await getRequestForCountries();
// Get the two templates: One is for both country and town, another is just for town when country already exists
let template = await getTemplate();
let templateTown = await getTemplateTown();
// Load countries on page load
onPageLoad();
//Attach load event to button
attachLoadEvent();
//Reset button for deleting the database
resetButton()
function errorHandler(){
error.style.display = 'block';
setTimeout(function(){
error.style.color = 'rgb(136, 9, 0)';
error.style.background = 'none';
}, 150)
error.style.color = 'red';
error.style.background = 'rgb(136, 9, 0)';
}
function onPageLoad(){
database.forEach(entry => {
let townsArr = entry.towns;
let countryName = entry.countryName;
let townsArrObj = townsArr.reduce((acc, cur) =>{
let townObj = {
name: cur
}
acc.push(townObj);
return acc;
},[]);
let countriesObj = {
countries:[
{
name: countryName,
towns: townsArrObj
}
]
}
//Was rootUl.innerHTML += template(countriesObj); But that breaks the DOM of error and makes error.isConnected = false;
// rootUl.innerHTML += template(countriesObj);
rootUl.insertAdjacentHTML('beforeend', template(countriesObj));
})
}
Element.innerHTML +=, gets HTML code within the element and append it with something.
document.querySelector('p').innerHTML += `<span>Appended span</span>`;
<p>
Lorem Ipsum
<span style="color: red">Something</span>
<p>
Whereas, Element.insertAdjacentHTML('beforeend', 'To be inserted node'), will add new node, before the specified element.
document.querySelector('p').insertAdjacentHTML('beforeend', '<div>I am div</div>');
<p>Lorem ipsum</p>
Below is my code which show me notice of inserting kill , fight, slap when i insert in the textbox.
But i want to block all inappropriate words possible in the textbox like f**k and so on. DO you guys have any ideas. Thanks
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div id="wrapper" style="width:600px; margin:0 auto;">
<h2></h2>
<input id="txtWords" style="width:300px;" />
<br />
<input type="button" id="btnCheck" onclick="fnCheckForRestrictedWords();" value="Check For
Restricted Words">
</div>
<script type="text/javascript">
function fnCheckForRestrictedWords() {
var restrictedWords = new Array("kill", "fight", "slap");
var txtInput = document.getElementById("txtWords").value;
var error = 0;
for (var i = 0; i < restrictedWords.length; i++) {
var val = restrictedWords[i];
if ((txtInput.toLowerCase()).indexOf(val.toString()) > -1) {
error = error + 1;
}
}
if (error > 0) {
alert('You have entered some restricted words.')
}
else {
// Your logic here
}
}
</script>
</body>
</html>
You need to define all "bad" words and put them in your blacklist. You can use some existing lists as a starting point for your list:
https://github.com/LDNOOBW/List-of-Dirty-Naughty-Obscene-and-Otherwise-Bad-Words/blob/master/en
https://github.com/dariusk/wordfilter/blob/master/lib/badwords.json
http://www.bannedwordlist.com/lists/swearWords.txt
http://www.frontgatemedia.com/new/wp-content/uploads/2014/03/Terms-to-Block.csv
Source: Reddit
If you want to include obfuscated "bad" words you may need to add the to the list as well.
The
includes()
method should work: txtInput.includes(restrictedWords[i]) which returns either true or false. You also want to include more bad words and different ways to write them
How can I remove div tags and their content in javascript ?
I tried the following script, but that remove only the tags and leave the content.
var res, html = document.getElementById('source').value;
res = html.replace(/(<div[^>]+>|<div>|<\/div>)/g, "");
document.getElementById('result').innerHTML = res;
textarea {
width: 100%;
height: 120px;
padding: 5px;
border: 1px solid rgba(0, 0, 0, .3);
}
<textarea id="source">
<p>
<input type="text"/>
<div class="parent"><div>inner01</div><div>inner02</div></div>
<span></span>
</p>
</textarea>
<textarea id="result"></textarea>
Assuming that the div is an actual string, try this regex instead:
<div.*<\/div>
A dot is any one single character: .
followed by an asterisk witch is zero or more instances of whatever precedes it: * *
and in order to interpret the forward slash literally escape it with a backward slash: \
* a plus: + would suffice as well -- one or more instances of whatever precedes it.
var res, html = document.getElementById('source').value;
res = html.replace(/<div.*<\/div>/g, "");
document.getElementById('result').innerHTML = res;
textarea {
width: 100%;
height: 120px;
padding: 5px;
border: 1px solid rgba(0, 0, 0, .3);
}
<textarea id="source">
<p>
<input type="text"/>
<div class="parent"><div>inner01</div><div>inner02</div></div>
<span></span>
<div class="parent"><input></div>
</p>
</textarea>
<textarea id="result"></textarea>
Note: An extra div is added to demonstrate that multiple instances are removed properly and without removing "tags" occurring between div "tags".
EDIT: epascarello has pointed out that I'm an idiot, so this should be acceptable at least in this example:
HTML:
<textarea id="source">
<p>
<input type="text">
<div id="parent"><div>inner01</div><div>inner02</div></div>
<span></span>
</p>
</textarea>
<textarea id="result"></textarea>
<button onclick="removeDiv()">
Click me to remove div!
</button>
JS:
function removeDiv() {
var string = document.getElementById("source").value;
var s1 = string.split("<div")[0];
var s2 = string.split("</div>");
string = s1 + s2[s2.length-1];
document.getElementById("result").value = string;
}
The problem: This removes everything between the first opening div tag and the last closing div tag, so if there's something you want to leave in between, it'll be deleted. Example:
<p>
<div>Some stuff</div>
<span>Stuff to keep</span>
<div>Some other stuff</div>
</p>
Will end up as:
<p>
</p>
So it will not work in every case.
here is example for clearing or removing div contents on html page you can select which one is suitable & you may as well count them , i have made this example for you where you can click on each div content and as per click it will remove content . also there is a button if you click it , it will count all divs on page clear it's content then completely remove its content along with sub tags child's inside it.
its important to keep this sequence of scripts other ways it will give error and scripts must be under the div tags so it can read the divs .
i have used sweetalert js library for styling the message alerts modals as well i have used j query library within the page please check snip code .
note : Your Source Example is included in my code and by clicking on div it will clear content & by clicking on button it will clear and remove , i left only one to avoid deleting so you can tweak it and understand how it works .
Edited : Frankly , after testing this on snip , i have noticed the counters giving totals of hidden div tags as well so am assuming these totals is counting also the snip tool window even the hidden one .
good luck
<!DOCTYPE html>
<html>
<!-- must use in order to make XP Themes render -->
<meta HTTP-EQUIV="MSThemeCompatible" content="Yes" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<head>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
</head>
<body>
<div id="unknown_id_Number">
<textrea id="unknown_idtxtbox">
<p>
<input type="text"/>
<div class="parent"><div>inner01</div><div>inner02</div></div>
<span></span>
</p>
</textarea>
<textarea id="result"></textarea>
</div>
<div id="div6">
<textrea>
<p>
<input type="text"/>
<div class="parent"><div>inner01</div><div>inner02</div></div>
<span></span>
</p>
</textarea>
<textarea id="result"></textarea>
</div>
<div id = "div1" value="i am div content" style= "width:200px;height:70px;background:orange;text-align:center;padding:5%;color:white;">
i am content of div1
</div>
<div id = "#div2" value="txt2" style= "width:200px;height:70px;background:pink;text-align:center;">
i am content of div2
</div>
<div id = 'div3' value="txt3" style= "width:200px;height:70px;background:green;text-align:center;">
i am content of div3
</div>
<button onclick="removealldiv()">Click to remove all div contents</button>
<script>
function removealldiv(){
// insert total divs on divs variable
var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++){
//do something to each div like
divs[i].innerHTML = " ";
divs[i].remove();
if ( i = i ) {
swal("i have clear then removed about "+ i +" div's on this page ",'success');
}
}
}
</script>
<script>
$("div").click( function(){
var name = $(this).attr("id");
swal({
title: "Are you sure you want to delete the content of div id = " +name+"?",
text: "if you click delete , the content of your div will be removed",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
swal("Poof! your div content is cleared now ", {
icon: "success",
});
if ( name = name ) {
$(this).text(' ');
}
}
else {
swal("your div content is safe , the content will remain on page ");
}
});
});
</script>
</body>
</html>
I am using a code snippet that I found to display a multipage form using visibility hidden.
There is a very good possibility that all of my problem stems from this method. That resource was from here:
http://www.devx.com/webdev/Article/10483/0/page/2
It is a fairly straightforward way to display multiple pages of a form...it probably was never intended to be able to allow printing.
<html>
<head>
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script language="JavaScript">
$.getScript("printThis.js", function(){
});
var currentLayer = 'page1';
function showLayer(lyr){
hideLayer(currentLayer);
document.getElementById(lyr).style.visibility = 'visible';
currentLayer = lyr;
}
function hideLayer(lyr){
document.getElementById(lyr).style.visibility = 'hidden';
}
function showValues(form){
var values = '';
var len = form.length - 1; //Leave off Submit Button
for(i=0; i<len; i++){
if(form[i].id.indexOf("C")!=-1||form[i].id.indexOf("B")!=-1)
continue;
values += form[i].id;
values += ': ';
values += form[i].value;
values += '\n';
}
alert(values);
}
</script>
<style>
body{
font: 10pt sans-serif;
}
.page{
position: absolute;
top: 10;
left: 100;
visibility: hidden;
}
</style>
</head>
<body>
<form id="multiForm" action="App1.php" method="POST" action="javascript:void(0)" onSubmit="showValues(this)" id="app">
<div id="page1" class="page" style="visibility:visible;">
Applicant Name: <input type="text" size="50" name="name1" >
</form>
<p><input type="button" id="C1" value="Continue" onClick="showLayer('page2')"></p>
</div>
<div id="page2" class="page">
This is Page 2
<br>
<input type="button" id="B1" value="Go Back" onClick="showLayer('page1')">
<input type="button" id="B2" value="Print App" onClick="$('#page1').printThis({})">
<br><br>
</div>
</form>
</body>
</html>
The "Print App" button is properly calling the printThis plugin. However, I get no content from the page1 DIV section. All that is printed is the normal header portion (Page 1 of 1) in the upper right and about:blank in lower left and date in lower right of page…no content, which with my sample file should be Applicant Name input box.
I assume that this is because the DIV for page1 is set to "hidden" while the content of page2 is being displayed. If I substitute "page2" in the button call then I get the content from page2 as expected.
So...I guess what I am after is a way to temporarily change the DIV being referenced in the printThis button call to be visible just long enough to perform the page print.
Any ideas?
I'm the plugin author - you need to incorporate the print media query into your css.
This would also help users that select file > print or control + P, as it will show all form elements.
The print media query allows you to make styling changes specifically for the printed page.
Example:
#media print {
#page1, #page2 {
display: block;
visibility: visible;
position: relative;
}
}
You include this in your css.
Additionally, based on your above code - you have css and javascript inline in your page. You should consider moving both to an external files, for maintenance and improved code standards.
printThis won't work with your current setup, because the plugin looks for the container (selector) you have specified and any linked css in the head of the document.
So for the above, you can do the following:
<!-- move all of this to the bottom of the page for performance -->
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="printThis.js"></script>
<script type="text/javascript" src="myJavascript.js"></script>
<!-- the above file is your javascript externalized, remove $.getScript, wrap in $(document).ready() -->
Then put this in your head:
<link type='text/css' rel='stylesheet' href='style.css'>
<!-- contains your css from the page, including the print media query -->
i try to make the div color changed when click or focus on textbox so i do this js function but it change the textbox color not its div
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test</title>
<style type="text/css">
/* This is the CSS class to use when no focus is on the input control */
.input_text
{
border:1px solid #c0c0c0;
padding:4px;
font-size:14px;
color:#000000;
background-color:#ffffff;
}
/* This is the CSS class to use when the control has focus */
.input_text:focus, input.input_text_focus
{
border-color:#646464;
background-color:#ffffc0;
}
</style>
<script type="text/javascript">
// creates a function to set the css class name of input controls when they
// receive or lose focus.
setAspnetTextFocus = function() {
// CSS class name to use when no focus is on the input control
var classBlur = 'input_text';
// CSS class name to use when the input control has focus
var classFocus = 'input_text_focus';
// get all of the input tags on the page
var inputElements = document.getElementsByTagName('input');
for (var i = 0; i < inputElements.length; i++) {
inputElements[i].onfocus = function() {
if (this.className == 'input_text') {
this.className += ' ' + classFocus;
}
}
// add the onblur event and set it to remove the on focused CSS class when it loses focus
inputElements[i].onblur = function() {
this.className = this.className.replace(new RegExp(' ' + classFocus + '\\b'), '');
}
}
}
// attach this event on load of the page
if (window.attachEvent) window.attachEvent('onload', setAspnetTextFocus);
</script>
</head>
<body>
<div class="input_text" >
<input type="text" id="TextBox1" class="input_text" />
</div>
</body>
</html>
any ideas?
To change the text select color you just need CSS. You wont be able to do it with JavaScript except with not so pretty hacks (you'd need to draw a rectangle on top/below the words on select...)
With CSS tho you just need to do (i believe):
#TextBox1::selection {
background: #ffb7b7; /* Safari */
}
#TextBox1::-moz-selection {
background: #ffb7b7; /* Firefox */
}
Source: http://css-tricks.com/overriding-the-default-text-selection-color-with-css/
Just a side note tho in case you care, this is NOT W3C validated CSS.
here is a jsfiddle using JQuery that will do what I think you are asking for: http://jsfiddle.net/pthurlow/GG6Te/
here it is in plain vanilla JS: http://jsfiddle.net/FSZZU/
EDIT code from jsfiddle:
html
<div class="input_text">
<input type="text" id="TextBox1" class="input_text" />
</div>
script
document.getElementById('TextBox1').onfocus = function() {
this.parentNode.className = 'input_text focus_text';
};
document.getElementById('TextBox1').onblur = function() {
this.parentNode.className = 'input_text';
};