Comparing attribute value with a random number (JavaScript/jQuery) - javascript

I have a problem with comparing an attribute value and a random number (created in a separated function).
In my html I have several divs within a surrounding div.
Each div within the surrounding element has an attribute, called 'value', the first one contains the value: 1, the second one: 2, ...
Like this:
<div id="Stage_placeholder_rectangles">
<div id="Stage_placeholder_rectangles_red" value=0 width=25 height=25/>
<div id="Stage_placeholder_rectangles_pink" value=1 width=25 height=25/>
<div id="Stage_placeholder_rectangles_orange" value=2 width=25 height=25/>
...
</div>
Now I want to compare the attribute 'value' with a random number, which was made to show random random colors:
The function is lik this:
function randomNumber(){
random = Math.floor(Math.random() * 9);
return random;
}
function randomColors(){
while(pastRandom == newRandom){
newRandom = randomNumber();
}
pastRandom = newRandom;
switch(newRandom){
case 0:
stageRef.getSymbol("placeholder_colors").stop("red");
break;
case 1:
stageRef.getSymbol("placeholder_colors").stop("black");
break;
case 2:
stageRef.getSymbol("placeholder_colors").stop("yellow");
break;
case 3:
stageRef.getSymbol("placeholder_colors").stop("green");
break;
case 4:
stageRef.getSymbol("placeholder_colors").stop("orange");
break;
case 5:
stageRef.getSymbol("placeholder_colors").stop("pink");
break;
case 6:
stageRef.getSymbol("placeholder_colors").stop("blue");
break;
case 7:
stageRef.getSymbol("placeholder_colors").stop("gray");
break;
case 8:
stageRef.getSymbol("placeholder_colors").stop("purple");
break;
}
checkColor(newRandom);
}
In my function checkColor, I want to compare the random number with the value that is stored in the attribute value of 'placeholder_rectagles_orange', 'placeholder_rectagles_red', ...
This is my function:
function checkColor(rnd){
if(gameStarted){
$("#Stage_placeholder_rectangles").click(function(e){
if($("#"+e.target.id).attr("value") == rnd){
console.log("right");
}
else if($("#"+e.target.id).attr("value") != rnd){
console.log("false");
gameOver = true;
}
});
}
}
My problem is, that when I the right element (the one with the same value in his attribute 'value' as the random number, I get in my console:
"right" and multiple times "false", even when my attributes value and random number are the same.

I think part of your problem is the usage of rnd, which is not defined earlier, but we don't have all of your code.
Here it is working:
<div>Please click the colour: <span id="name"></span></div>
<p/>
<div id="Stage_placeholder_rectangles">
<div id="Stage_placeholder_rectangles_red" class="square red" value=0 width="25" height="25"></div>
<div id="Stage_placeholder_rectangles_pink" class="square pink" value=1 width="25" height="25"></div>
<div id="Stage_placeholder_rectangles_orange" class="square orange" value=2 width=25 height="25"></div>
</div>
<p/>
<div id="result"></div>
And the JS:
var colors = ["red","pink","orange"],
gameStarted = true, newRandom, pastRandom;
function randomNumber(){
random = Math.floor(Math.random() * 3);
return random;
}
var giveOption = function() {
while(pastRandom == newRandom){
newRandom = randomNumber();
}
pastRandom = newRandom;
$("#name").html(colors[newRandom]);
};
$("#Stage_placeholder_rectangles").click(function(e){
var val = $(e.target).attr("value"),
resultDiv = $("#result");
if(val == newRandom){
resultDiv.html("right!");
giveOption();
} else {
resultDiv.html("Wrong! Sorry. Game over");
gameOver = true;
}
});
giveOption();
There also is a lot of stuff that could be simplified using arrays and jquery, but I left it for now.
Fully functional jsfiddle at http://jsfiddle.net/obqmwLet/1/

Related

How can I call a function from different buttons?

I am trying to put different buttons with same function in switch statement. Every button needs to call same function but with different switch parameter.
<button type="submit" onclick="myFunction()" class="dugme1" id="btnSQRT">
SQRT
</button>
<button type="submit" onclick="myFunction()" class="dugme1" id="btnSIN" style="margin-left:
100px;">
SIN
</button>
<button type="submit" onclick="myFunction()" class="dugme1" id="btnCOS" style="margin-left:
100px;">
COS
</button>
<button type="submit" onclick="myFunction()" class="dugme1" id="btnROUND" style="margin-left:
100px;">
ROUND
</button>
And here is JS code,
<script>
function myFunction(){
var x = prompt("Input number beteen 1 i 999");
if(x > 0 && x < 1000){
switch(x){
case 0:
document.getElementById("btnSQRT");
document.write("nesta");
break;
case 1:
document.getElementById("btnSIN");
document.write("nesta");
break;
case 2:
document.getElementById("btnCOS");
document.write("nesta");
break;
case 3:
document.getElementById("btnROUND");
document.write("nesta");
break;
}
}
else{
alert("Thats not a wanted number");
}
}
</script>
Change all of your onclick="myFunction()" to onclick="myFunction(this)" - that will allow you to test for the switch in myFunction - in which case you want to switch on the button ID rather than the prompt value.
function myFunction(el){ // el will be the button that called the function
var x = prompt("Input number between 1 i 999");
if(x > 0 && x < 1000){
switch(el.id){ // switching on the ID of the button which tells us which math to use
case 'btnSQRT':
alert('The square root is ' + Math.sqrt(x));
break;
.....
I am not sure what 'nesta' and document.write was for, so I removed them here.
You are trying to switch between INT numbers, and "prompt" return a STRING. So, It will never get in any switch statement. To solve this, I just added a "parseInt()" in your prompt variable.
I changed "document.write('nesta')" by inner.HTML('nesta'), so, it changes the text in the button. But, to change the text inside the button, you got to set a variable to each button.
HTML:
<button type="submit" onclick="myFunction()" class="dugme1" id="btnSQRT">SQRT</button>
<button type="submit" onclick="myFunction()" class="dugme1" id="btnSIN" style="margin-left: 100px;">SIN</button>
<button type="submit" onclick="myFunction()" class="dugme1" id="btnCOS" style="margin-left: 100px;">COS</button>
<button type="submit" onclick="myFunction()" class="dugme1" id="btnROUND" style="margin-left: 100px;">ROUND</button>
JS:
function myFunction(){
var x = prompt("Input number beteen 1 i 999");
var x = parseInt(x);
if(x > 0 && x < 1000) {
switch(x){
case 1:
var nesta = document.getElementById("btnSQRT");
nesta.innerHTML = 'nesta';
break;
case 2:
var nesta =document.getElementById("btnSIN");
nesta.innerHTML = 'nesta';
break;
case 3:
var nesta = document.getElementById("btnCOS");
nesta.innerHTML = 'nesta';
break;
case 4:
var nesta =document.getElementById("btnROUND");
nesta.innerHTML = 'nesta';
break;
}
} else {
alert("Thats not a wanted number");
}
}
Here you have:
One event listener for all buttons.
getting the "value" from the button using the attribute id. An alternative could be to use a data-attribute (like I did with the 2ed button).
A switch statement for handling what to do next.
It is not completely clear for me if the switch statement is the right approach here. Please comment if you have questions.
document.addEventListener('DOMContentLoaded', e => {
let buttons = document.getElementById('buttons');
let output = document.getElementById('output');
buttons.addEventListener('click', e => {
if (e.target.nodeName == 'BUTTON') {
switch (e.target.id) {
case 'btnSQRT':
output.innerHTML = 'You clicked SQRT';
break;
case 'btnSIN':
output.innerHTML = 'You clicked SIN';
break;
case 'btnCOS':
output.innerHTML = 'You clicked COS';
break;
case 'btnROUND':
output.innerHTML = 'You clicked ROUND';
break;
}
}
});
});
div#buttons {
display: flex;
justify-content: space-between;
}
<div id="buttons">
<button id="btnSQRT">SQRT</button>
<button data-func="SIN" id="btnSIN">SIN</button>
<button id="btnCOS">COS</button>
<button id="btnROUND">ROUND</button>
</div>
<div id="output"></div>

How to insert different text message in HTML with an event listner attached to radio buttons

I'm a new student to javascript, and wrote below code that was meant to display different image and text message based on radio button selection:
*<!-- charSelect.html -->*
<!-- skipped -->
<body>
<img id = "charImg" src = "1.jpg" width = "500" height = "500" border = "0">
<div id = "charStat">
</div>
<div id = "charSelect">
<form method = "get" action = "form-action.html">
<input type = "radio" name="char" value = 0>Warrior<br>
<input type = "radio" name="char" value = 1>Magician<br>
<input type = "radio" name="char" value = 2>Healer<br>
<p>
<input type = "submit" value="OK">
</p>
</form>
</div>
</body>
<script src="js/charSelect.js"></script>
*// charSelect.js*
let char0 = `img/01.jpg`;
let char1 = `img/02.jpg`;
let char2 = `img/03.jpg`;
let char3 = `img/04.jpg`;
const imgArray = [ char0, char1, char2, char3, ];
const statWarrior = { class: `Warrior`, level: 1, hp: 1200, en: 300, }
const statMagician = { class: `Magician`, level: 1, hp: 800, en: 560, }
const statHealer = { class: `Healer`, level: 1, hp: 900, en: 410, }
const printStat = document.getElementById(`charStat`);
const radio = document.querySelectorAll(`input[type = "radio"]`);
function charChange(a) {
document.images[0].src = imgArray[a];
document.images[0].width = 500;
switch (a) {
case 0:
printStat.textContent = JSON.stringify(statWarrior);
break;
case 1:
printStat.textContent = JSON.stringify(statMagician);
break;
case 2:
printStat.textContent = JSON.stringify(statHealer);
break;
default:
printStat.textContent = `Please select your character.`;
}
}
for (i = 0; i < radio.length; i++) {
radio[i].addEventListener(`click`, function (e) {
charChange(e.target.value)
});
}
[Issue]:
When I click different radio buttons, image changes as intended. However, text message does not change but only shows the default message "Please select your character" instead. I am guessing that the switch (a) parameter is not receiving e.target.value for some reason, but there is no error message in the console.
[What I tried]:
Split the charChange(a) function into two separate functions (one
for image change, the other for text change) -- didn't work out;
Change switch into if-else -- didn't work out.
[Expected behavior]:
The intention is to make both image and text message change together, with the text message displaying the statWarrior, statMagician, statHealer objects.
As I just started learning, I would be happy to take any other comments or suggestions to improve that goes beyond my question above.
Thank you for your advice in advance.
e.target.value returns a string but the cases expect integers.
You can either turn a into an integer or do what I did below and have the cases expect strings.
function charChange(a) {
document.images[0].src = imgArray[a];
document.images[0].width = 500;
switch (a) {
case '0':
printStat.textContent = JSON.stringify(statWarrior);
break;
case '1':
printStat.textContent = JSON.stringify(statMagician);
break;
case '2':
printStat.textContent = JSON.stringify(statHealer);
break;
default:
printStat.textContent = `Please select your character.`;
}
}

I'm trying to make a Javascript calculator as part of a freecodecamp task but can't get it to work with IDs and data-operators

I've added ids and data operators and numbers to the html but the output still shows "NaN on the screen
I've tried to test it in the suite but the following tests don't pass:
My calculator should contain 10 clickable elements containing one number each from 0-9, with the following corresponding IDs: id="zero", id="one", id="two", id="three", id="four", id="five", id="six", id="seven", id="eight", and id="nine".
My calculator should contain 4 clickable elements each containing one of the 4 primary mathematical operators with the following corresponding IDs: id="add", id="subtract", id="multiply", id="divide".
My calculator should contain a clickable element with an id="clear"
At any time, pressing the clear button clears the input and output values, and returns the calculator to its initialized state; 0 should be shown in the element with the id of "display"
5.At any time, pressing the clear button clears the input and output values, and returns the calculator to its initialized state; 0 should be shown in the element with the id of "display"
In any order, I should be able to add, subtract, multiply and divide a chain of numbers of any length, and when I hit "=", the correct result should be shown in the element with the id of "display"
In any order, I should be able to add, subtract, multiply and divide a chain of numbers of any length, and when I hit "=", the correct result should be shown in the element with the id of "display"
I should be able to perform any operation (+, -, *, /) on numbers containing decimal points
I should be able to perform any operation (+, -, *, /) on numbers containing decimal points
I'm guessing I have to use a switch statement somewhere?
Can anyone help me? Thank you.
function getHistory() {
return document.getElementById('previous-operand').innerText;
}
function printHistory(num) {
document.getElementById('previous-operand').innerText = num;
}
function getOutput() {
return document.getElementById('display').innerText;
}
function printOutput(num) {
if (num == "") {
document.getElementById('display').innerText = num;
} else {
document.getElementById('display').innerText = getFormattedNumber(num);
}
}
function getFormattedNumber(num) {
if (num == "minus") {
return "";
}
var n = Number(num);
var value = n.toLocaleString("en");
return value;
}
function reverseNumberFormat(num) {
return Number(num.replace(/,/g, ''));
}
var operator = document.getElementsByClassName("operator");
for (var i = 0; i < operator.length; i++) {
operator[i].addEventListener('click', function() {
if (this.id == "clear") {
printHistory("");
printOutput("");
} else if (this.id == "backspace") {
var output = reverseNumberFormat(getOutput()).toString();
if (output) { //if output has a value
output = output.substr(0, output.length - 1);
printOutput(output);
}
} else {
var output = getOutput();
var history = getHistory();
if (output == "" && history != "") {
if (isNaN(history[history.length - 1])) {
history = history.substr(0, history.length - 1);
}
}
if (output != "" || history != "") {
output = output == "" ?
output : reverseNumberFormat(output);
history = history + output;
if (this.id == "=") {
var result = eval(history);
printOutput(result);
printHistory("");
} else {
history = history.this.id;
printHistory(history);
printOutput("");
}
}
}
});
}
var number = document.getElementsByClassName("number");
for (var i = 0; i < number.length; i++) {
number[i].addEventListener('click', function() {
//get output commas removed
var output = reverseNumberFormat(getOutput());
//
if (output != NaN) { //if output is a number
output = output + this.id;
printOutput(output);
}
});
}
<div id="calculator-grid" class="calculator-grid">
<div class="output">
<div id="previous-operand"></div>
<div id="display"></div>
</div>
<button data-operator="clear" class="operator">AC</button>
<button data-operator="del" class="operator">DEL</button>
<button data-operator="divide" id="divide" class="operator">รท</button>
<button data-number="1" id="one" class="number">1</button>
<button data-number="2" id="two" class="number">2</button>
<button data-number="3" id="three" class="number">3</button>
<button data-operator="multiply" class="operator">*</button>
<button data-number="4" id="four" class="number">4</button>
<button data-number="5" id="five " class="number">5</button>
<button data-number="6" id="six" class="number">6</button>
<button data-operator="add" id="add" class="operator">+</button>
<button data-number="7" id="seven" class="number">7</button>
<button data-number="8" id="eight" class="number">8</button>
<button data-number="9" id="nine" class="nine">9</button>
<button data-operator="minus" id="subtract" class="operator">-</button>
<button data-operator="decimal" id="decimal" class="operator">.</button>
<button data-number="0" id="zero" class="number">0</button>
<button data-operator="equals" id="equals" class="span-two operator">=</button>
</div>
I've made a Codepen to demonstrate your app with minimal styling, I recommend you do this the next time you're asking for help.
https://codepen.io/bashuatdiff/pen/JjoQZoe
I believe the "NaN" value is returned by this function.
function getFormattedNumber(num) {
if (num == "minus") {
return "";
}
var n = Number(num);
var value = n.toLocaleString("en");
return value;
}
The problem is that you're passing in a string to this function - that is, the id value of the Number Button that was clicked, appended to the current Output value. Then you use Number(num) to coerce this string to a number.
Any time you try to create a Number from a string with non-digit characters, the result will be NaN. In this case your id values are "one", "two", etc, none of which can be coerced to a Number - you'll end up with NaN.
Possible solutions:
Don't use word values for your id attributes. Instead of "two", use "2". More generally, you're converting back and forth between strings and numbers a lot throughout this code, and it will help to be aware of when you're expecting a string and when you're expecting a number.
Convert the id attribute to a number before concatenating it to the output. It's important to understand when the Plus symbol (+) is concatenating and when it's adding.
Add checks for "NaN" throughout your code. You had one: output != NaN but this won't actually work. Even NaN isn't equal to NaN. Instead, try something like typeof output == "number".
Good luck.

How to populate circle type percentage validation in jQuery

I have five input fields, I need to validate all the fields by showing a circle type validation modal. It will be incremented dynamically.
Please find attached sample validation images.
Here is the code:
$("#field1, #field2, #field3").blur(function() {
var getImageName = $('#step-dwld').attr('src').slice(7, 30);
if( !this.value ){
$('#step-dwld').attr('src', 'images/'+getImageName);
} else{
switch (getImageName) {
case "step-bg.png":
$('#step-dwld').attr('src', "images/step-1.png");
break;
case "step-1.png":
$('#step-dwld').attr('src', "images/step-2.png");
break;
case "step-2.png":
$('#step-dwld').attr('src', "images/step-3.png");
break;
}
}
});
Because of your vague question without or with very less code it is hard for us to guess what your code is and your HTML structure, you need to create a Minimal, Complete, and Verifiable example so that others can help you.
However check this it might give you an idea on how to do it, I don't now your code this why and based on guesswork I implemented a similar one to simulate it
JS Fiddle
var validate = $('.validate'), score= 0;
validate.on('change', function(){
score = 0;
validate.each(function(){
if($(this).val() != ''){
score += 100 / validate.length;
}
console.log(score);
setImage(score);
});
});
function setImage(score){
var url;
switch (score){
case 20:
url = '20%';
break;
case 40:
url = '40%';
break;
case 60:
url = '60%';
break;
case 80:
url = '80%';
break;
case 100:
url = '100%';
break;
default:
url = '0%';
}
var img = '<img src="//placehold.it/100x100/?text=' +url+ '">';
$('#img').html(img);
}
#img{width:100px;height:100px;border:1px solid gray;margin:10px 0;}
input[type="text"]{display:block;margin:2px 0;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="img"></div>
<input type="text" class="validate">
<input type="text" class="validate">
<input type="text" class="validate">
<input type="text" class="validate">
<input type="text" class="validate">
<button id="done">I'm Done!</button>

Display image depending on two input radio buttons

I am trying to display an image based on the selection of 4 different radio buttons with 2 different names.
For example the first set of radio buttons should select the product model (two options) and the second set of radio buttons the color (two options).
Here are the radio buttons:
<img src="Rack-BK.jpg" name="formula" id="formula">
<br>
<input type="radio" name="model" value="Rack" id="rack_option">Rack
<input type="radio" name="model" value="NoRack" id="norack_option" >NoRack
<br><br>
<input type="radio" name="color" value="Black" id="black_option" > Black
<input type="radio" name="color" value="Gray" id="gray_option" > Gray
This is what is working but only to select the model but I need the color to be added also.
<script type='text/javascript'>
$(document).ready(function(){
$("input:radio[name=model]").click(function() {
var value = $(this).val();
var image_name;
if(value == 'Rack'){
image_name = "Rack-BK.jpg";
}else{
if(value == 'NoRack'){
image_name = "Without-Rack-BK.jpg";
}
}
$('#formula').attr('src', image_name);
});
});
This is what I tried doing but doesn't work:
<script type='text/javascript'>
$(document).ready(function(){
$("input:radio[name=model]").click(function()
$("input:radio[name=color]").click(function()
{
var value = $(this).val();
var image_name;
if(value == 'Rack')
{
if (value == 'Gray')
{
image_name = "Rack-GY.jpg";
}
image_name = "Rack-BK.jpg";
}
}else{
if(value == 'NoRack')
{
if (value =='Gray'
{
image_name = "Without-Rack-GY.jpg";
}
image_name = "Without-Rack-BK.jpg";
}
}
$('#formula').attr('src', image_name);
});
});
In this case, it appears that a combination of using a switch statement and the 'checked' selector would be of good use.
I would put the event handler on both the radio groups...in this case the input:radio[name=model] and input:radio[name=color] (explicitly defined in case you have any other radio buttons on the page).
Then, inside of the handler get the currently selected value for each group, and do your handling inside of switch statements (better suited for handling a lot of if/else style of checking when you're just looking at the value of the item). This means if you add more options, such as blue, yellow, etc, it will be easier to drop in and handle those cases.
TL;DR: Here's how you could do it:
$("input:radio[name=model], input:radio[name=color]").click(function() { // This handler runs when any of the radio buttons are clicked.
var modelValue = $("input:radio[name=model]:checked").val(); // Find which model radio button is checked.
var colorValue = $("input:radio[name=color]:checked").val(); // Find which color radio button is checked.
var image_name = ""; // Initialize the image name to blank. We will be appending as we go.
switch (modelValue) {
case 'Rack':
image_name += "Rack"; // Rack was selected, so use that value for the first part of the image.
break;
case 'NoRack':
image_name += "Without-Rack"; // No Rack was selected, so use that value for the first part of the image.
break;
default:
image_name += "Rack"; // Make sure there is a default value, or a broken image could occur!
break;
}
switch (colorValue) {
case 'Black':
image_name += "-BK.jpg"; // Black was selected, so use that value for the last part of the image.
break;
case 'Gray':
image_name += "-GY.jpg"; // Gray was selected, so use that value for the last part of the image.
break;
default:
image_name += "-BK.jpg"; // Make sure there is a default value, or a broken image could occur!
break;
}
$('#formula').attr('src', image_name); // Put the image value in the formula image field src.
});

Categories