This is probably a silly question but why do I lose all the formatting when the function test() starts? What should I change in my code? I would really appreciate your help!
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<style type="text/css">
body {
background: #E6E6FA;
font-family: book antiqua;
}
h1, h2 {
color: grey;
}
</style>
</head>
<h3>Title</h3>
<body bgcolor="#E6E6FA">
<input type="text" id="userInput"></input>
<button onclick="test()">Submit</button>
<p id="Demo"></p>
<p id="Beg"></p>
<p id="Fin"></p>
<script>
function test()
{
var nam= document.getElementById("userInput").value;
var l = nam.length;
var pocz = nam.slice(0,1);
var kon = nam.slice(-1);
document.getElementById("Demo").innerHTML = document.write("Your secret code: " + l + pocz + kon);
var one = nam.slice(-1)
if (one == "a") {
document.write(nam.slice(0,-1) + "bbb");
} else {
document.write(nam + "ccc");
}
}
</script>
</body>
</html>
If document.write is called after the DOM loaded, it replaces the document. Also you are using document.write incorrectly, it doesn't return anything. Just omit it and it will work fine.
document.getElementById("Demo").innerHTML = "Your secret code: " + l + pocz + kon;
For the other uses, do the same thing and assign the value to an element via innerHTML.
Please read the documentation before you use an unfamiliar function.
Never use document.write. Ever. Just don't use it. It is completely antiquated.
Felix Kling's answer will work for the first part, since you are assigning html to an element directly. but the later calls are adding more content to the document, not replacing content, so you must append new content to the document, or make another placeholder (like demo). here is how to do it with appending new content:
function test()
{
var nam= document.getElementById("userInput").value;
var l = nam.length;
var pocz = nam.slice(0,1);
var kon = nam.slice(-1);
document.getElementById("Demo").innerHTML = "Your secret code: " + l + pocz + kon;
var one = nam.slice(-1);
if (document.getElementsByClassName("spantext").length===0)
{
var text=document.createElement("span");
text.setAttribute("class","spantext");
document.getElementsByTagName("body")[0].appendChild(text);
}
else {
var text=document.getElementsByClassName("spantext")[0];
}
if (one == "a") {
text.innerHTML=nam.slice(0,-1) + "bbb";
} else {
text.innerHTML=nam + "ccc";
}
}
fiddle
Related
So I am currently trying to find out how to select text between two characters(for the example I will use a slash / )
Here is what I have so far.
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function startWhenLoaded() {
var text = $("p").text();
var secondStartingPoint, startPointOne, startPointTwo;
if (text.indexOf("/", 0) !== -1) {
//I did -1 because indexOf returns -1 if nothing is found.
/*Also, the second argument in indexOf() acts as my starting
point for searching.*/
secondStartingPoint = text.indexOf("/") + 1;
startPointOne = text.indexOf("/") + 1;
if (text.indexOf("/", secondStartingPoint) !== -1) {
startPointTwo = text.indexOf("", secondStartingPoint) + 1;
var selectedText = slice(startPointOne, startPointTwo);
$("body").append("<p>" + selectedText + "</p>");
//but nothing happens.
}
}
</script>
</head>
<body onload="startWhenLoaded()">
<p>/can I select and duplicate this?/</p>
</body>
</html>
But it doesn't do anything.
It could be achieved simply by using a regex like :
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function startWhenLoaded() {
var text = $("p").text();
var extracted = text.match(/\/(.*)\//).pop();
alert('The extracted text is :'+extracted);
}
</script>
</head>
<body onload="startWhenLoaded()">
<p>Some text here in the start /can I select and duplicate this?/ Some extra text at the end</p>
</body>
</html>
Regex is simplest and easiest way to get your solution.
use exec() function to get text between '/';
console.log(/^\/(.*)\/$/.exec('/some text, /other example//'))
So, I'm new to learning js. And I know that document.write is outdated and the new solution is element.innerHTML. I'm working through some tutorial, but in testing my code it's breaking. What would be the appropriate means of going about inserting element.innerHTML and it's accompanying code, to get this to work?
Below is my snippet:
<!DOCTYPE html>
<html>
<head>
<title>8. Javascript Arrays</title>
</head>
<body>
<h1>8. Javascript Arrays</h1>
<script>
<div id="flightDate"></div>
<div id="myValues"></div>
var flightDate = new Date("September 22, 2004");
var myValues = ["Oceanic", 815, flightDate];
for (i in myValues)
{
document.write("<br />" + myValues[i]);
}
</script>
</body>
</html>
You can display the output in the DIVs that you created.
document.getElementById('flightDate').innerHTML = flightDate;
for (i = 0; i < myValues.length; i++) {
document.getElementById('myValues').innerHTML += myValues[i] + '<br/>';
}
+= concatenates the value with the content that's already there.
I am making my first foray into javascript + jQuery, designing a simple page but encountering errors, I'm sure it's something silly but I've been over the code several times and can't spot it.
The error I receive is below:
The entire code is below (I've changed the dynamic '#' + elementname + 'perc' to a string and I get the same error), can anyone offer any insight?
<DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<!--<script src="js/dealercalc.js"></script>-->
<script type="text/javascript">
$(document).ready(function(){
$(".val-adjust").click(function(){
var name = $(this).attr('name');
var bit = $(this).attr('value');
setvalue(name,bit);
//discountbits['basic'] = false;
//$("#basedisper").text(discountlist['basic']);
});
$("#basdisyes").click(function(){
discountbits['basic'] = true;
//$("#test1").html("<b>Hello world!</b>");
});
$("#btn3").click(function(){
$("#test3").val(gettotal());
});
}
);
function getpercbypurc(value){
return 0;
};
function setvalue(elementname,yesno){
discountbits[elementname] = yesno;
if (yesno) {
$("#basicperc").hmtl(discountlist[elementname] + "%");
} else {
$('#' + elementname + 'perc').hmtl("0%");
}
};
function gettotal() {
var total = 0;
for (var i=0; i<keys.length; i++){
if (discountbits[keys[i]] = true) {
total += discountlist[keys[i]];
}
}
return total;
};
function displaytotal(){
$('#totalper').html(gettotal());
};
var keys = ['basic', 'marketing'];
var discountlist = {
basic:20,
marketing:2
};
var discountbits = {
basic:true,
marketing:false
};
</script>
</head>
<body>
Base Discount<br>
<button class="val-adjust" name="basic" value="false">No</button>
<button class="val-adjust" name="basic" value="true">Yes</button>
<span id="basicperc">0</span>
<br>
<br>
Marketing Plan<br>
<button class="val-adjust" name="marketing" value="false">No</button>
<button class="val-adjust" name="marketing" value="true">Yes</button>
<span id="marketingperc">0</span>
<br>
<br>
Total<br>
<span id="totalper">0</span>
</body>
</html>
You have wrong spelling for html, hmlt should be html
Change
$("#basicperc").hmtl(discountlist[elementname] + "%");
To
$("#basicperc").html(discountlist[elementname] + "%");
you have a typo
$("#basicperc").hmtl(discountlist[elementname] + "%");
//-----^^^^---here
should be
$("#basicperc").html(discountlist[elementname] + "%");
you've made a typo, it's html not hmtl :)
Very obvious typo. It's html, not hmtl !
I would like to be able to control the font-weight of text if bracketed inside a p tag using JavaScript.
For instance:
The cow jumped over the {moon}. font-weight within {} would be increased.
This so the end user can type this into a text area and on submit the would print to page altering the font-weight within the braces or curly brackets.
Any help on this would be great.
Here is how you can do this:
var ps = document.getElementsByTagName('p');
foreach = Array.prototype.forEach;
foreach.call(ps, function (p) {
var content = p.innerHTML;
p.innerHTML = content.replace(/\{(.*?)\}|\((.*?)\)/g, function (m) {
return '<span style="font-weight: bold;">' + m + '</span>';
});
});
And of course a fiddle.
For the example you need just pure JavaScript, no additional libraries.
Edit:
If you don't want to see the brackets in the result you can use:
var ps = document.getElementsByTagName('p');
foreach = Array.prototype.forEach;
foreach.call(ps, function (p) {
var content = p.innerHTML;
p.innerHTML = content.replace(/\((.*?)\)|\{(.*?)\}/g, function (m) {
return '<span style="font-weight: bold;">' + m.replace(/[\(\)\{\}]/g, '') + '</span>';
});
});
Fiddle: http://jsfiddle.net/ma47D/4/
Best regards!
You can do it with mootools like this:
window.addEvent('domready', function()
{
$$('P').each(function(p)
{
p.set('html', p.get('text').replace(/{([^\}]*)*}/g,"<b>$1</b>"));
});
});
domready is important because it must be done after page is completely loaded. converting to jquery would not be so hard.
http://jsfiddle.net/Smw7Q/1/
Locally you can handle it like this:
<!DOCTYPE html>
<html>
<head>
<script>
function transfer(){
document.getElementById("result").innerHTML=document.getElementById("demo").value.replace(/{/g,'<strong>').replace(/}/g,'</strong>');
}
</script>
</head>
<body>
Input: <input type="text" name="input" id="demo"><br>
<input type="button" value="Submit" onclick="transfer();">
<p id="result"></p>
</body>
</html>
If you submit the text to server, the magic can be done similarly at server side.
My suggestion
<!DOCTYPE html>
<html>
<head>
<style>
p span {
font-size:1.5em;
}
</style>
<script>
function regex(){
document.getElementById("output").innerHTML=
document.getElementById("input").value.replace(/{(.*?)}/g, "<span>$1</span>");
};
</script>
</head>
<body>
<p id="output"></p>
<textarea id="input" rows="30" cols="80"></textarea>
<input type="button" value="Input" onclick="regex();"/>
</body>
<html>
Of course, prior to submitting, you need to sanitize your data.
If tried something, but I'm sure there are more elegant solutions.
http://jsfiddle.net/xT7Fg/
$(document).ready(function(){
$(tb).blur(function(){
var str = '';
var nextFont = 0;
$.each($(tb).val(),function(i,char){
if(nextFont == 0){
if(char == '{'){
if($(tb).val().indexOf(i,'}')){
str += '<font size="15">';
nextFont = $(tb).val().indexOf('}', i);
} else {
str += char;
}
} else {
str += char;
}
} else if (nextFont === i) {
str += '</font>';
nextFont = 0;
} else {
str += char;
}
});
$("#txt").html(str);
});
});
I'm writing my first program to make an extension in Google chrome, i just took the "hello world" tutorial as example from here
This is my html file source code :
<!doctype html>
<html>
<head>
<title>Getting Started Extension's Popup</title>
<style>
body {
min-width:357px;
overflow-x:hidden;
}
img {
margin:5px;
border:2px solid black;
vertical-align:middle;
width:75px;
height:75px;
}
</style>
<!-- JavaScript and HTML must be in separate files for security. -->
<script src="popup.js"></script>
</head>
<body>
</body>
</html>
ad this is my javascript file source code :
var req = new XMLHttpRequest();
req.open(
"GET",
"http://api.flickr.com/services/rest/?" +
"method=flickr.photos.search&" +
"api_key=90485e931f687a9b9c2a66bf58a3861a&" +
"text=hello%20world&" +
"safe_search=1&" + // 1 is "safe"
"content_type=1&" + // 1 is "photos only"
"sort=relevance&" + // another good one is "interestingness-desc"
"per_page=20",
true);
req.onload = showPhotos;
req.send(null);
function showPhotos() {
var photos = req.responseXML.getElementsByTagName("photo");
var element = document.createElement('h1');
element.appendChild(document.createTextNode
('tete '+document.location.href+'hgdfhgd'));
for (var i = 0, photo; photo = photos[i]; i++) {
var img = document.createElement("image");
img.src = constructImageURL(photo);
document.body.appendChild(img);
}
}
// See: http://www.flickr.com/services/api/misc.urls.html
function constructImageURL(photo) {
return "http://farm" + photo.getAttribute("farm") +
".static.flickr.com/" + photo.getAttribute("server") +
"/" + photo.getAttribute("id") +
"_" + photo.getAttribute("secret") +
"_s.jpg";
}
The example is very simple and it works fine, but when add my own javascript instruction, it doesn't display it, the instruction that added is in showPhotos() function and it's :
var element = document.createElement('h1');
element.appendChild(document.createTextNode
('tete '+document.location.href+'hgdfhgd'));
in the result, i can see the other content but my 'h1' i don't see it.
i missed something ? can anyone help me please ?
Thanks
You're creating an element but you're not adding it to the page. So it can't be visible.
You can see it you add it, for example like this :
var element = document.createElement('h1');
element.appendChild(document.createTextNode ('tete '+document.location.href+'hgdfhgd'));
document.body.appendChild(element);