Can't find a way to refactor alert (exercise) - javascript

I'm a JS noob trying to make this "hello mr./miss yourname!" clean.
I don't see a way to refactor the alert inside the if/else because then i lose the value of var b.
the JS:
<script>
"use strict";
window.onload = function () {
let form1 = document.getElementById('myForm');
form1.addEventListener('submit', helloYou);
function helloYou() {
let x = document.getElementById("1").value;
let a = document.getElementById('3').value;
if ( a === "M") {
let b = "Mr.";
alert('Hello ' + b + " " + x + "!");
}
else {
let b = "Miss";
alert('Hello ' + b + " " + x + "!");
}
}
}
</script>
the HTML:
<body>
<form id="myForm">
Write your name:
<input type="text" name="yourname" id="1" placeholder="name">
<select name="gender" id="3">
<option value="M">Male</option>
<option value="F">Female</option>
<input type="submit" name="submission" id="2" value="TRY ME">
</form>
</body>
Thanks for any suggestions.

You can use ternary operator
alert('Hello ' + ( a === "M" ? "Mr." : "Miss" ) + " " + x + "!");
i.e.
function helloYou() {
let x = document.getElementById("1").value;
let a = document.getElementById('3').value;
alert('Hello ' + ( a === "M" ? "Mr." : "Miss" ) + " " + x + "!");
}

Assuming you are only needing the value of your gender select for the alert, you could change the value to Mr. and Miss and just alert/print those.
<script>
"use strict";
window.onload = function () {
let form1 = document.getElementById('myForm');
form1.addEventListener('submit', helloYou);
function helloYou() {
let x = document.getElementById("1").value;
let a = document.getElementById('3').value;
alert('Hello ' + a + " " + x + "!");
}
}
</script>
HTML
<body>
<form id="myForm">
Write your name:
<input type="text" name="yourname" id="1" placeholder="name">
<select name="gender" id="3">
<option value="Mr.">Male</option>
<option value="Miss">Female</option>
<input type="submit" name="submission" id="2" value="TRY ME">
</form>
</body>

