Again I got a problem with JavaScript, but this time is something more complex.
I'm trying to make a little JavaScript text editor. Basically it's an experiment, a test and the thing should be easy. I have a <h1> HTML element, and a <p> HTML element, and both of them change, as the user writes on a <input type="text" /> element and a <textarea></textarea>.
Now, everything work fine, but there is a problem. For making a space between lines, the user can't just press Enter, but of course need to use the <br /> HTML tag.
So my idea was to make a little button that allows the user to add this tag by pressing that button.
And JavaScript just makes a variable of the actual text, save it and add at the end of it the <br />. The result should be the text written by the user plus the break HTML tag.
And this works, if the textarea is empty and if you have never written something on it. It works and work even 10 or 20 times, but if you write something on it, it just stop working, even if you delete all the text. What is the problem in the code below?
<html>
<head>
<title>Text editor</title>
<meta charset="utf-8" />
<link href="https://fonts.googleapis.com/css?family=Roboto|Roboto+Slab" rel="stylesheet">
<style>
.title {
font-family: roboto;
text-align: center;
}
.text {
font-family: roboto slab;
text-align: justify;
margin-bottom: 40px;
}
.container {
width: 80%;
}
.textarea {
width: 100%;
height: 30em;
text-indent: 0.5em;
}
.title_box {
margin: 10px;
width: 20em;
padding: 10px;
font-size: 1em;
}
</style>
</head>
<body>
<center>
<div class="container">
<h1 class="title" id="title_space">Title of the page</h1>
<p class="text" id="text_space">Content of the page.</p>
</div>
</center>
<hr />
<center><input type="text" class="title_box" placeholder="Title" id="title_box" /></center>
<textarea class="textarea" id="text_box"></textarea>
<input type="submit" value="Save" onclick="saveText()" />
<input type="submit" value="br" onclick="br()" />
<script>
function saveText(){
var title = document.getElementById("title_box").value;
var text = document.getElementById("text_box").value;
document.getElementById("title_space").innerHTML = title;
document.getElementById("text_space").innerHTML = text;
}
function br(){
var actualtext = document.getElementById("text_box").value;
var processedtext = actualtext + "<br />";
document.getElementById("text_box").innerHTML = processedtext;
}
</script>
</body>
</html>
When you're updating the text area, instead of:
document.getElementById("text_box").innerHTML = processedtext;
Use:
document.getElementById("text_box").value = processedtext;
Try to add this to your JavaScript code just before changing the text
text = text.replace(/\r?\n/g, '<br>');
Line breaks are \r\n or \n while HTML line break is <br> and that is the problem.
This in case I understood your question correctly.
Here is the code running
Related
Basically, I have to create a button that when clicked, I need to retrieve all the paragraphs within the div and make their background highlighted.
Then I have to write the corresponding JS code (in an unobtrusive manner) to link the button to a function that highlights the paragraphs when clicked.
The button should act as a “toggle”, that is, if the paragraphs are already highlighted, then clicking the button unhighlight them. If the paragraphs aren’t highlighted, then clicking the button highlights them. The button’s text should change to reflect this so it should either say click to highlight or click to unhighlight. So far, I'm trying to create a function that iterates over these paragraphs but the highlight isn't working
** I know that the mark tag in html would highlight a text is there any way i can add that to my js code? **
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="task2.js"></script>
<style>
#poem {
padding: 10px;
margin-bottom: 10px;
color: blue;
font-size: 1.25em;
font-family: sans-serif;
background-color: silver;
border: 1px dashed black;
width: 30%;
}
</style>
</head>
<!- Modify code to add a button ->
<body>
<div id="poem">
<h2> How Many, How Much </h2>
<h4> by Shel Silverstein </h4>
<p> How many slams in an old screen door? </p>
<p> Depends how loud you shut it.</p>
<p> How many slices in a bread?</p>
<p> Depends how thin you cut it.</p>
<p> How much good inside a day? </p>
<p> Depends how good you live 'em. </p>
<p> How much love inside a friend? </p>
<p> Depends how much you give 'em. </p>
</div>
<button id="button"> Click to highlight </button>
</body>
</html>
js code:
function pageLoad() {
var button = document.getElementById("button");
button.onclick = okClick;
}
function okClick() {
var allParas = document.getElementsByTagName("p");
for (var i=0; i < allParas.length; i++) {
if(allParas[i].classList.contains('highlightClass')) {
allParas[i].classList.remove('highlightClass');
} else {
allParas[i].classList.add('highlightClass');
}
}
}
window.onload = pageLoad;
create a new class highlightClass.
if ( allParas[i].classList.contains('highlightClass') ) {
allParas[i].classList.remove('highlightClass');
}else{
allParas[i].classList.add('highlightClass');
}
I'm new to coding, I've learned the very basics of html/css/js/java, at least I thought I had, until I went to make a simple game.
I made a simple choose your own adventure game that worked, as each choice just went to a new page.
Then, I thought I'd make it a bit more complex, so I want to have the user enter their name, and store that to show next to the player's stats.
I've got a dropdown box with 4 choices for characters.I want to have Strength/Mana/Lives stats and have the player's choice of character to be able to adjust these stats accordingly before the game starts i.e. Male Warrior would have 2 extra Strength, Female Mage 2 extra mana etc.
Then, I'd like an image based on their character choice displayed next to their stats, so that the game can begin.
So far, I've been pulling my hair out in great clumps and have tried many different methods but so far, I've only got to the stage where I place the page with user input into an iframe. I can get to reflect their choices with text, but I can't get an image to load on submit. Ideally I'd like a permanent box in the top corner of the iframe, and have the statistics variables passed into the stats shown alongside the character's image.
I'd really really appreciate any help here, especially if it can be solved using HTML/CSS/JS as I'm not too familiar with JQuery, and would like to keep it as simple as possible really.
I've gone through as many q's and a's as I can to find relevant help, but I'm mainly finding answers for PHP or other languages.
I must apologise in advance for my waffling above, and sloppy coding. (I seriously thought this would be easy heh).
I'm unsure if my code so far will help, but I'll just paste it below anyway.
HTML for the UI page is:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Character Selection</title>
<link rel="stylesheet" href="css/style2.css">
<style>
img {
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<div>
<div id='gamestitle'>
<p>
<img src = "GAMETITLE.jpg"
alt = "Steve's Perilous Capers"/>
</p>
</div>
<br>
</div>
<div class='wrapper'>
<form id='nameForm'>
<div class='form-uname'>
<lable id='nameLable' for='nameField'>Create a username:</lable>
<input id='nameField' type='text' maxlength='25'></input>
</div>
<div class='form-sub'>
<button id='subButton' type='button'>Enter your name!</button>
</div>
</form>
<div>
<p id='result'></p></div>
</div>
<div>
</div>
<div>
<form>
Select your Hero please:
<select id="mySelect">
<option>Male Warrior</option>
<option>Male Mage</option>
<option>Female Warrior</option>
<option>Female Mage</option>
</select>
<br><br>
<input type="button" onclick="getOption()" value="Confirm">
</form>
</div>
<script src="js/index.js"></script>
<script>
document.getElementById("demo").innerHTML =
obj.options[obj.selectedIndex].text;
</script>
<p id="demo"></p>
</body>
</html>
The CSS is:
body {
margin: auto;
text-align: center;
}
li {
list-style:none;
}
li.fields {
margin: 0;
padding: 1em 0;
}
li.title {
cursor: pointer;
font-weight: bold;
font-size : 1.5em;
line-height: 2em;
background: #e3e3e3;
border-bottom: 1px solid #c5c5c5;
border-top: 1px solid white;
}
.gamestitle {
max-width: 100%;
margin: auto;
}
.hide { display: none;}
.result {
height: 200px;
width: 50%;
background-color: powderblue;
}
The JS file: (I've tried using icons and background image but I couldn't get them to show)
// the function which handles the input field logic
function getUserName() {
var nameField = document.getElementById('nameField').value;
var result = document.getElementById('result');
if (nameField.length < 3) {
result.textContent = 'Username must contain at least 3 characters';
//alert('Username must contain at least 3 characters');
} else {
result.textContent = 'Your Hero is: ' + nameField;
//alert(nameField);
}
}
function getOption() {
var obj = document.getElementById("mySelect");
document.getElementById("demo").innerHTML =
obj.options[obj.selectedIndex].text;
}
function swapImage(){
var image = document.getElementById("imageToSwap");
var dropd = document.getElementById("dd");
image.src = dropd.value;
};
// use an eventlistener for the click event
var subButton = document.getElementById('subButton');
subButton.addEventListener('click', getUserName, false);
var subButtonTwo = document.getElementById('subButtonTwo');
subButtonTwo.addEventListener('click', getOption, false);
$(function () {
$.widget("custom.iconselectmenu", $.ui.selectmenu, {
_renderItem: function (ul, item) {
var li = $("<li>"),
wrapper = $("<div>", {text: item.label});
if (item.disabled) {
li.addClass("ui-state-disabled");
}
$("<span>", {
style: item.element.attr("option-style"),
"class": "ui-icon " + item.element.attr("data-class")
})
.appendTo(wrapper);
return li.append(wrapper).appendTo(ul);
}
});
$("#mySelect")
.iconselectmenu()
.iconselectmenu("menuWidget")
.addClass("ui-menu-icons avatar");
});
/*
function getcurrentChoice() {
var characterSelection = ['MaleWarrior'], ['MaleMage'], ['FemaleWarrior'], ['FemaleMage'];
var currentChoice = document.getElementById('currentChoice').value;
var resultChoice = document.getElementById('resultChoice');
var subButtons = document.getElementById('subButtons');
subButtons.addEventListener('click', getcurrentChoice, false);
}
*/
Sorry for the messy coding, it's not helped that I've tried so many workarounds for each problem I've encountered that I've lost track of what is and isn't working.
I'm pretty sure this is out of control by now, and a waste of your time, but I'm so confused. I'm sure i'm over complicating the matter.
Thanks in advance again,
Steve.
Check this:
https://jsfiddle.net/digitalrevenge/q9z1x6vv/
I've added an img src and made some changes to your JS.
I'm not sure if it does exactly what you want but there's no harm in giving it a try ;)
I am not sure how to do this in Javascript, but I have achieved it with jQuery, maybe you can adapt it to Javascript if you like.
Basically...
Give each option a value
On selection, or change, empty div#change_this, and check for the value
If value = # then add html code to div#change_this
You can change the image/add in the stats, I just used some filler.
You will also need to add css and all that, if you have any specific questions about that, please let me know.
Functionality is there though.
Best,
Levi
body {
margin: auto;
text-align: center;
}
li {
list-style:none;
}
li.fields {
margin: 0;
padding: 1em 0;
}
li.title {
cursor: pointer;
font-weight: bold;
font-size : 1.5em;
line-height: 2em;
background: #e3e3e3;
border-bottom: 1px solid #c5c5c5;
border-top: 1px solid white;
}
.gamestitle {
max-width: 100%;
margin: auto;
}
.hide {
display: none;
}
.result {
height: 200px;
width: 50%;
background-color: powderblue;
}
<div>
<div id='gamestitle'>
<img src = "GAMETITLE.jpg" alt = "Steve's Perilous Capers"/>
</div>
<br>
</div>
<div class='wrapper'>
<form id='nameForm'>
<div class='form-uname'>
<lable id='nameLabel' for='nameField'>Create a username:</lable>
<input id='nameField' type='text' maxlength='25'></input>
</div>
<div class='form-sub'>
<button id='subButton' type='button'>Enter your name!</button>
</div>
</form>
<div>
<p id='result'></p>
</div>
</div>
<div>
<form>
Select your Hero please:
<select name="hero_type" id="mySelect">
<option value="0">Male Warrior</option>
<option value="1">Male Mage</option>
<option value="2">Female Warrior</option>
<option value="3">Female Mage</option>
</select>
<br><br>
<input type="button" onclick="getOption()" value="Confirm">
</form>
</div>
<div id="change_this">
<p>Yayyy, Male Warrior.</p> <img alt="" src="http://via.placeholder.com/350x150">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('select[name="hero_type"]').click(function() {
$('#change_this').empty();
if ($('select[name="hero_type"]').val() == "0"){
$('#change_this').append('<p>Yayyy, Male Warrior.</p> <img alt="" src="http://via.placeholder.com/350x150">')
}
if ($('select[name="hero_type"]').val() == "1"){
$('#change_this').append('<p>Yayyy, Male Mage.</p> <img alt="" src="http://via.placeholder.com/350x150">')
}
if ($('select[name="hero_type"]').val() == "2"){
$('#change_this').append('<p>Yayyy, Female Warrior</p> <img alt="" src="http://via.placeholder.com/350x150">')
}
if ($('select[name="hero_type"]').val() == "3"){
$('#change_this').append('<p>Yayyy, Female Mage</p> <img alt="" src="http://via.placeholder.com/350x150">')
}
})
});
</script>
The src attribute of an image tag points to the location of the image file to use.
You should be somewhat aware of this as your code contains:
<img src = "GAMETITLE.jpg" alt = "Steve's Perilous Capers"/>
To change the image, simply change the src attribute to point to the location of the new image.
The source of an image tag can be accessed and changed via:
document.getElementById("imageId").src="fileToUse";
This means you need to add an id to your image tag as so:
<img src = "GAMETITLE.jpg" alt = "Steve's Perilous Capers" id="imageId"/>
In your case, you want to get the image src from a select field. This means you need to tie the image file locations to your select form as values.
<select id="mySelect">
<option value="location-of-this-image.png">Male Warrior</option>
<option value="location-of-this-image.png">Male Mage</option>
<option value="location-of-this-image.png">Female Warrior</option>
<option value="location-of-this-image.png">Female Mage</option>
</select>
To use these values and assign them to the image src:
document.getElementById("imageId").src=document.getElementById("mySelect").value;
If you correctly id your image and select form, give the select form proper values, and put the above line of code in the function you call when choosing and image, your image should change.
Important Note
JQuery is a JavaScript library and isn't part of the base language. To use JQuery, you must import it in your html code. You seem to be using JQuery functions, but I don't see where you imported JQuery. This may be causing you problems/breaking your code.
If you do have JQuery imported, the above code can be rewritten using JQuery rather than vanilla JavaScript and it'll look a lot cleaner.
I am new all around HTML and JavaScript. Now I am trying to build a simple program that get input from the command line by the user and print it on the big console window. Now when I insert a simple text it does not print nothing into the box. Is there a special object should I use?
this is my code:
</head>
<body>
<img src="img/Mellanox_logo.jpg" alt="logo" align="middle">
<h1>Menu</h1>
<div id="container1" >
<div id="console" >
<p>
<script>
function showVal(){
var tmp = document.lineform.command_line.value;
document.getElementsByName('command_line').value = tmp;
}
</script>
</p>
</div>
<div >
<form id="form1" name="lineform" >
<input id="commandline" type="text" name="command_line" placeholder="Command line" onclick="showVal()" >
</form>
</div>
</div>
</body>
</html>
this is the css:
h1{
color: black;
text-align: left;
}
p{
color: black;
text-align: left;
font-size: 20px;
}
#container1{
width:1300px ;
}
#form1{
width:1300px ;
}
#console{
border:5px solid dodgerblue;
background-color: white;
height: 650px ;
padding-left: 5px;
margin-bottom: 5px;
position: relative;
width: inherit;
}
#commandline{
width: inherit;
border: 5px solid dodgerblue;
height: 30px;
padding-left: 5px;
font-size: 18px;
position: absolute;
}
this is how the command line and the window looks like:
1.- For this case i think you should be using getElementById instead of getElementsByName.
2.- I'd recommend not using a form, but instead have the input in the div's "root".
3.- A text input doesnt have a onclick (or at least it doesn't do what you want it to do)
4.- Add a button type input that executes the code through onclick="blabla();"
5.- i'd recommend putting your script at the end of the page since it works with the DOM and you're not using JQuery.
6.- add an id to the <p> element inside of the console <div>
<body>
<h1>Menu</h1>
<div id="container1">
<div id="console">
<p id="console_content">
</p>
</div>
<div>
<input id="commandline" type="text" name="command_line" placeholder="Command line">
<input id="commandButton" type="button" name="command_button" value="confirm" onclick="showVal();">
</div>
</div>
</body>
7.- new script:
<script>
function showVal() {
var tmp = document.getElementById("commandline").value;
document.getElementById('console_content').innerHTML += (tmp + "<br/>");
}
</script>
Here's a JFiddle so you can see it works:
https://jsfiddle.net/bLehLrum/
The function you are using returns an HTMLCollection, you need to the following:
Change,
document.getElementsByName('command_line').value = tmp;
To
document.getElementsByName('command_line')[0].value = tmp;
This gets the first element in the array, notice how there is an s at the end of getElements which suggests plural. This should help you in the future.
Reading Material
getElementsByName
Exdending Script47 answer, The problem is you are taking the value from input field and setting the same value again to it, That's why you are seeing any change/affect.
If by the box you mean the console, you should change your function with this
function showVal(){
// get the value of the input
var tmp = document.getElementById('commandline').value;
// add to the innerHTML of the console the tmp value
document.getElementById('console').innerHTML += "<p>"+tmp+"</p>";
}
document.getElementById
Your code try to reassign the value of command_line with the same value.
document.lineform.command_line.value could be the same as document.getElementsByName('command_line')[0]
I've been trying to do a radio button checker with HTML and java script. When I click the 'check' button, it changes the inner-html to a paragraph. For some reason, the text only shows for about a half second then disappears.
JS file:
function runQuestionCheck() {
var question_one_answer = 1;
var question_two_answer = 1;
var question_three_answer = 1;
var question_one_explanation = "Text explaining why that's stupid!";
var question_two_explanation = " ";
var question_three_explanation = " ";
var question_one = document.getElementById("question_1").childNodes;
if (question_one[question_one_answer].isChecked) {
document.getElementById("q1_response").class = "correct";
document.getElementById("q1_response").innerHTML = "Correct!";
}
else
{
document.getElementById("q1_response").innerHTML = ("Sorry, that's incorrect." + question_one_explanation);
}
}
HTML:
<!DOCTYPE html>
<html>
<!-- Init CSS -->
<style>
html {
background-image: url("../Pictures/bg_france.png");
background-repeat: no-repeat;
background-size: cover;
background-attachment: fixed;
}
.center {
margin-left: auto;
margin-right: auto;
width: 20%;
}
.right {
position: absolute;
right: 1cm;
}
.left {
position: absolute;
left: 1cm;
}
.button_left {
position: absolute;
left: 1cm;
color: blue;
}
.button_right {
position: absolute;
right: 1cm;
color: blue;
}
.correct {
color: green;
}
.incorrect {
color: red;
}
</style>
<!-- Init head -->
<head>
<a href="home.html">
<div class="button_left">
Back to Home
</div>
</a>
<a href="sub_france.html">
<div class="button_right">
Highlight facts
</div>
</a>
<title>
France
</title>
<link rel="icon" type="image/png" href="../Pictures/beck_icon.png">
</head>
<!-- Init question script -->
<script type="text/javascript" src="../JavaScripts/questions_spain.js"></script>
<!-- Init body -->
<body>
<br>
<FONT FACE="arial">
<!-- Title -->
<h1>
America and France
</h1>
<!-- Body/Info -->
<p>
This is where the info would go.
</p>
<br>
<!-- Questions -->
<hr>
<h1>Comprehension Questions</h1>
<form id="question_1">
This is the first question!
<br>
<input type="radio" name="color" value="q1_one">Answer one<br>
<input type="radio" name="color" id="q1_two" value="green">Answer two<br>
<input type="radio" name="color" id="q1_three" value="blue">Answer three<br>
</form>
<p id="q1_response"></p>
<br>
<form id="question_2">
This is the second question!
<br>
<input type="radio" name="color" value="q2_one">Answer one<br>
<input type="radio" name="color" id="q2_two" value="green">Answer two<br>
<input type="radio" name="color" id="q2_three" value="blue">Answer three<br>
</form>
<p id="q2_response"></p>
<br>
<form id="question_3">
This is the third question!
<br>
<input type="radio" name="color" value="q3_one">Answer one<br>
<input type="radio" name="color" id="q3_two" value="green">Answer two<br>
<input type="radio" name="color" id="q3_three" value="blue">Answer three<br>
</form>
<br>
<form>
<button onclick="runQuestionCheck()">Check answers!</button>
</form>
<p id="q3_response"></p>
<br>
</FONT>
</body>
</html>
The reason you're seeing only a flash of text is because the text is being displayed, and then the page is immediately being refreshed. That's caused by the fact that your check button is inside a form. Since the form doesn't have an action or a method set, it defaults to submitting to the current page, via GET, which is basically the same as refreshing the page.
Looking at your code, you have a lot of forms that you probably don't need. You're not sending the data anywhere, you're just checking it locally in JavaScript. However, to remove all of them, your JavaScript code would need to be significantly overhauled, so to avoid that you can solve this problem either of these two ways:
Removing the form from your button
Right now it's not doing anything at all. Just get rid of it and you won't have a problem. Replace
<form>
<button onclick="runQuestionCheck()">Check answers!</button>
</form>
With
<button onclick="runQuestionCheck()">Check answers!</button>
Or, Add a type attribute to the button
The button defaults to being a submit button, which will submit whatever form it's in when it's clicked. That's what we want to avoid, so you can instead set it to be just a normal button, like this:
<form>
<button onclick="runQuestionCheck()" type="button">Check answers!</button>
</form>
If you want to keep the form, then this is your best option.
Your code has some other problems, too.
Your style should go in the head.
Your links (Back to Home and Highlight facts) should not be in the head, they should be in the body. Content never goes in the head.
Your script can't just be in the middle of nowhere. It has to go in either the head or the body. Nowadays it's generally recommended to put it in the body.
You shouldn't use FONT tags to style your text, you should use CSS. To put everything in Arial, you can put this in your style tag:
body {
font-family: arial;
}
Your JavaScript will encounter an error. The correct way to change an element's class in JavaScript is className. Replace this:
document.getElementById("q1_response").class = "correct";
With this:
document.getElementById("q1_response").className = "correct";
I am fairly new to Javascript and am trying to write an extension for Chrome. I am struggling with one aspect. Please note that the HTML comes from another webpage over which I have no control so I cannot modify it unless I do it programmatically. Also, I have shown three text items in the example below, but this could be as few as one or many more separated by "br". The HTML is as below:
<div class = "cls" id = "1234">
<quote>...</quote>
"Text to hide/show 1"
<br style="font-size: medium; height: auto; line-height: normal;">
"Text to hide/show 2"
<br style="font-size: medium; height: auto; line-height: normal;">
"Text to hide/show 3"
</div>
The Javascript code is as follows:
function processQuotes() {
$('.cls quote').each(function() {
var $quote = $(this);
var userId = $quote.parent().first().text(); /* For example */
/* See whether user is blocked */
if(blockUser[userId]) {
/* Hide text and br elements */
} else {
/* Show text and br elements */
}
});
}
I want to be able to hide the section from "Text to hide/show 1" to "Text to hide/show 3". I envisaged using the JQuery $var.Hide() and $var.Show() methods but I am struggling with how to get the parts I want to hide into $var.
Any help would be gratefully received.
Thanks,
Richard
I worte a sample, maybe could help:
<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.11.1.min.js" type="text/javascript" ></script>
</head>
<body>
<div class = "cls" id = "1234">
<quote>...</quote>
<p style="font-size: medium; height: auto; line-height: normal;">"Text to hide/show 1"</p>
<br />
<p style="font-size: medium; height: auto; line-height: normal;">"Text to hide/show 2"</p>
<br />
<p>"Text to hide/show 3"</p>
</div>
<script>
for(var i=0; i<3; i++){
(function(i){
$("#1234 p").eq(i).click(function(){
$("#1234 p").show();
$("#1234 p").eq(i).hide();
});
})(i);
}
</script>
</body>
</html>