I've started to learn programming using javascript. My aim is for the program to ask the user a set of yes/no questions. So far I've been using the prompt function for the asking but I wanted something less invasive, like a button. The problem is I can't get the program to wait for an answer to be picked without using a while loop, which freezes the program.
Is there a way to get the while loop to behave? If not what do I do?
Code( simplified, just function and buttons):
var currentAnswer = "unanswered"
function Change2Yes(){
currentAnswer = "y"
}
function Change2No(){
currentAnswer = "n"
}
function Change2Maybe(){
currentAnswer = "m"
}
function question(x){
document.write(x)
while (currentAnswer != "y" && currentAnswer != "n" && currentAnswer != "m"){
//do nothing THIS IS THE PART THAT FREEZES THE PROGRAM
}
if(currentAnswer == "y"){
answerlist.push("y");
latestAnswer="y";
}
else if(currentAnswer == "n"){
answerlist.push("n");
latestAnswer="n";
}
else if(currentAnswer== "m"){
answerlist.push("m");
latestAnswer="n";
}
currentAnswer= "unanswered"
}
<button id="btnYes" onclick="Change2Yes()">
Yes
</button>
<button id="btnNo" onclick="Change2No()">
No
</button>
<button id="btnMaybe" onclick="Change2Maybe()">
Maybe
</button>
Thanks so much :)
You should use events. Add a listener for clicks, for example:
var buttons = Array.prototype.slice.call(document.querySelectorAll('button'));
buttons.forEach(function (button) {
button.addEventListener('click', answer.bind(this, button.value));
});
function answer(currentAnswer) { ... };
The answer function will be called once a button is clicked.
http://jsfiddle.net/fWeq6/
Related
First off I would like to say that I programmed a LONG time ago at school but I had alot of trouble getting into programming cause of ADD, so now I'm just 'trying' stuff at my own tempo with no pressure so I can pace it reall slow, but that does mean I'm a complete beginner, I know only snippets of some languages.
Now onto the problem, what I want to do eventually is change text color through a button click, so if I click a button with the label blue I want the text to turn blue and same with red etc.
So what I have is 2 buttons,
<button type="button" id="redButton" onclick="changeText()" value="red">Red</button>
<button type="button" id="blueButton" onclick="changeText()" value="blue">Blue</button>
Now in my javascript file I have the following:
var rButton = document.getElementById("redButton");
var bButton = document.getElementById("blueButton");
And I can alert both var with their value and it shows the value.
What I can't seem to figure is how to perhaps put rButton & bButton in a new var like
var cButton = [rButton, bButton];
Or something along those lines. Cause I can put cButton into an if statement right now and say this like:
if(cButton = document.getElementById("redButton"))
{
alert("Hello!");
}
else if(cButton = document.getElementById("blueButton"))
{
alert("Hello hello");
}
else
{
alert("Error!");
}
But that will only show Hello! and not Hello Hello even though I do press my blue button.
It's probably something realy stupid but I can't figure it out, and I haven't found much on google that I tried that worked.
Also yes changeText() is the function name which is where all this stuff is in.
If checking the colour is what you want to do, you can do it easily by simply passing the colour to the function as a parameter like this.
<button type="button" id="redButton" onclick="changeText('red')" value="red">Red</button>
<button type="button" id="blueButton" onclick="changeText('blue')" value="blue">Blue</button>
And then in in your javascript change your function to something like this.
function changeText(col){
if(col == "red")
{
alert("Hello!");
}
else if(col == "blue")
{
alert("Hello hello");
}
else
{
alert("Error!");
}
}
Also when you want to compare two values use == (comparison), when you use = (assignment) it will assign the value.
No need to get a reference to two different buttons. Instead, you can pass the color in the function call itself.
var textRef = document.getElementById("text");
function changeText(newColor){
console.log(textRef)
textRef.style.color = newColor;
}
<button type="button" onclick="changeText('red')" value="red">Red</button>
<button type="button" onclick="changeText('blue')" value="blue">Blue</button>
<p id="text">I am the text!!</p>
Try this
let cButton = document.querySelectorAll('.btn');
cButton.forEach(element => {
if (element.id === 'redButton') {
alert('Hello');
} else if (element.id === 'blueButton') {
alert('Hello Hello');
} else {
alert('Error');
}
})
Concerning what you said here
But that will only show Hello! and not Hello Hello even though I do press my blue button.
You can add an event listener like this :
cButton.forEach(element => {
element.addEventListener('click', (e) => {
if (e.target.id === 'redButton') {
alert('Hello');
} else if (e.target.id === 'blueButton') {
alert('Hello Hello');
} else {
alert('Error');
}
})
})
Note: That you have to add class="btn" in each button
I am a noob to javascript and and programming really and I just want to know what I am doing wrong. Im sure this is a really simple question but I have no idea why this isn't working. According to research online I'm doing everything correctly.
var varname = 0;
$(document).keydown(function(e) {
if(e.which == 74) {
varname++;
console.log(varname);
}
}
Everytime I press "j" I want to increase my variable, but console log shows a consistent 1 and doesn't go any higher. What can I do Thanks for the help. The key press event works fine, the number just wont increase upon the keypress. Thanks again
you can just declare like this:
var varname = 0;
function keyPress(e){
if(e.which == 74) {
varname++;
console.log(varname);
}
}
In this case, your variable will keep it's previous value, and it will increment.
It's a little hard to tell, but I presume you're trying for something like this:
var jCounter = 0
document.getElementById('keycheck')
.addEventListener('keydown', function (evt) {
if (evt.which === 74) {
console.log("Yup, that's a 'j' alright.")
jCounter++
document.getElementById('jcounter').innerHTML = jCounter
}
})
<input type="text" id="keycheck" placeholder="I really like j's...">
<span id="jcounter">0</span>
Here is my code, not working please help I want to call two js functions using one submit button.I have tried the below code.But it gives error.
function scrollWin() {
// First time click
if (e.name != 'Click') {
e.name = "Click";
function scrollWin() {
window.scrollBy(0, 85);
}
}
// When click it again..
else if (e.name == 'Click') {
e.name = "Unclick";
function myFunction() {
document.getElementById("demo").innerHTML = "<h2> Second Click </h2>";
}
}
}
<input type="button" onclick="scrollWin(); this.style.visibility= 'hidden';
myFunction()" value="Click Me" />
<p id="demo"></p>
You need to define one function which handles this action. It is probably best to store a variable where you can save the state of the clicking. Here is an example:
var clickCount = 0;
function scrollWin(button) {
// first click
if (clickCount === 0) {
window.scrollBy(0, 85);
}
// second or more click
else {
document.getElementById("demo").innerHTML = "<h2> Second Click </h2>";
button.style.display = 'none';
}
clickCount++;
}
<input type="button" onclick="scrollWin(this)" value="Click Me" />
<p id="demo"></p>
You need to get the fundamentals right. A function call will have its own scope and once the scope of a function ends, the variables are destroyed. I think you want to capture a second click for the element.
Don't try declaring a global variable for the same but try to set the elements property on first click which you can access on the second click. read that property on click and then manipulate.
I would suggest you to call the click event as
onclick="click123(this);"
and use this to set the property using setAttribute
I think this accomplishes what you described. You need to pass in the event of the button click and read the button text, but e.name probably wont work you'll need to use innerHTML or textContent. Then you can either perform the operations or call the functions you wish to execute depending on the button text which changes after the 2nd click.
function scrollWin(e) {
//First time click
if(e.textContent != 'Click'){
e.textContent = "Click";
window.scrollBy(0, 85);
}
else if(e.textContent == 'Click'){
e.textContent = "Unclick";
document.getElementById("demo").innerHTML = "<h2> Second Click </h2>";
}//end else
}//end function
<button onclick="scrollWin(this)">Click</button>
<div id="demo"></div>
What I understand you want to perform two operation on same button but in two different condition, if you want to perform keep state and perform action according to that then. Like:
function scrollWin(e) {
var btn = e.target;
var state = btn.dataset.myattr;
if( state == 'state1'){
btn.dataset.myattr = 'state2';
e.name = "Click";
window.scrollBy(0, 85);
}else if (state == 'state2'){
btn.dataset.myattr = 'state1';
e.name = "Unclick";
document.getElementById("demo").innerHTML = "<h2> Second Click </h2>";
}
}
If you want to change the name attribute to something else you can do that and you don't have to change the JS code for that.
very new to JS, I'm struggling with my current project: Trying to insert some HTML via a function if a variable = "yes". The variable value will change on a button click.
I've been using firebug to look at the variable value - it doesn't seem to be changing on the button click.
Was hoping someone would be kind enough to help.
I THINK my main issue is with setting the variable value - but I could of course be wrong so I've attached a codepen version for good luck :)
HTML:
<button id="butterbutton" onclick="imageAdd('yes'); ">
<img id="worldimg" src="http://butterybeast.hol.es/world.png"></img>
</button>
JS:
var beast
function imageAdd(choice) {
beast = choice;
}
if (beast = "yes" ) {
function imagemap () {
document.getElementById('test1').innerHTML += '<img> an image map goes here';
}
}
http://codepen.io/Puffincat/pen/Nrdgrz?editors=1010
You have just a couple of problems with your code. The first is this:
if (beast = "yes") {
In this case, you're assigning "yes" to beast, not comparing it. Change it to
if (beast == "yes") {
Next, your code at the bottom (if (beast == "yes") { ...) is only run at the start. Instead, you want that code to run whenever the variable is updated. Move it into your imageAdd function or somewhere else where you update the UI then call it from imageAdd. While you're at it, remove that imagemap function declaration. It doesn't make sense to declare a function inside of an if statement.
var beast;
function imageAdd(choice) {
beast = choice;
updateUI();
}
function updateUI() {
if (beast == "yes") {
document.getElementById('test1').innerHTML += '<img> an image map goes here';
}
}
You have a function imagemap wrapped in a conditional but you aren't calling that function.
Also for your conditional, beast will always be null since the conditional is called straight away.
Consider the following adjustment
var beast;
function imagemap () {
document.getElementById('test1').innerHTML += '<img> an image map goes here';
}
function imageAdd(choice) {
beast = choice;
if (beast === "yes" ) {
imagemap();
}
}
I have a form with many fields and 2 submit buttons. I want to run a different check depending on which submit button i click on. I tried writing the code below but it is wrong (i dont know JS) and nothing happens (bad syntax?). How do i figure out which of the two buttons was clicked?
document.getElementById('sub1').onclick = checkForm;
document.getElementById('sub2').onclick = checkForm;
function checkForm(e)
{
var e = e || window.event;
var o = e.srcElement || e.originalTarget;
if(o.id=="sub1")
return checkNotNull();
else
return checkSamePass();
}
I put your code into a test page, and it works fine on both FF and IE. The problem likely lies with the two functions you are calling, checkNotNull() and checkSamePass(). I would check that they are working and are properly returning.
You can verify that the o.id is correct by the time it gets to the if/else statement by putting in an alert(o.id).
Why make it so complicated?
function checkForm(button) {
formOk = false;
if (button = 'first') {
//check form
if (formOk) myform.submit();
}
if (button = 'second') {
//check form using other logic
if (formOk) myform.submit();
}
}
<input type="button" onClick="checkForm('first');" value = "button 1">
<input type="button" onClick="checkForm('second');" value = "button 2">