function helloYou() {
const val = id => document.getElementById(id).value;
alert(`Hello ${val(3) === "M" ? "Mr." : "Miss"} ${val(1)} !`);
}
We can make use of two things 1 tenary to shorten your if logic.
condition ? result : otherResult
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
and template literals which let you add javascript to a string `string ${javascript}`` using back tics
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Something like this?
<script>
"use strict";
window.onload = function () {
let form1 = document.getElementById('myForm');
form1.addEventListener('submit', helloYou);
function helloYou() {
let x = document.getElementById("1").value;
let a = document.getElementById('3').value;
let b = "Miss"
if ( a === "M") {
b = "Mr.";
}
alert('Hello ' + b + " " + x + "!");
}
}
</script>

Just adding this as an option, quite clean :)
const helloYou = () => {
let name = document.getElementById('1').value
let gender = document.getElementById('3').value
const prefix = gender === 'M' ? 'Mr.' : 'Miss'
alert(`Hello ${prefix} ${name}!`)
}

Related

Computer Guess A Number JavaScript

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 ...

How can I find if a specific checkbox is checked?

I've looked at lots of posts but I couldn't find anything that works in my case. I need to display of a preview of the user's signature in their profile, with the options to not show their phone number and/or email address so I have a checkbox for each.
Here's my HTML for the checkboxes:
<div class="checkbox">
<label>
<input type="checkbox" name="showInSignature[]" id="showPhoneId" value="showPhone" class="checkbox style-0" checked="checked">
<span>Teléfono</span>
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="showInSignature[]" id="showEmailId" value="showEmail" class="checkbox style-0" checked="checked">
<span>Dirección de e-mail</span>
</label>
</div>
and here is the jQuery:
var fname = $('#personalOptionsForm').find('[name="fname"]').val(),
lname = $('#personalOptionsForm').find('[name="lname"]').val(),
cellphone = $('#personalOptionsForm').find('[name="cellphone"]').val(),
email = $('#personalOptionsForm').find('[name="email"]').val(),
if ($('#showPhoneId').is(':checked') = true) {
showPhone = 1;
} else {
showPhone = 0;
},
// showPhone = (($('input[name="showInSignature[]"]')['showPhone'].checked = true) ? 1 : 0),
// showEmail = (($('input[name="showInSignature[]"]')['showEmail'].checked = true) ? 1 : 0),
str = "<strong>" + fname + " " + lname + "</strong><br /><br />" + ((showPhone = 1) ? 'Teléfono: ' + cellphone + '<br />' : '') + "E-mail: " + email + "",
html = $.parseHTML( str );
$('#signaturePreview').append(html);
If I comment out the IF (as I've commented out other tries I've made) and the ternary operator in the str var it works but NOTHING is displayed when trying to use a dynamic value (like the phone checkbox). There's only two methods there but I've tried many more. None of them work. Nothing is appended.
How can I do it? Thanks in advance!
showPhone = $('#showPhoneId').is(':checked');
surely that's all you need. It returns a boolean
$(document).ready(function() {
alert('Is Checked: ' + $('#showPhoneId')[0].checked);
console.log(typeof $('#showPhoneId')[0].checked);
console.log($('#showPhoneId')[0].checked === true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkbox">
<label>
<input type="checkbox" name="showInSignature[]" id="showPhoneId" value="showPhone" class="checkbox style-0" checked="checked">
<span>Teléfono</span>
</label>
</div>
In your code you are using assignment operator "=" which means
a = b (value of b is assigned to a),
in your case you are trying to assign true to $('#showPhoneId').is(':checked')
kindly"==" instead
var fname = $('#personalOptionsForm').find('[name="fname"]').val() ,
lname = $('#personalOptionsForm').find('[name="lname"]').val() ,
cellphone = $('#personalOptionsForm').find('[name="cellphone"]').val(),
email = $('#personalOptionsForm').find('[name="email"]').val(),
//dummy values
fname = 'abc', lname="dksjdn",
cellphone = "98989898", email = "abc#gmail.com";
if($('#showPhoneId').is(':checked') == true) {
showPhone = 1;
} else {
showPhone = 0;
};
// showPhone = (($('input[name="showInSignature[]"]').is(':checked') == true) ? 1 : 0),
// showEmail = (($('input[name="showInSignature[]"]').is(':checked') == true) ? 1 : 0),
str = "<strong>" + fname + " " + lname + "</strong><br /><br />" + ((showPhone == 1) ? 'Teléfono: ' + cellphone + '<br />' : '') + "E-mail: " + email + "",
html = $.parseHTML( str );
$('#signaturePreview').append(html);
please refer https://jsbin.com/rolodozode/1/edit?html,js,output

Button click to wait for button click

I have two buttons: Btn1 <input type="button" class="buttons" value="Test">
and Btn2 <input type="button" class="buttons" value="Test2">. I want to be able to click on Btn1 and Btn1 waits for the second button to be pressed and if the second button (Btn2) is pressed the output is Test Test2 is this possible?
I know how to do the button clicks of course but I can't find a solution for the first button to wait for the second one
Try this:-
If you are using Input Buttons like this:-
<input type="button" id="button1" class="buttons" value="Test" />
<input type="button" id="button2" class="buttons" value="Test2" />
<textarea name="test" id="test" rows="8" cols="80" readonly></textarea>
Then use this script:-
<script src="https://code.jquery.com/jquery-1.12.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
var flag1 = false;
var result;
$(document).ready(function () {
$("input[ID$='button1']").click(function () {
flag1 = true;
alert("you clicked button 'Test', Click another button for result");
});
$("input[ID$='button2']").click(function () {
if (flag1 == true) {
//flag1 = false;
if (result)
result = result + " " + $("input[ID$='button1']").val() + " " + $("input[ID$='button2']").val();
else
result = $("input[ID$='button1']").val() + " " + $("input[ID$='button2']").val();
// alert(result);
document.getElementById("test").innerHTML = result;
}
else {
//alert("Please click button 'Test' first");
if (result)
result = result + " " + $("input[ID$='button2']").val();
else
result = $("input[ID$='button2']").val();
document.getElementById("test").innerHTML = result;
}
});
window.onload = function () {
if (flag1 == true) {
//flag1 = false;
if (result)
result = result + " " + $("input[ID$='button1']").val() + " " + $("input[ID$='button2']").val();
else
result = $("input[ID$='button1']").val() + " " + $("input[ID$='button2']").val();
//alert(result);
document.getElementById("test").innerHTML = result;
}
};
});
</script>
If you are using buttons like this:-
<button id="btntest1" class="buttons">Test</button>
<button id="btntest2" class="buttons">Test2</button>
<textarea name="test" id="test" rows="8" cols="80" readonly></textarea>
Then use this script:-
<script src="https://code.jquery.com/jquery-1.12.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("button[ID$='btntest1']").click(function () {
flag1 = true;
alert("you clicked button 'Test', Click another button for result");
});
$("button[ID$='btntest2']").click(function () {
if (flag1 == true) {
//flag1 = false;
if (result)
result = result + " " + $("button[ID$='btntest1']").html() + " " + $("button[ID$='btntest2']").html();
else
result = $("button[ID$='btntest1']").html() + " " + $("button[ID$='btntest2']").html();
//alert(result);
document.getElementById("test").innerHTML = result;
}
else {
//alert("Please click button 'Test' first");
if (result)
result = result + " " + $("button[ID$='btntest2']").html();
else
result = $("button[ID$='btntest2']").html();
document.getElementById("test").innerHTML = result;
}
});
});
window.onload = function () {
if (flag1 == true) {
//flag1 = false;
if (result)
result = result + " " + $("button[ID$='btntest1']").html() + " " + $("button[ID$='btntest2']").html();
else
result = $("button[ID$='btntest1']").html() + " " + $("button[ID$='btntest2']").html();
//alert(result);
document.getElementById("test").innerHTML = result;
}
};
</script>
Hope this will help you.
depends on your needs.
1- Show button 1 enable
2- Show button 2 disable
3- onclick button 1 :
3.1 : set flags to btn1_clicked = true; and othe var you need
3.2 : Enable button 2
4 onclick button 2 do your output
It's just a global thinking, you can adapt .
So, with the idea of my comment you can do this :
btn1 = document.getElementById('btn-1');
btn2 = document.getElementById('btn-2');
btn1.addEventListener('click', function(){
btn2.removeAttribute('disabled');
btn1.disabled = 'disabled';
});
btn2.addEventListener('click', function(){
btn1.removeAttribute('disabled');
btn2.disabled = 'disabled';
alert(btn2.value);
});
<input id="btn-1" type="button" class="buttons" value="Test">
<input id="btn-2" type="button" class="buttons" value="Test 2" disabled>
Based on my comment...
OnButton1Click -> Set a flag to true
OnButton2Click -> If Variable is true -> "Test Test2" if variable is false -> "Test2"
I created a quick example all vanilla JS.
JSBin Example

How do I capture values (JavaScript Only) of each text box and display them?

I am building a form using JavaScript and HTML only (business need - no server access). I have a list of textboxes that I need the values from. The user has the option of either filling out 1 textbox, or as many as they need up to 35. I COULD create a function for each individual box
var a = $('#a').val();
var b = $('#b').val();
var c = $('#c').val();
if (a != '' && b != '' && c != '') {
var abc = "this is a: " + a + "this is b: " + b + "and this is c:" + c;
}
and I could make a function for each scenario of each value:
if(a != '' && b != '' && c == '') {
var ab = "this is a: " + a + " and b: " + b + "but not c";
}
if(a != '' && b == '' && c != '') {
var ac = "this is a: " + a + " and c: " + c + "but not b";
}
if(a != '' && b == '' && c == '') {
var a-only = "this is a: " + a + " but not b or c";
}
if(a == '' && b != '' && c != '') {
var bc = "this is b: " + b + " and c: " + c + " but not a";
}
That's not even every scenario for just 3 variables, but I could potentially have up to 35 different variables that I need to make a function for each scenario which is a huge chunk of time and space and I think after about 10 of them, it will get too messy and hard to maintain later if I need let alone all 35.
I feel like there must be a far more efficient way of capturing the values and displaying them if they are not empty other than going through each possible scenario.
My textboxes are dynamically created by clicking an "Add More" button
JavaScript:
var max_fields = 35;
var x = 0;
$('#add').click(function(e) {
e.preventDefault();
if(x < max_fields){
x++;
var inps = $('#wrapper >div:last').data('count')+1 || 1;
$('#wrapper').append('<div class="date-time-list" data-count="'+inps+'"><input type="text" name="date_count' + inps + '" id="date_count'+inps+'" class="inp"/><input type="text" name="time_count' + inps + '" id="time_count'+inps+'" class="inp"/><a class=remove>Remove</a><br><br></div>');
}
});
$('#wrapper').on('click' , 'a.remove' ,function(){
var inps = $('#wrapper > div:last').data('count')-1 || 1;
x--;
$(this).closest('div').remove();
});
HTML:
<tr class="list" style="line-height:1em;">
<td>
Please fill in the dates and times
</td>
<td>
<strong>Dates</strong> <strong>Times</strong>
</td>
</tr>
<tr class="list" style="line-height:1em;">
<td>
</td>
<td>
<span id="wrapper">
</span>
</td>
</tr>
<tr class="list">
<td>
</td>
<td>
<button id="add">Add More</button>
</td>
</tr>
Please have a look at this little snippet: https://jsfiddle.net/0h52y0Ly/1/
$( document ).ready(function() {
$('button').click(function(){
var content = '';
var countOfTextareasFilled = 0;
$('textarea').each(function(){
if ($(this).val().length){
content += $(this).val() + '\n\n';
countOfTextareasFilled++;
}
});
alert(countOfTextareasFilled + ' text boxes have been filled. Contents are:\n\n' +content);
});
});
It shows a very generic approach to your task. You should be able to adapt it to your needs very easily.
EDIT:
I am fairly certain, that adapting a perfectly functioning generalized solution to your special use case, is something you should do yourself. But here it is:
https://jsfiddle.net/cb7ujmsw/
$('#evaluate').click(function(){
var content = '';
var data = [];
var dateField, timeField;
$('.date-time-list').each(function(){
dateField = $('#date_count' + $(this).data('count'));
timeField = $('#time_count' + $(this).data('count'));
if (dateField.val().length && timeField.val().length){
data.push({
date: dateField.val(),
time: timeField.val()
});
}
});
alert(data.length + ' complete datetimes. Data:\n\n' +JSON.stringify(data));
});
I added a button with the ID "evaluate". The rest is completely your code.
Assuming you have a way to select all relevant inputs (in this example all elements have the check-me class)
$(function(){
$('.do-the-check').on('click', function(e){
e.preventDefault();
var inputs = $('.check-me', this.form),
empty = inputs.filter(function(){return this.value === ''}),
nonempty = inputs.not(empty),
message = 'This is ';
if (nonempty.length){
message += nonempty.map(function(){return this.name + ':' + this.value}).get().join(' and ');
}
if (empty.length){
if (nonempty.length){
message += ' but ';
}
message += 'not ' + empty.map(function(){return this.name;}).get().join(' or ');
}
alert(message);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
a:<input name="a" class="check-me"><br/>
b:<input name="b" class="check-me"><br/>
c:<input name="c" class="check-me"><br/>
d:<input name="d" class="check-me"><br/>
e:<input name="e" class="check-me"><br/>
f:<input name="f" class="check-me"><br/>
g:<input name="g" class="check-me"><br/>
h:<input name="h" class="check-me"><br/>
i:<input name="i" class="check-me"><br/>
j:<input name="j" class="check-me"><br/>
<button class="do-the-check">check them</button>
</form>

JQuery autocomplete works for one section but not the other

I'm trying to get a JQuery function to pick up specific changes to a form and then plug the information into equations so that each section of the form has answers created for it automatically. I got the first part of it to work (Quantity for Posts) but can't get the second part to work (Quantity for Rails). If anyone can point out or explain where I went wrong and how I could fix it it would be greatly appreciated! Thanks!
Here is a JSFiddle - http://jsfiddle.net/gv0029/ncn42/1/
HTML:
<fieldset id="fence">
<div name="inputFence" class="inputFence">
<legend><strong>Fence Description</strong>
</legend>
<label>Footage:
<input name="footage_1" class="footage" />
</label>
<select name="fenceHeight_1" class="fenceHeight">
<option value="select">Select Fence Height</option>
<option value="6" id="fH6">6 Ft.</option>
<option value="8" id="fH8">8 Ft.</option>
</select>
<legend><strong>Post Type</strong>
</legend>
<label>Post Quantity:
<input name="postQuantity_1" class="postQuantity" />
</label>
<legend><strong>Rail Type</strong>
</legend>
<select name="6foc_1" class="6foc">
<option value="select">6 Ft. on Center?</option>
<option value="no">No</option>
<option value="yes">Yes</option>
</select>
<label>Quantity:
<input class="railQuantity" name="railQuantity_1" />
</label>
</fieldset>
<div>
<input type="button" id="btnAddFence" value="Add Another Fence" />
<input type="button" id="btnDelFence" value="Remove Fence" />
</div>
</form>
JS:
//Quantity for Posts
$(document.body).on('keypress keydown keyup change', '[class^="footage"] ', function () {
var footage = parseFloat($(this).val(), 10);
var total = '';
var parts = $(this).attr('name').split("_");
var fenceNumber = parts[1];
if (!isNaN(footage)) {
total = Math.ceil(footage / 7);
$(":input[name='postQuantity_" + fenceNumber + "'" + ']').val(total.toString());
} else {
$(":input[name='postQuantity_" + fenceNumber + "'" + ']').val("");
}
});
//Quantity for Rails
$(document.body).on('keypress keydown keyup change', '[class^="footage"] [class^="fenceHeight"] [class^="6foc"]', function () {
var parts = $(this).attr('name').split("_");
var fenceNumber = parts[1];
var footage = parseFloat($(":input[name='footage_" + fenceNumber + "'" + ']').val(), 10);
var fenceHeight = $(":input[name='fenceHeight_" + fenceNumber + "'" + ']').val();
var railQuantity = $(":input[name='railQuantity_" + fenceNumber + "'" + ']').val();
var total = '';
var sfoc = $(":input[name='6foc_" + fenceNumber + "'" + ']').val();
if (fenceHeight = !NaN) {
if (sfoc == "no") {
if (fenceHeight == '8') {
total = (Math.ceil(footage / 8) * 4);
}
if (fenceHeight == '6') {
total = (Math.ceil(footage / 8) * 3);
}
railQuantity.val(total);
}
if (sfoc == "yes") {
if (fenceHeight == '8') {
total = (Math.ceil(footage / 12) * 4);
railQuantity.val(total);
}
if (fenceHeight == '6') {
alert("Error: 6ft on Center cannot use 6ft posts");
railQuantity.val("ERROR");
}
}
} else {
railQuantity.val("");
}
});
//Dynamic Fence Input Fields
$('#btnAddFence').click(function () {
// create the new element via clone()
var newElem = $('.inputFence:last').clone();
// insert the new element after the last "duplicable" input field
$('.inputFence:last').after(newElem);
// enable the "remove" button
$('#btnDelFence').removeAttr('disabled');
//get the input name and split into array (assuming your clone is always last)
var parts = $('.fenceHeight:last').attr('name').split("_");
//change the second element of the array to be one higher
parts[1]++;
//join back into a string and apply to the new element
$('.fenceHeight:last').attr('name', parts.join("_"));
//do the same for other two inputs
parts = $('.postQuantity:last').attr('name').split("_");
parts[1]++;
$('.postQuantity:last').attr('name', parts.join("_"));
parts = $('.footage:last').attr('name').split("_");
parts[1]++;
$('.footage:last').attr('name', parts.join("_"));
parts = $('.6foc:last').attr('name').split("_");
parts[1]++;
$('.6foc:last').attr('name', parts.join("_"));
});
$('#btnDelFence').click(function () {
//remove the last inputFence
$('.inputFence:last').remove();
// if only one element remains, disable the "remove" button
if ($('.inputFence').length == 1) $('#btnDelFence').attr('disabled', 'disabled');
});
$('#btnDelFence').attr('disabled', 'disabled');
You had a few problems.
First was this line:
$(document.body).on('keypress keydown keyup change', '[class^="footage"] [class^="fenceHeight"] [class^="6foc"]',
You have to separate the different inputs with a comma as shown here:
$(document.body).on('keypress keydown keyup change', '[class^="footage"],[class^="fenceHeight"],[class^="6foc"]',
Second was this line:
var fenceHeight = $(":input[name='fenceHeight_" + fenceNumber + "'" + ']').val();
You're getting the value of the select, when really you want the value of the selected option:
var fenceHeight = $(":input[name='fenceHeight_" + fenceNumber + "'" + ']').find('option:selected').val();
Third was this line:
var railQuantity = $(":input[name='railQuantity_" + fenceNumber + "'" + ']').val();
You're getting the value of this line, when down in the code you're actually trying to set the value of the value. What you want is just the element. I've left the quantity in there in case you want that later, but repurposed railQuantity:
var railQuantity = $(":input[name='railQuantity_" + fenceNumber + "'" + ']');
var railQuantityval = $(":input[name='railQuantity_" + fenceNumber + "'" + ']').val();
Fourth is your if statement:
if (fenceHeight = !NaN) {
You can't really use it like that. Use this instead:
if (!isNaN(Number(fenceHeight))) {
Down in the if statement, you also could benefit from if/else statements instead of just if statements. I've changed those to reflect this.
You were also missing the railsQuantity element in your add function, which I added for you:
parts = $('.railQuantity:last').attr('name').split("_");
parts[1]++;
$('.railQuantity:last').attr('name', parts.join("_"));
Updated fiddle here.

Categories