I already have a function that adds content to a div once an image is clicked; however, I want the content to be removed once the same image is clicked a second time. Is there a simple way to do this?
Is there also a way for the function that adds content to also appear with a number field next to it?
Here is the function that I used to add content.
function frenchBread(){
var div = document.getElementById("orderBox");
div.innerHTML = div.innerHTML + "French Bread" + "<br>";
}
Assign a variable to determine if the image was clicked or not.
Edit
Forgot to assign is_clicked :)
Edit Again
Added the input field next to the "Frech Bread" text.
var is_clicked = false;
function frenchBread(){
var div = document.getElementById("orderBox");
var curr = div.innerHTML, frenchy = 'French Bread <input type="number" name="amount"><br>';
if ( is_clicked ) {
var tmp = div.innerHTML;
curr = tmp.replace(frenchy, "");
div.innerHTML = curr;
is_clicked = false;
} else {
div.innerHTML = curr + frenchy
is_clicked = true;
}
}
<img src="" style="width: 30px; height: 30px; background: black;" onclick="frenchBread()" />
<div id="orderBox">
An item here <br />
</div>
You could just check for the content in innerHTML:
function frenchBread() {
var div = document.getElementById("orderBox");
if(var.innerHTML == "") {
div.innerHTML += "French Bread" + "<input type='number' /><br />";
} else {
div.innerHTML = "";
}
}
Edit: even shorter with the ternary operator, although less readable:
function frenchBread() {
var div = document.getElementById("orderBox");
div.innerHTML = if(var.innerHTML == "") ? "French Bread" + "<input type='number' /><br />" : "";
}
Edit: added the number field in both versions.
Related
I am making a little project for my self. So basically its main function is to create a base counter for each game.
For example: If there are two players it should create three bases. (This is for the card game "smash up" if that helps you understand better.) But when the Buttons populate they all only effect the last input. I can not figure out how to make them effect their respective inputs.
The problem I am having is that every button I click only effects the last input.
<html>
<title> Base Maker </title>
<body>
<div>
<hl> Score Keeper </h1>
<hr>
<input type = "text" placeholder = "How many players?">
<button id = "enter" onclick = "baseMaker()">
Enter
</button>
</div>
<p></p>
</body>
</html>
var parent = document.querySelector("p");
var input = document.querySelector("input");
var enter = document.getElementById("enter");
function baseMaker()
{
for(var i = 0; i <= input.value; i++)
{
//base
var base = document.createElement("p");
base.textContent = "Base " + (i + 1) + ":";
//score
var score = document.createElement( "input");
score.setAttribute("id", "score" + i);
score.value = 20;
//upbutton
var upButton = document.createElement( "button");
upButton.textContent = "+";
upButton.setAttribute("id", "upButton" + i)
upButton.addEventListener('click', function() {
score.value++; });
//downbutton
var downButton = document.createElement( "button");
downButton.textContent = "-";
downButton.setAttribute("id", "downButton" + i)
downButton.addEventListener('click', function() {
score.value--; });
//populate data
parent.appendChild(base);
parent.appendChild(score);
parent.appendChild(upButton);
parent.appendChild(downButton);
}
input.value = "";
}
This is a common thing to run into especially when not using a framework in javascript.
I am not sure why this happens but when a function is defined directly in a loop, the closure for these created functions becomes whatever it is after the last iteration. I believe it is because the closure for each callback function is only "sealed up" (for lack of a better word) at the end of the loop-containing-function's execution which is after the last iteration. It's really beyond me, though.
There are some easy ways to avoid this behavior:
use bind to ensure a callback gets called with the correct input (used in solution at bottom)
create a function which creates a handler function for you and use that in the loop body
function createIncrementHandler(input, howMuch){
return () => input.valueAsNumber += howMuch;
}
/// then in your loop body:
downButton.addEventListener('click', createIncrementHandler(score, 1));
get the correct input by using the event parameter in the handler
downButton.addEventListener('click', (event) => event.target.valueAsNumber += 1);
make the entire body of the loop into a function, for example:
function createInputs(i) {
//base
var base = document.createElement("p");
base.textContent = "Base " + (i + 1) + ":";
//score
var score = document.createElement("input");
score.type = "number";
score.setAttribute("id", "score" + i);
score.value = 20;
//upbutton
var upButton = document.createElement( "button");
upButton.textContent = "+";
upButton.setAttribute("id", "upButton" + i)
upButton.addEventListener('click', function() {
score.value++; });
//downbutton
var downButton = document.createElement( "button");
downButton.textContent = "-";
downButton.setAttribute("id", "downButton" + i)
downButton.addEventListener('click', function() {
score.value--; });
//populate data
parent.appendChild(base);
parent.appendChild(score);
parent.appendChild(upButton);
parent.appendChild(downButton);
}
Here is a full example of one of the possible fixes.
<html>
<title> Base Maker </title>
<body>
<div>
<hl> Score Keeper </h1>
<hr>
<input type="text" placeholder="How many players?">
<button id="enter" onclick="baseMaker()">
Enter
</button>
</div>
<p></p>
<script>
var parent = document.querySelector("p");
var input = document.querySelector("input");
var enter = document.getElementById("enter");
function incrementInput(input, byHowMuch) {
input.valueAsNumber = input.valueAsNumber + byHowMuch;
}
function baseMaker() {
for (var i = 0; i <= input.value; i++) {
//base
var base = document.createElement("p");
base.textContent = "Base " + (i + 1) + ":";
//score
var score = document.createElement("input");
score.type = "number";
score.setAttribute("id", "score" + i);
score.value = 20;
//upbutton
var upButton = document.createElement("button");
upButton.textContent = "+";
upButton.setAttribute("id", "upButton" + i)
upButton.addEventListener('click', incrementInput.bind(null, score, 1));
//downbutton
var downButton = document.createElement("button");
downButton.textContent = "-";
downButton.setAttribute("id", "downButton" + i)
downButton.addEventListener('click', incrementInput.bind(null, score, -1));
//populate data
parent.appendChild(base);
parent.appendChild(score);
parent.appendChild(upButton);
parent.appendChild(downButton);
}
input.value = "";
}
</script>
</body>
</html>
I will do that this way :
const
AllBases = document.querySelector('#bases')
, bt_Start = document.querySelector('#game-go')
, bt_newGame = document.querySelector('#new-game')
, playerCount = document.querySelector("#play-start > input")
;
playerCount.value = ''
playerCount.focus()
playerCount.oninput = () =>
{
playerCount.value.trim()
bt_Start.disabled = (playerCount.value === '' || isNaN(playerCount.value))
playerCount.value = (bt_Start.disabled) ? ''
: (playerCount.valueAsNumber > playerCount.max) ? playerCount.max
: (playerCount.valueAsNumber < playerCount.min) ? playerCount.min
: playerCount.value
}
bt_newGame.onclick = () =>
{
playerCount.value = ''
playerCount.disabled = false
bt_Start.disabled = true
bt_newGame.disabled = true
AllBases.innerHTML = ''
playerCount.focus()
}
bt_Start.onclick = () =>
{
playerCount.disabled = true
bt_Start.disabled = true
bt_newGame.disabled = false
for(let i = 0; i <= playerCount.valueAsNumber; i++)
{
let base = document.createElement('p')
base.countValue = 20 // create a counter property on <p>
base.innerHTML = `Base ${i+1} : <span>${base.countValue}</span> <button>+</button> <button>−</button>\n`
AllBases.appendChild(base)
}
}
AllBases.onclick = ({target}) =>
{
if (!target.matches('button')) return // verify clicked element
let countElm = target.closest('p')
if (target.textContent==='+') countElm.countValue++
else countElm.countValue--
countElm.querySelector('span').textContent = countElm.countValue
}
#bases p span {
display : inline-block;
width : 6em;
border-bottom : 2px solid aqua;
padding-right : .2em;
text-align : right;
margin : 0 .3em;
}
#bases p button {
width : 2em;
margin : 0 .1em;
cursor : pointer;
}
<hr>
<hl> Score Keeper </h1>
<hr>
<div id="play-start" >
<input type="number" placeholder="How many players?" min="2" max="4">
<button id="game-go" disabled> Enter </button>
<button id="new-game" disabled> new </button>
</div>
<hr>
<div id="bases"></div>
If it helps, I can add more explanations
I am trying to make a blog type of website. I got to a point where you can enter text into a textarea box and then click submit to have it appear below. However, I have come to a problem where it does not save the format of the input (notably for me, transforms paragraphs into spaces). I have read that this would require a rich-text editor, and I have tried TinyMCE but it gives a lot more options than needed or which would be able to be used in my case. Is there a simple way to fix this problem? If not, what is the best way to go about this?
I am mainly after the paragraph, tab, and multiple spaces formatting, everything else is currently not needed.
Here is what I currently have that is related:
HTML
<!-- Blog Section -->
<div class="itemBlog">
<h2 id="itemBlogTitle">My Blog</h2>
<textarea type="text" rows="10" cols="100" class="blogTextArea" id="blogInput"></textarea>
<div onclick="newBlog()" class="addBtn">Add</div>
<ul id="blogList"></ul>
</div>
<script src="itemblog.js"></script>
JavaScript
// Create a new blog item when clicking on the "Add" button
function newBlog() {
var li = document.createElement("li");
var inputValue = document.getElementById("blogInput").value;
var t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue != '') {
document.getElementById("blogList").appendChild(li);
}
document.getElementById("blogInput").value = "";
var textarea = document.createElement("TEXTAREA");
var txt = document.createTextNode("\u00D7");
textarea.className = "close";
textarea.appendChild(txt);
li.appendChild(textarea);
for (i = 0; i < close.length; i++) {
close[i].onclick = function () {
var div = this.parentElement;
div.style.display = "none";
}
}
}
EDIT: white-space: pre-wrap; fixed it, thank you
If you want something simple, just save into your database the input content with id description, after that it will respect the paragraph and spaces.
JQUERY
$('#test').keyup(function() {
var text = $(this).val();
var description = text.replace(/ /g, ' ').replace(/[\n]/g, '<br>');
$('#text').html(description)
$('#description').val(description)
});
<textarea id="test" cols="30" rows="10"></textarea>
<input id="description" name="description" hidden>
<div id="text"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
js
function formatString(el) {
var str = el.value;
str = str.replace(/ /g, ' ').replace(/[\n]/g, '<br>');
document.getElementById('text').innerHTML = str;
document.getElementById('description').value = str;
}
<textarea onkeyup="formatString(this)" cols="30" rows="10"></textarea>
<input id="description" name="description" hidden>
<div id="text"></div>
You can create a function nl2br() as folows:
function nl2br (str, is_xhtml) {
if (typeof str === 'undefined' || str === null) {
return '';
}
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}
You can see more here
I have a quiz system that is created in JS. I am using input elements to display each quiz option. I am trying to make it so when you click submit, it will loop through each input element and set the styling of the input text to green if it is a correct answer and red if it an incorrect answer. I am having trouble actually getting the text that is next to the input value however.
Below is a picture of the quiz:
https://gyazo.com/1ba5245de2c5c6f96bd728e31aeb0899
HTML:
<!DOCTYPE html>
<html>
<head>
<link href ="style.css" rel ="stylesheet">
<!-- <link href="https://fonts.googleapis.com/css?family=OpenSans" rel="stylesheet"> -->
<script src = "main.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h1>Chapter 1 Quiz</h1>
<form id = "quiz" name = "quiz">
<p class = "questions">What is the capital of Rhode Island?</p>
<input id = "textbox" type = "text" name = "question1">
<p class = "questions">What is the capital of Connecticut?</p>
<input type = "radio" id = "mc" name = "question2" value = "Hartford"> Hartford<br>
<input type = "radio" id = "mc" name = "question2" value = "Heartford"> Heartford<br>
<p class = "questions">What is the capital of New York?</p>
<input type = "radio" id = "mc" name = "question3" value = "Albany"> Albany<br>
<input type = "radio" id = "mc" name = "question3" value = "All Benny's"> All Benny's<br>
<input id = "button" type = "button" value = "Finish" onclick = "check();">
</form>
<div id = "after_submit">
<p id = "number_correct"></p>
<p id = "message"></p>
</div>
</html>
</body>
JAVASCRIPT:
function check(){
var question1 = document.quiz.question1.value;
var question2 = document.quiz.question2.value;
var question3 = document.quiz.question3.value;
var correct = 0;
var total_questions = 3;
if (question1 == "Providence") {
correct++;
}
if (question2 == "Hartford") {
correct++;
}
if (question3 == "Albany") {
correct++;
}
var score;
if (correct == 0) {
score = 2;
}
if (correct > 0 && correct < total_questions) {
score = 1;
}
if (correct == total_questions) {
score = 0;
}
$( "input" ).each(function( index ) {
console.log( index + ": " + $( this ).val() );
// CHANGE THE STYLING HERE. VAL DOES NOT GET THE TEXT OF INPUT AND NIETHER DOES .text()
});
document.getElementById("after_submit").style.visibility = "visible";
document.getElementById("message").innerHTML = "Correct Answers:";
document.getElementById("number_correct").innerHTML = "Score: " + correct + " / " + total_questions + " (" + Math.trunc((correct / total_questions)*100) + "%)";
}
I was thinking I could store the correct answers in the array and if the input has the value then change the styling of the text to green otherwise change it to red.
why simple don't use class:
if(ans == correct) { $(this).toggleClass(corect); correct ++; } if(ans != correct) { $(this).toggleClass(wrong); }
// whidth text color you need on css
This code is not good. I decided to rewrite it with the correct answers in one place. Also I added labels to each input element so that I can manipulate the CSS better.
Here is the JS:
function check(){
var correct = 0;
var total_questions = 3;
var correct_answers = ["Providence", "Hartford", "Albany"];
$( "label" ).each(function( index ) {
console.log( index + ": " + $( this ).text() );
if (correct_answers.includes($( this ).text())) {
this.style.color = 'green'
correct++
} else {
this.style.color = 'red'
}
});
document.getElementById("after_submit").style.visibility = "visible";
document.getElementById("message").innerHTML = "Correct Answers:";
document.getElementById("number_correct").innerHTML = "Score: " + correct + " / " + total_questions + " (" + Math.trunc((correct / total_questions)*100) + "%)";
}
hi that is be done by just adding one else condition
style
.mystyle{
border-color: red;
}
if (question2 == "Hartford") {
correct++;
}
else{
var element = document.getElementById("textbox");
element.classList.add("mystyle");
}
check my fiddle here
click
I have a form in my PHP with JavaScript code to add select elements dynamically, which is working nicely :
<tr><th>Requester</th><td><input type="hidden" name="requester" value="<?php echo $_SESSION['user_id']; ?>"><?php echo $_SESSION['user_descr']; ?></td></tr>
<tr>
<th>User(s) for whom you are requesting the access</th>
<td>
<div id="dynamicUsers">
<?php
$q_users = 'SELECT id,descr,tnumber FROM users ORDER BY descr;';
$prep = $dbh->prepare($q_users);
$prep->execute();
$arrAll = $prep->fetchAll();
echo '<select name="firecallUsers[]">';
foreach($arrAll as $data)
{
echo '<option value="'.$data['id'].'">'.$data['descr'].'</option>';
}
echo '</select>';
?>
</div>
<input type="button" value="Add user" onClick="add_FC_User('dynamicUsers');">
</td>
</tr>
The JavaScript is :
var counter = 1;
var limit = 5;
function add_FC_User(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " users");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = '<select name="firecallUsers[]"><?php
$q_users = 'SELECT id,descr,tnumber FROM users ORDER BY descr;';
$prep = $dbh->prepare($q_users);
$prep->execute();
$arrAll = $prep->fetchAll();
foreach($arrAll as $data)
{
echo '<option value="'.$data['id'].'">'.$data['descr'].'</option>';
}
?></select>';
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
But I would like to add a little "remove" button next to each added element, for example something like this in the javascript :
?></select> remove ';
How can I script this javascript function in order to remove the dynamically-added elements ?
I suppose I have to say something like (remove the child div created in parent div called dynamicUsers, but my child div doesn't have a name/id it seems)
any idea ?
thanks!
PS : I tried this solution 1 (doesn't work) :
I tried to do something like :
1.adding a name to the div in the javascript, e.g :
var newdiv = document.createElement('div'); newdiv.id = "userDiv";
2.creating a function like :
function remove_FC_User(divName){
var child = document.getElementById(userDiv);
var parent = document.getElementById(divName);
parent.removeChild(child);
}
3.creating the remove link in the JS with :
?></select> remove';
but it won't work :(
it's working nicely now with :
function randId() {
return Math.random().toString(36).substr(2, 10);
}
var counter = 1;
var limit = 15;
function add_FC_User(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " users");
}
else {
var newdiv = document.createElement('div');
var randstring = randId();
newdiv.setAttribute("id", randstring);
newdiv.innerHTML = '<select name="firecallUsers[]"><?php
$q_users = 'SELECT id,descr,tnumber FROM users ORDER BY descr;';
$prep = $dbh->prepare($q_users);
$prep->execute();
$arrAll = $prep->fetchAll();
foreach($arrAll as $data)
{
echo '<option value="'.$data['id'].'">'.$data['descr'].'</option>';
}
?></select> remove';
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
thanks a lot for your hints/help !
mmh I managed to make it half-work with :
var newdiv = document.createElement('div');
newdiv.setAttribute("id", "one");
and
?></select> remove';
and
function remove_FC_User(parentDiv, userDiv){
var child = document.getElementById(userDiv);
var parent = document.getElementById(parentDiv);
parent.removeChild(child);
}
the elements get removed successfully, but it changes the remaining elements contents :(
maybe I need to generate a random "id" and avoid using "one" for each ?
how can I do that ? with a random function ? or a count ?
You could set an id of your newly added element and then use it with your onclick:
newdiv.setAttribute("id", "SOME_GENERATED_ID");
and then
remove;
Or you could use a class or name or data-* attribute. Or you could just remove the sibling of your "a" attribute etc.
I have a page of thirty text boxes with Id's roughly correlating to _Q0/_Q1/_Q2/_Q3 etc.
I'm trying to design a JS code that will hide all but the first box, and then will reveal the next textbox as the previous one is filled in.
Here is my code:
$(function () {
for(var i=1;i<30;i++){
var t = i
document.getElementById("_Q" + t).style.visibility = 'hidden';
};
var idNumber = 0
document.getElementById("_Q"+idNumber).onKeyUp(function(){return boxAdder()});
function boxAdder(){
idNumber = idNumber+1;
document.getElementById("_Q" + idNumber).style.visibility = 'block';
document.getElementById("_Q" + idNumber).onKeyUp(function(){return boxAdder()});
};
});
So far all the boxes are hidden excluding the first box. However when I write into the first box nothing happens. I'm not entirely sure where this code is going wrong.
Edit: sample JSFiddle: http://jsfiddle.net/8b7pH/3/
Solved! Here is the final code:
$(function () {
for(var i=1;i<=5;i++){
var t = i;
document.getElementById("_Q" + t).style.visibility = 'hidden';
// document.getElementById("_Q" + idNumber).onkeyup = function(){console.log("hi"); return boxAdder(t+1);};
}
var idNumber = 0;
document.getElementById("_Q0").onkeyup = function(){console.log("hi"); return boxAdder(0);};
function boxAdder(numm){
console.log("ho");
//idNumber = idNumber+1;
document.getElementById("_Q" + numm).style.visibility = 'visible';
document.getElementById("_Q" + numm).onkeyup = function(){return boxAdder(numm+1);};
}
});
This does what you want:
$(function () {
var $boxes = $("[id^=_Q]").hide().keyup(function(){ //Hide all, then attach keyup
var i = $(this).index(); //Index of the box being typed
$boxes.eq(i+1).show(); //Get and show next textbox
});
$boxes.first().show(); //Show next textbox
});
Btw $("[id^=_Q]") selects all elements whose id starts with _Q
Working OK here: http://jsfiddle.net/edgarinvillegas/8b7pH/7/
Cheers
My suggestion is that you assign a function to the onchange event of the text boxes, and give each one an id as follows:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
function textChange(){
// Get the number of the caller's id
var inputNumber = $(event.target).attr('id').split("txt")[1];
// Select the next input by increasing the inputNumber and set its "display" attr to block
$("#txt" + ++inputNumber).css("display", "block");
}
</script>
<from>
<input type="text" id="txt1" onchange="textChange()" />
<input type="text" style="display:none;" id="txt2" onchange="textChange()" />
<input type="text" style="display:none;" id="txt3" onchange="textChange()" />
<input type="text" style="display:none;" id="txt4" onchange="textChange()" />
<input type="text" style="display:none;" id="txt5" onchange="textChange()" />
</form>
A working example can be found here:
http://jsfiddle.net/WChd8/
Thanks for the fiddle. I've updated it to a working one.
Here's the code:
$(function () {
for(var i=1;i<=5;i++){
var t = i;
document.getElementById("_Q" + t).style.visibility = 'hidden';
}
var idNumber = 0;
document.getElementById("_Q" + idNumber).onkeyup = function(){console.log("hi"); return boxAdder();};
function boxAdder(){
console.log("ho");
idNumber = idNumber+1;
document.getElementById("_Q" + idNumber).style.visibility = 'visible';
document.getElementById("_Q" + idNumber).onkeyup = function(){return boxAdder();};
}
});
The significant change was the syntax for onkeyup: element.onkeyup = function(). Other than that, there were a bunch of missing semicolons that didn't matter. I added console.logs that can obviously be removed.
EDIT
Edgar found a valid bug, so I put in a fix. Basically, remove the onkeyup event as soon as it's called:
document.getElementById("_Q" + idNumber).onkeyup = function(){this.onkeyup = null; return boxAdder();};
function boxAdder(){
idNumber = idNumber+1;
document.getElementById("_Q" + idNumber).style.visibility = 'visible';
document.getElementById("_Q" + idNumber).onkeyup = function(){this.onkeyup = null; return boxAdder();};
}
Note the new this.onkeyup = null; in two places.
This is a javascript only approach, based on what you already had, that also checks for the content written in the input. If is blank, it hides the next one again.
for(var i=0;i<30;i++){
var element = document.getElementById("_Q" + i);
if(element != null)
{
element.onkeyup = function() {
var next = parseInt(this.id.replace("_Q", "")) + 1;
document.getElementById("_Q" + next).style.visibility = (this.value != "" ? "visible" : "hidden");
}
}
if(i>0)
element.style.visibility = 'hidden';
};