I am trying to create a simple "guess the number game" in a web page where a user is the one thinking of the number and the computer is to guess the number(in range 1-100) that the user is thinking (no user input required). I've created four buttons for user to respond to the computer's guess: Start, Guess Higher, Guess Lower, Bingo. I have a problems with this range. If user click button 'Lover' it should became the biggest number (For example, 60 is too high, then computer guess between 1-60)(same with 'Higher'), but can't connect it together. Here is my code:
let computerGuess = 0,
numberOfGuesses = 0;
function writeMessage(elementId, message, appendMessage) {
let elemToUpdate = document.getElementById(elementId);
if (appendMessage) {
elemToUpdate.innerHTML = elemToUpdate.innerHTML + message;
} else {
elemToUpdate.innerHTML = message;
}
};
function newGame() {
computerGuess = 0;
numberOfGuesses = 1;
writeMessage('historyList', '');
document.getElementById('buttonLover').disabled = true;
document.getElementById('buttonHigher').disabled = true;
document.getElementById('buttonBingo').disabled = true;
}
function randomNumber(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
function computerGuessed() {
let compGuess = document.getElementById('compGuess'),
butLover = document.getElementById('buttonLover'),
butHigher = document.getElementById('buttonHigher'),
butBingo = document.getElementById('buttonBingo'),
statusArea = document.getElementById('statusArea'),
historyList = document.getElementById('historyList');
document.getElementById('buttonArea').disabled = true;
butLover.disabled = false;
butHigher.disabled = false;
butBingo.disabled = false;
let a = 1, b = 100;
computerGuess = randomNumber(a, b);
writeMessage('compGuess', '<p>' + computerGuess + '</p>', true);
writeMessage('statusArea', '<p>Choose a number between 1-100 and click the button.</p>');
butLover.addEventListener("click", function () {
writeMessage('historyList', '<li>' + computerGuess + ' (too high)</li>', true);
writeMessage('compGuess', '<p>' + '' + '</p>', false);
computerGuess = randomNumber(a, computerGuess);
writeMessage('compGuess', '<p>' + computerGuess + '</p>', true);
numberOfGuesses++;
});
butHigher.addEventListener("click", function () {
writeMessage('historyList', '<li>' + computerGuess + ' (too low)</li>', true);
writeMessage('compGuess', '<p>' + '' + '</p>', false);
computerGuess = randomNumber(computerGuess, b);
writeMessage('compGuess', '<p>' + computerGuess + '</p>', true);
numberOfGuesses++;
});
butBingo.addEventListener("click", function () {
writeMessage('statusArea', '<p>You got me in ' + numberOfGuesses + ' guesses, I was thinking ' + computerGuess + '. Let\'s go again...</p>');
writeMessage('compGuess', '<p>' + '' + '</p>', false);
document.getElementById('buttonArea').disabled = false;
newGame();
});
}
window.onload = function () {
newGame();
document.getElementById('buttonArea').addEventListener('click', computerGuessed);
};
<div id="game">
<h1>Computer Guessing Game</h1>
<div id="statusArea">
<p>Choose a number between 1-100 and click the button.</p>
</div>
<div id="compGuess">
</div>
<div class="buttons">
<input type="button" value="Start" class="button" id="buttonArea"/>
<input type="button" value="Lover" class="button" id="buttonLover"/>
<input type="button" value="Higher" class="button" id="buttonHigher"/>
<input type="button" value="Bingo" class="button" id="buttonBingo"/>
</div>
<div id="historyArea">
<h2>Computer Previous Guesses</h2>
<ol id="historyList">
</ol>
</div>
</div>
Each time you call computerGuessed() you reset a & b to 1 and 100. Try setting them as global vars (since you're already using global vars), and set them to 1 and 100 on the start of each game.
let computerGuess = 0,
numberOfGuesses = 0,
a=0,
b=100;
function writeMessage(elementId, message, appendMessage) {
let elemToUpdate = document.getElementById(elementId);
if (appendMessage) {
elemToUpdate.innerHTML = elemToUpdate.innerHTML + message;
} else {
elemToUpdate.innerHTML = message;
}
};
function newGame() {
computerGuess = 0;
numberOfGuesses = 1;
a = 0;
b = 100;
writeMessage('historyList', '');
document.getElementById('buttonLower').disabled = true;
document.getElementById('buttonHigher').disabled = true;
document.getElementById('buttonBingo').disabled = true;
}
function randomNumber(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
function computerGuessed() {
let compGuess = document.getElementById('compGuess'),
butLower = document.getElementById('buttonLower'),
butHigher = document.getElementById('buttonHigher'),
butBingo = document.getElementById('buttonBingo'),
statusArea = document.getElementById('statusArea'),
historyList = document.getElementById('historyList');
document.getElementById('buttonArea').disabled = true;
butLower.disabled = false;
butHigher.disabled = false;
butBingo.disabled = false;
computerGuess = randomNumber(a, b);
writeMessage('compGuess', '<p>' + computerGuess + '</p>', true);
writeMessage('statusArea', '<p>Choose a number between 1-100 and click the button.</p>');
}
window.onload = function () {
newGame();
document.getElementById('buttonArea').addEventListener('click', computerGuessed);
let butLower = document.getElementById('buttonLower'),
butHigher = document.getElementById('buttonHigher'),
butBingo = document.getElementById('buttonBingo');
butLower.addEventListener("click", function () {
writeMessage('historyList', '<li>' + computerGuess + ' (too high)</li>', true);
writeMessage('compGuess', '<p>' + '' + '</p>', false);
b = computerGuess;
computerGuessed();
writeMessage('compGuess', '<p>' + computerGuess + '</p>', true);
numberOfGuesses++;
});
butHigher.addEventListener("click", function () {
writeMessage('historyList', '<li>' + computerGuess + ' (too low)</li>', true);
writeMessage('compGuess', '<p>' + '' + '</p>', false);
a = computerGuess;
computerGuessed();
writeMessage('compGuess', '<p>' + computerGuess + '</p>', true);
numberOfGuesses++;
});
butBingo.addEventListener("click", function () {
writeMessage('statusArea', '<p>You got me in ' + numberOfGuesses + ' guesses, I was thinking ' + computerGuess + '. Let\'s go again...</p>');
writeMessage('compGuess', '<p>' + '' + '</p>', false);
document.getElementById('buttonArea').disabled = false;
newGame();
});
};
<div id="game">
<h1>Computer Guessing Game</h1>
<div id="statusArea">
<p>Choose a number between 1-100 and click the button.</p>
</div>
<div id="compGuess">
</div>
<div class="buttons">
<input type="button" value="Start" class="button" id="buttonArea"/>
<input type="button" value="Lower" class="button" id="buttonLower"/>
<input type="button" value="Higher" class="button" id="buttonHigher"/>
<input type="button" value="Bingo" class="button" id="buttonBingo"/>
</div>
<div id="historyArea">
<h2>Computer Previous Guesses</h2>
<ol id="historyList">
</ol>
</div>
</div>
This version disables lower/higher buttons if we've already ruled out those possibilities, and it detects bingo automatically if there is no other option left.
//initialize global variables to keep track of stuff between functions
var min = 1;
var max = 100;
var currentGuess = -1;
function start() {
//reset everything
min = 1;
max = 100;
document.getElementById("historyList").innerHTML = "";
disable("startButton");
enable("lowerButton");
enable("higherButton");
enable("bingoButton");
//and guess
guess();
}
function guess() {
//generate a guess between min and max
currentGuess = rando(min, max);
//disable higher/lower buttons if we've ruled out those possibilities
currentGuess == min ? disable("lowerButton") : enable("lowerButton");
currentGuess == max ? disable("higherButton") : enable("higherButton");
//tell the user the guess
document.getElementById("compGuess").innerHTML = currentGuess;
}
function lower() {
//our guess was too high, so our new max is one lower than that guess
max = currentGuess - 1;
//automatically detect bingo if it's the only possible outcome left and don't bother executing the rest of the lower function
if (max == min) {
currentGuess = min;
return bingo();
}
//record that the guess was too high
document.getElementById("historyList").innerHTML += "<li>" + currentGuess + " (too high)</li>";
guess();
}
function higher() {
//our guess was too low, so our new min is one higher than that guess
min = currentGuess + 1;
//automatically detect bingo if it's the only possible outcome left and don't bother executing the rest of the higher function
if (max == min) {
currentGuess = min;
return bingo();
}
//record that the guess was too low
document.getElementById("historyList").innerHTML += "<li>" + currentGuess + " (too low)</li>";
guess();
}
function bingo() {
//record that the guess was a bingo
document.getElementById("historyList").innerHTML += "<li>" + currentGuess + " (BINGO)</li>";
//only allow start button
enable("startButton");
disable("lowerButton");
disable("higherButton");
disable("bingoButton");
//give the user a breakdown
document.getElementById("compGuess").innerHTML = "You got me in " + document.getElementsByTagName("li").length + " guesses. I was thinking " + currentGuess + ". Let's go again...";
}
//these two functions just make our code easier to read
function disable(id) {
document.getElementById(id).disabled = true;
}
function enable(id) {
document.getElementById(id).disabled = false;
}
<script src="https://randojs.com/1.0.0.js"></script>
<div id="game">
<h1>Computer Guessing Game</h1>
<div id="statusArea">
<p>Choose a number between 1-100 and click the button.</p>
</div>
<div id="compGuess"></div>
<div class="buttons">
<input type="button" value="Start" id="startButton" onclick="start();" />
<input type="button" value="Lower" id="lowerButton" onclick="lower();" disabled/>
<input type="button" value="Higher" id="higherButton" onclick="higher();" disabled/>
<input type="button" value="Bingo" id="bingoButton" onclick="bingo();" disabled/>
</div>
<div id="historyArea">
<h2>Computer Previous Guesses</h2>
<ol id="historyList"></ol>
</div>
</div>
It uses randojs.com to make the randomness easier to read, so if you use this code, make sure you have this in the head tag of your html document:
<script src="https://randojs.com/1.0.0.js"></script>
try the following ...
start.html
<!DOCTYPE html>
<html>
<head>
<script>
function StartGame()
{
aMaxValue = Number(theMaxValueText.value);
window.localStorage.setItem ("theMaxValueToGuess", aMaxValue);
aNumberToGuess = Math.floor ( Math.random() * aMaxValue + 1 );
window.localStorage.setItem ("theNumberToGuess", aNumberToGuess);
aMaxNumberOfTries = Math.floor ( Math.log2 (aMaxValue) + 1 );
window.localStorage.setItem ("theMaxNumberOfTries", aMaxNumberOfTries);
window.localStorage.setItem ("theUserTriesCount", 0);
aPrevGuessesString = "";
window.localStorage.setItem ("thePrevGuessesString", aPrevGuessesString);
document.location.href = "play.html";
}
</script>
</head>
<body>
<h1>Guess a Number</h1>
<div class="form">
<label for="theMaxValueText">Max Value to Guess:</label>
<input type="text" id="theMaxValueText">
<input type="submit" value="Play" id="ExecPlayBtn" onclick="StartGame()">
</div>
</body>
</html>
play.html
<!DOCTYPE html>
<html>
<head>
<script>
var theMaxNumberToGuess = Number ( window.localStorage.getItem ("theMaxValueToGuess") );
// let theMaxNumberOfTries = 0;
// let theNumberToGuess = 0;
// let theUserTriesCount = 0;
function getMaxNumberOfTries() {
return Number ( window.localStorage.getItem ("theMaxNumberOfTries") );
}
function getNumberToGuess() {
return Number ( window.localStorage.getItem ("theNumberToGuess") );
}
function getUserTriesCount() {
return Number ( window.localStorage.getItem ("theUserTriesCount") );
}
function incrUserTriesCount()
{
aUserTriesCount = getUserTriesCount();
++ aUserTriesCount;
window.localStorage.setItem ("theUserTriesCount", aUserTriesCount);
}
function getNumberOfTriesLeft()
{
aMaxNumberOfTries = getMaxNumberOfTries();
aUserTriesCount = getUserTriesCount();
aNumberOfTriesLeft = aMaxNumberOfTries - aUserTriesCount;
return aNumberOfTriesLeft;
}
function getPrevGuessesString() { return window.localStorage.getItem ("thePrevGuessesString"); }
function addToPrevGuessesString (aStr)
{
aPrevGuessesString = getPrevGuessesString();
aPrevGuessesString += (aStr + " ");
window.localStorage.setItem ("thePrevGuessesString", aPrevGuessesString);
}
function PageLoaded()
{
document.getElementById("theMaxNumberToGuessLabel").innerHTML = theMaxNumberToGuess;
// compute values ...
// theNumberToGuess = Math.floor ( Math.random() * theMaxNumberToGuess + 1 );
// theMaxNumberOfTries = Math.floor ( Math.log2 (theMaxNumberToGuess) + 1 );
// theUserTriesCount = 0;
DisplayGameStatus();
}
window.addEventListener ("load", PageLoaded);
function DisplayNumberOfTriesLeft()
{
aNumberOfTriesLeft = getNumberOfTriesLeft();
document.getElementById("theTriesLeftCountLabel").innerHTML = aNumberOfTriesLeft;
}
function DisplayPrevUserGuesses()
{
aPrevGuessesString = getPrevGuessesString();
document.getElementById("theUserPrevGuessesLabel").innerHTML = aPrevGuessesString;
}
function DisplayGameStatus()
{
DisplayNumberOfTriesLeft();
DisplayPrevUserGuesses();
}
function CheckUserGuess()
{
aNumberOfTriesLeft = getNumberOfTriesLeft();
if (aNumberOfTriesLeft <= 0) {
// go to the loose page
}
aNumberToGuess = getNumberToGuess();
aUserGuess = Number(theUserValueText.value);
addToPrevGuessesString ("" + aUserGuess);
if (aUserGuess < aNumberToGuess) {
// retry
document.getElementById("theUserHintMessageLabel").innerHTML =
"retry, the number to guess is > higher"
} else if (aUserGuess > aNumberToGuess) {
// retry
document.getElementById("theUserHintMessageLabel").innerHTML =
"retry, the number to guess is < lower"
} else {
// the user wins !!
document.getElementById("theUserHintMessageLabel").innerHTML =
"you win !! " + aUserGuess + " == " + aNumberToGuess + ""
alert ("you win !! " + aUserGuess + " == " + aNumberToGuess + "");
// go to the win page ...
document.location.href = "youwin.html";
}
// ++ theUserTriesCount;
incrUserTriesCount();
aNumberOfTriesLeft = getNumberOfTriesLeft();
if (aNumberOfTriesLeft <= 0) {
// go to the loose page
document.location.href = "youloose.html";
}
DisplayGameStatus();
}
</script>
</head>
<body>
<div>
<h1>
<label>Guess a Number in the Range ( 0 .. </label>
<label id="theMaxNumberToGuessLabel"></label>
<label>)</label>
</h1>
</div>
<div>
<label>you have </label>
<label id="theTriesLeftCountLabel"></label>
<label> tries left</label>
</div>
<p></p>
<div>
<label for="theUserValueText">Enter your Guess: </label>
<input type="text" id="theUserValueText">
<input type="submit" value="Guess" id="ExecUserGuessBtn" onclick="CheckUserGuess()">
</div>
<p></p>
<div>
<label>Prev Guesses: </label>
<label id="theUserPrevGuessesLabel"></label>
</div>
<p></p>
<div>
<label id="theUserHintMessageLabel"></label>
</div>
</body>
</html>
youloose.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
<h1>
<label>Sorry, You Loose !!</label>
<label>go to </label> Start
</h1>
</div>
</body>
</html>
youwin.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
<h1>
<label>Congrats, You Win !!</label>
<label>go to </label> Start
</h1>
</div>
</body>
</html>
that's all folks ...
Related
I'd like to know why whenever I switch the <input> tag to a <p> tag, my character counter doesn't appear at all. I want the Characters remaining: part to not be inside an <input> tag. I've tried a lot of ways to solve this but hit a wall, I just need another pair of eyes to see this.
What am I doing wrong and how can I solve this? JSFiddle provided for reference.
https://jsfiddle.net/2b38k9zt/
var txtBoxRef = document.querySelector("#txtBox");
var counterRef = document.querySelector("#counterBox");
txtBoxRef.addEventListener("keydown",function(){
var remLength = 0;
remLength = 0 + parseInt(txtBoxRef.value.length);
if(remLength < 0) {
txtBoxRef.value = txtBoxRef.value.substring(0, 200);
return false;
} else if(remLength > 200) {
counterRef.style.color = "red";
}
counterRef.value = "Characters remaining: " + remLength + "/200";
},true);
<textarea style="width: 600px;" id="txtBox"></textarea>
<input type="text" id="counterBox"/>
Set your input to a p element and change this line
counterRef.value = "Characters remaining: " + remLength + "/200";
to
counterRef.innerHTML = "Characters remaining: " + remLength + "/200";
input tag has a value attribute, while for p tag textContent should be used:
var txtBoxRef = document.querySelector("#txtBox");
var counterRef = document.querySelector("#counterBox");
var pRef = document.querySelector("#pBox");
txtBoxRef.addEventListener("keydown",function(){
var remLength = 0;
remLength = 0 + parseInt(txtBoxRef.value.length);
if(remLength < 0) {
txtBoxRef.value = txtBoxRef.value.substring(0, 200);
return false;
} else if(remLength > 200) {
counterRef.style.color = "red";
}
pRef.textContent = "Characters remaining: " + remLength + "/200";
},true);
<textarea style="width: 600px;" id="txtBox"></textarea>
<input type="text" id="counterBox"/>
<p id='pBox'></p>
How can I make sure that audio rows gets added after the video rows with the code below. Note that I want it all in the same table. I assume I shouldn't use prepend() the way I do.
The expected result should look like this if you add 3 video rows and 2 audio rows, no matter what order you add them in:
video 3
video 2
video 1
audio 2
audio 1
var videoCount = 1;
var audioCount = 1;
$('input[type="submit"]').on('click', function(e) {
var type = $('input[name="type"]:checked').val();
if( type == 'video' )
{
var count = videoCount; videoCount++;
}
else
{
var count = audioCount; audioCount++;
}
$('table').prepend('<tr><td>' + type + ' ' + count + '</td></tr>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label><input type="radio" name="type" value="video" checked="checked" /> Video</label>
<label><input type="radio" name="type" value="audio" /> Audio</label>
<input type="submit" name="submit" value="New Row" />
<table></table>
I am satisfied with the ans by Murali Nepalli but you don't need to go for different if else condition for video and audio when its already there once. I suggest keeping the code optimal. You can verify it on : JSFiddle Verification
So you can simply go for :
var videoCount = 1;
var audioCount = 1;
$('input[type="submit"]').on('click', function(e) {
var type = $('input[name="type"]:checked').val();
if( type == 'video' )
{
var count = videoCount; videoCount++;
$('table').prepend('<tr><td>' + type + ' ' + count + '</td></tr>');
}
else
{
var count = audioCount; audioCount++;
if( $('tr:contains("audio")').length > 0){
$('<tr><td>' + type + ' ' + count + '</td></tr>').insertBefore($('tr:contains("audio")')[0]);
}else{
$('table').append('<tr><td>' + type + ' ' + count + '</td></tr>');
}
}
});
And it works like a pro.
Try this code, I verified this at https://jsfiddle.net/9cpk51eq/
var videoCount = 1;
var audioCount = 1;
$('input[type="submit"]').on('click', function(e) {
var type = $('input[name="type"]:checked').val();
if( type == 'video' )
{
var count = videoCount; videoCount++;
}
else
{
var count = audioCount; audioCount++;
}
if(type=="video"){
$('table').prepend('<tr><td>' + type + ' ' + count + '</td></tr>');
}else{
if( $('tr:contains("audio")').length > 0){
$('<tr><td>' + type + ' ' + count + '</td></tr>').insertBefore($('tr:contains("audio")')[0]);
}else{
$('table').append('<tr><td>' + type + ' ' + count + '</td></tr>');
}
}
});
What I need to do is have some sort of textbox form where someone can input a number, and based on this number a variable will multiply certain values by the number of shares:
var stocks = [
['Apple', 141.63, 144.77, 90.34],
['Microsoft', 65.48, 65.78, 48.43]
];
var select = document.getElementById("selectStock");
select.onchange = (e) => {
let index = stocks.indexOf(stocks.find(a => a.indexOf(e.target.value) > -1));
document.getElementById("result").innerText =
("$" + Math.round(stocks[index][1] * 100) / 100 + " per share \n") +
("$" + Math.round(stocks[index][2] * 100) / 100 + " year high \n") +
("$" + Math.round(stocks[index][3] * 100) / 100 + " year low \n")
};
for (var i = 0; i < stocks.length; i++) {
var opt = stocks[i][0];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
var select = document.getElementById("selectStock1");
select.onchange = (e) => {
let index = stocks.indexOf(stocks.find(a => a.indexOf(e.target.value) > -1));
document.getElementById("result1").innerText =
("$" + Math.round(stocks[index][1] * 100) / 100 + " per share \n") +
("$" + Math.round(stocks[index][2] * 100) / 100 + " year high \n") +
("$" + Math.round(stocks[index][3] * 100) / 100 + " year low \n")
};
for (var i = 0; i < stocks.length; i++) {
var opt = stocks[i][0];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div style="display:block;">
<select id="selectStock">
<option>Pick a stock!</option>
<br>
<br>
<div id="result"></div>
</select>
<select id="selectStock1">
<option>Pick a stock!</option>
</select>
<br>
<br>
<div id="result"></div>
<br>
<br>
<div id="result1"></div>
</div>
</body>
So once the user inputs the number and selects a value from each dropdown menu, it provides the results side by side for comparison. I'm having trouble coming up with the code to insert a textbox and link it to my javascript code, so I'd really appreciate help on this. I'm also having trouble formatting the code so that the actual results are side by side, so I'd also appreciate help on this as well. Much appreciated!!
Add an input and also add the corresponding keyup event to monitor for changes. I wrote up an example in jQuery.
var stocks = [
['Apple', 141.63, 144.77, 90.34],
['Microsoft', 65.48, 65.78, 48.43]
];
$(".selectStock").each(function (){
for (var i = 0, len = stocks.length; i < len; i++) {
$("<option>").html(stocks[i][0]).attr("value", i).appendTo(this);
}
});
function r2d (i) {
return Math.round(i * 100) / 100
}
$(".selectStock").change(updateAmount);
$("#numberOfStocks").on('keyup', updateAmount);
function updateAmount() {
$(".selectStock").each(function () {
index = Number($(this).val());
if (isNaN(index)) {
return;
}
amt = Number($("#numberOfStocks").val());
if (isNaN(amt) || amt == 0) {
amt = 1;
}
$(this).nextAll(".result:first").html("")
.append("$" + r2d(amt*stocks[index][1]) + " per share<br />")
.append("$" + r2d(amt*stocks[index][2]) + " high year<br />")
.append("$" + r2d(amt*stocks[index][3]) + " low year<br />");
});
}
.side {
float:left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<input value="1" type="text" id="numberOfStocks" />
<div style="display:block;">
<div class="side">
<select class="selectStock">
<option>Pick a stock!</option>
</select>
<br>
<br>
<div class="result"></div>
</div>
<div class="side">
<select class="selectStock">
<option>Pick a stock!</option>
</select>
<br>
<br>
<div class="result"></div>
</div>
</div>
</body>
So I recieved help from an internet saint to vastly improve my code to create a bootstrap slider per list item within a JS for loop, but now it is behaving erratically.
Sometimes it works perfectly, others it creates new items but not sliders (just a text input field), and others it only creates one item per list.
Any great minds see where I'm going wrong?
var proArray = [];
function addPro() {
var val = document.getElementById("proInput").value.trim();
document.getElementById("proForm").reset();
if (val.length == 0) {
return;
}
if (document.getElementById('proInput' + val) == null) {
proArray.push({id: val, slider: null});
} else {
return;
}
for (var i = 0; i < proArray.length; i++) {
var ele = document.getElementById('proInput' + proArray[i].id);
if (ele == null) {
var newItem = "<li><p>" + proArray[i].id + "</p><input class='bootstrap-slider' type='text' value='' id='proInput" +
proArray[i].id + "' data-slider-id='SIDproInput" + proArray[i].id
+ "' data-slider-min='0' data-slider-max='10' data-slider-value='5'/></li>";
document.getElementById("proList").innerHTML += newItem;
proArray[i].slider = new Slider('#proInput' + proArray[i].id, {
formatter: function(value) {
return 'Current value: ' + value;
}
});
} else {
(function(i) {
setTimeout(function() {
var val = proArray[i].slider.getValue();
proArray[i].slider.destroy();
document.getElementById('SIDproInput' + proArray[i].id).remove();
proArray[i].slider = new Slider('#proInput' + proArray[i].id, {
formatter: function (value) {
return 'Current value: ' + value;
}
});
proArray[i].slider.setValue(val);
}, 100);
})(i);
}
}
}
var conArray = [];
function addCon() {
var valCon = document.getElementById("conInput").value.trim();
document.getElementById("conForm").reset();
if (valCon.length == 0) {
return;
}
if (document.getElementById('conInput' + valCon) == null) {
conArray.push({id: valCon, slider: null});
} else {
return;
}
for (var i = 0; i < conArray.length; i++) {
var ele = document.getElementById('conInput' + conArray[i].id);
if (ele == null) {
var newItem = "<li><p>" + conArray[i].id + "</p><input class='bootstrap-slider' type='text' value='' id='conInput" +
conArray[i].id + "' data-slider-id='SIDconInput" + conArray[i].id
+ "' data-slider-min='0' data-slider-max='10' data-slider-value='5'/></li>";
document.getElementById("conList").innerHTML += newItem;
conArray[i].slider = new Slider('#conInput' + conArray[i].id, {
formatter: function(value) {
return 'Current value: ' + value;
}
});
} else {
(function(i) {
setTimeout(function() {
var valCon = conArray[i].slider.getValue();
conArray[i].slider.destroy();
document.getElementById('SIDconInput' + conArray[i].id).remove();
conArray[i].slider = new Slider('#conInput' + conArray[i].id, {
formatter: function (value) {
return 'Current value: ' + value;
}
});
conArray[i].slider.setValue(valCon);
}, 100);
})(i);
}
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.3/css/bootstrap-slider.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.3/bootstrap-slider.min.js"></script>
<div class="col-sm-6">
<h2>Pros</h2>
<p>The Good Stuff</p>
<form id="proForm" onkeypress="return event.keyCode != 13;">
<input class="form-control text-left pro-con-input" id="proInput" placeholder="Add New Benefit"/>
<div onclick="addPro()" class="btn pro-con-btn">Add</div>
</form>
<h3 class="text-left">Benefits</h3>
<ul class="text-left" id="proList">
</ul>
</div> <!-- pros -->
<div class="col-sm-6">
<h2>Cons</h2>
<p>The Bad Stuff</p>
<form id="conForm" onkeypress="return event.keyCode != 13;">
<input class="form-control text-left pro-con-input" id="conInput" placeholder="Add New Benefit"/>
<div onclick="addCon()" class="btn pro-con-btn">Add</div>
</form>
<h3 class="text-left">Costs</h3>
<ul class="text-left" id="conList">
</ul>
</div> <!-- cons -->
Because you have two lists you can use two arrays:
var proArray = [];
var conArray = [];
The inline functions can be changed in order to pass the list prefix as parameter:
newAdd('pro')
newAdd('con')
And so you can adjust the addPro function to these changes.
From comment:
If I type in "#" or "?" as an item in your snippet above it shows the error. Not for you?
In order to solve such an issue you need to escape those chars when creating the slider:
arr[i].slider = new Slider('#' + listIdPrefix + 'Input' +
arr[i].id.replace(/#/g, '\\#').replace(/\?/g, '\\?').....
The snippet:
var proArray = [];
var conArray = [];
function newAdd(listIdPrefix) {
var val = document.getElementById(listIdPrefix + "Input").value.trim();
document.getElementById(listIdPrefix + "Form").reset();
if (val.length == 0) {
return;
}
var arr;
if (document.getElementById(listIdPrefix + 'Input' + val) == null) {
if (listIdPrefix == 'pro') {
proArray.push({id: val, slider: null});
arr = proArray;
} else {
conArray.push({id: val, slider: null});
arr = conArray;
}
} else {
return;
}
for (var i = 0; i < arr.length; i++) {
var ele = document.getElementById(listIdPrefix + 'Input' + arr[i].id);
if (ele == null) {
var newItem = "<li><p>" + arr[i].id + "</p><input class='bootstrap-slider' type='text' value='' id='" + listIdPrefix + "Input" +
arr[i].id + "' data-slider-id='SID" + listIdPrefix + "Input" + arr[i].id
+ "' data-slider-min='0' data-slider-max='10' data-slider-value='5'/></li>";
document.getElementById(listIdPrefix + "List").innerHTML += newItem;
arr[i].slider = new Slider('#' + listIdPrefix + 'Input' + arr[i].id.replace(/#/g, '\\#').replace(/\?/g, '\\?').replace(/\./g, '\\.'), {
formatter: function (value) {
return 'Current value: ' + value;
}
});
} else {
(function (i, arr) {
setTimeout(function () {
var val = arr[i].slider.getValue();
arr[i].slider.destroy();
document.getElementById('SID' + listIdPrefix + 'Input' + arr[i].id).remove();
arr[i].slider = new Slider('#' + listIdPrefix + 'Input' + arr[i].id.replace(/#/g, '\\#').replace(/\?/g, '\\?').replace(/\./g, '\\.'), {
formatter: function (value) {
return 'Current value: ' + value;
}
});
arr[i].slider.setValue(val);
}, 100);
})(i, arr);
}
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.3/css/bootstrap-slider.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.3/bootstrap-slider.min.js"></script>
<div class="col-sm-6">
<h2>Pros</h2>
<p>The Good Stuff</p>
<form id="proForm" onkeypress="return event.keyCode != 13;">
<input class="form-control text-left pro-con-input" id="proInput" placeholder="Add New Benefit"/>
<div onclick="newAdd('pro')" class="btn pro-con-btn">Add</div>
</form>
<h3 class="text-left">Benefits</h3>
<ul class="text-left" id="proList">
</ul>
</div> <!-- pros -->
<div class="col-sm-6">
<h2>Cons</h2>
<p>The Bad Stuff</p>
<form id="conForm" onkeypress="return event.keyCode != 13;">
<input class="form-control text-left pro-con-input" id="conInput" placeholder="Add New Benefit"/>
<div onclick="newAdd('con')" class="btn pro-con-btn">Add</div>
</form>
<h3 class="text-left">Costs</h3>
<ul class="text-left" id="conList">
</ul>
</div>
So I Have Looked Through The Site Only To Not Find The Answer For My Particular Problem. I Am Pretty New To Writing Code And Am Trying To Figure Out How To Remove A Form Field After Its Been Added with Javascript. Here is the code. I would Greatly Appreciate Feedback/Solutions.
var counter = 1;
var limit = 1000;
function addInput(Favorites){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<br>Favorite " + (counter + 1) + "<input type='text' name='Favorites[]'><input type ='button' value ='Remove'>";
document.getElementById(Favorites).appendChild(newdiv);
counter++;
}
function removeInput(newdiv){
document.getElementById('Favorites').removeChild(newdiv);
counter - 1;
}
}
<form>
<div id="Favorites">
Favorite 1<input type="text" name="Favorites[]">
</div>
<input type="button" value="Add New Favorite" onClick="addInput('Favorites');">
<input type = "button" value = "Save Changes">
</form>
there are various issues in your code so I have modified it a bit. So use following js code
var counter = 1;
var limit = 1000;
function addInput(){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = " <div class='inputElement'>Favorite " + (counter + 1) + "<input type='text' name='Favorites[]'><input type ='button' value ='Remove' onClick='removeInput(this)'></div>";
document.getElementById("Favorites").appendChild(newdiv);
counter++;
}
}
function removeInput(removeLink){
var inputElement = removeLink.parentNode;
inputElement.remove();
counter= counter - 1;
}
In html you can modify your code a bit
<form>
<div id="Favorites">
<div class='inputElement'>
Favorite 1<input type="text" name="Favorites[]">
</div>
</div>
<input type="button" value="Add New Favorite" onClick="addInput();">
<input type = "button" value = "Save Changes">
</form>
Check out above code here
https://jsbin.com/hizimateri/1/edit?html,js,console,output
If you have any issues with it . Let me know.
Maybe this help? Check the link here link
var counter = 1;
var limit = 2;
function addInput(Favorites) {
if (counter == limit) {
removeInput();
alert("You have reached the limit of adding " + counter + " inputs");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<br>Favorite " + (counter + 1) + "<input type='text' name='Favorites[]'><input type ='button' value ='Remove'>";
document.getElementById(Favorites).appendChild(newdiv);
counter++;
}
function removeInput() {
var x = document.querySelector('#Favorites div:last-child');
x.remove();
--counter;
}
}