I'm trying to make clicking the battle button print "You have slain" + selected option + What I have now works for the first option, but if you select a different option in the dropdown and click battle it still says Fly.
Fiddle
var mon = document.getElementById('monsters');
var monster =mon.options[mon.selectedIndex].text;
$('#battle').click(function() {
document.getElementById('dam').innerHTML = "You have hit the " + monster + " for 5 damage";
});
In your solution, you have declared the values of the selected value globally which is set only once during the document load. In order to calculate the right value, you have to declare them locally during the button click.
$('#battle').click(function() {
var mon = document.getElementById('monsters');
var monster =mon.options[mon.selectedIndex].text;
document.getElementById('dam').innerHTML = "You have hit the " + monster + " for 5 damage";
});
Working example : https://jsfiddle.net/DinoMyte/4dyph8jh/5/
Updated fiddle
Because you're using jQuery it could be simply :
$('#battle').click(function() {
$('#dam').text("You have hit the " + $('#monsters option:selected').text() + " for 5 damage");
});
Hope this helps.
Related
to summarize my problem ... I have made a calendar with contains the from - to date range. Now the selected dates are displayed in a div with a delete button for each. But as the id of the button is the same for all the dates ....it deletes the entire date range. I have attached the screenshot as well.
I also tried taking a loop and giving each date a div so that the Del function will work properly. but I wasn't successful. I will mention code for the same
$(document).ready(function () {
var i = 0;
$.each(between, function (key, value) {
var rest = $('#target').append($('<div id="r' + i +value+ '" class="ansbox">
</div>'));
console.log(between);
var template = '<div id="ChildTarget_' + i + '"><span>key + ":" + "' + value + '"
</span><button id="tr' + i + '" class="target">X</button></div><br></div>';
i++;
$('#target').on('click', function () {
console.log("hola");
$('#target').remove();
You should add click event for the button itself.
var template = `
<div id="ChildTarget_' + i + '">
<span>key + ":" + "' + value + '"</span>
<button id="tr' + i + '" class="deleteButton">X</button>
</div>`;
$(".deleteButton').on('click', function() {
// do deletion here
});
First of all ,
The 'X' button should have different id
$.each(between, function (key, value){
$('#results').append(key+":"+value+'<br>');
$('#results').html(between.join('<button id="result"+key+"" > X </button><br>')
here you can see i am adding key to the Button Id making it unique. Use that id to remove the value, that you dont want. Hope this helps
I am trying to write a web page where I can detect button presses on a Xbox controller and show a user a boolean value based on the button pressed. Right now, I can detect a controller being connected and show that as a string. The documentation says to use this code to detect a button press here:
var isPressed = navigator.getGamepads()[0].pressed;
but Chrome shows this error when using it:
Uncaught TypeError: Cannot read property 'pressed' of null
The error is linked to the .pressed part of the above line of code. All the documentation is on the Mozilla site, so I'm assuming they used FireFox when writing the tutorials.
What I ideally want to end up with is this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<h id="button"></h>
<h id="gpInfo"></h>
<script>
var i = 1;
window.addEventListener("gamepadconnected", function(e) {
var gp = navigator.getGamepads()[e.gamepad.index];
document.getElementById("gpInfo").innerHTML = ("A " + gp.id + " was successfully detected! There are a total of " + gp.buttons.length + " buttons.")
//alert("A " + gp.id + " was successfully detected!")
});
var isPressed = navigator.getGamepads()[0].pressed;
document.getElementById("button").innerHTML = isPressed;
</script>
<!-- <script type="text/javascript" src="gamepadtest.js"></script> -->
</head>
</html>
The code would print a boolean value on the screen for users to see when they press a button.
This is my first time working with JavaScript and HTML. If you could make your answer noob-friendly that would be great! Documentation for Gamepad API and for GamepadButton
You shouldn't reference the Gamepad object until the gamepadconnected event has been thrown. Also, you'll need a loop to poll the button value. Here's some revised code:
var i = 1;
window.addEventListener("gamepadconnected", function(e) {
var gp = navigator.getGamepads()[e.gamepad.index];
document.getElementById("gpInfo").innerHTML = ("A " + gp.id + " was successfully detected! There are a total of " + gp.buttons.length + " buttons.")
//alert("A " + gp.id + " was successfully detected!")
setInterval(function(){
isPressed = gp.buttons[0].pressed;
document.getElementById("button").innerHTML = isPressed;
}, 100)
});
I don't have enough reputation to just add a comment to Caleb Denio's answer, but regarding Nathan's comment on that answer:
I have used your example to listen for 20 buttons and i can detect each button, but once i have pressed one, it will not change another result for a different button.
I see the same behaviour on Chrome 90. Specifically, a new GamepadList instance, containing new Gamepad instances, all seem to be created each time the state of any gamepad changes (e.g. which of its buttons are pressed).
You can test it with this:
var gamepads = null;
function callback() {
var new_gamepads = navigator.getGamepads();
if(new_gamepads !== gamepads) {
console.log('New GamepadList!', new_gamepads);
gamepads = new_gamepads;
}
}
var interval = setInterval(callback, 100);
...for me, that logs 'New GamepadList!' each time I press/release a button.
Long story short, you need to poll navigator.getGamepads() each frame in order to detect changes in gamepad state.
A minimalist fix for Caleb Denio's answer would therefore be:
var i = 1;
window.addEventListener("gamepadconnected", function(e) {
var gp = navigator.getGamepads()[e.gamepad.index];
document.getElementById("gpInfo").innerHTML = ("A " + gp.id + " was successfully detected! There are a total of " + gp.buttons.length + " buttons.")
//alert("A " + gp.id + " was successfully detected!")
setInterval(function(){
// ===> Get a fresh GamepadList! <===
var gp = navigator.getGamepads()[e.gamepad.index];
isPressed = gp.buttons[0].pressed;
document.getElementById("button").innerHTML = isPressed;
}, 100)
});
onclick on <li> element, I want to clear div which i will find by id. I have got a code
javascript this is how i writing code in a div:
document.getElementById("outputLaps").insertAdjacentHTML(
"beforebegin",
<br /> + "some code";
And that's how i try to clear the div:
document.getElementById("outputLaps").innerHTML = '';
or
var myNode = document.getElementById("outputLaps");
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
But they don't work.
#EDIT
Ok, i tried some solutions from answer but they are not working fine. I will try to explain it one more time.
I've got two elements. When i click on one, it adds some content to div. When i click on second element, i want to clear this div, not completely destroy it. Some solutions from the answers clear only something that i wrote in the div before first element add some code to it.
HTML
<ul>
<li id="lap" onclick="displayLap()">Lap</li>
<li id = "clear" onclick="clearLaps()">Clear laps</li>
</ul>
<div id="outputLaps">rr</div>
First element on click add text:
function displayLap() {
numberOfLap++;
document.getElementById("outputLaps").insertAdjacentHTML(
"beforebegin",
" Number of lap: " + numberOfLap + " time: " + minutes + ":" + seconds + ":" + milliseconds
);
}
Then i want to clear it with this function:
function clearLaps() {
}
You were close:
document.getElementById("outputLaps").outerHTML='';
You can use this.
var node = document.getElementById("outputLaps");
node.parentNode.replaceChild(node.cloneNode(false), node);
Or if you want to destroy all.
var node = document.getElementById("outputLaps");
node.parentNode.removeChild(node);
Ok, I finally created what I wanted. Thanks everyone for answer. I had to change the way of adding text to the div, had to change it all on text so the innerHTML could clear it easy. I had to not use <br /> but instead of "\n", so it display next text properly. Here what I have now:
html
<ul>
<li id="lap" onclick="displayLap()">Lap</li>
<li id = "clear" onclick="clearLaps()">Clear laps</li>
</ul>
<div id="outputLaps"></div>
JS
function displayLap() {
numberOfLap++;
var str = "Number of lap: " + numberOfLap + " time: " + minutes + ":" + seconds + ":0" + milliseconds + "\n";
document.getElementById("outputLaps").appendChild(
document.createTextNode(str))
}
function clearLaps() {
numberOfLap = 0;
document.getElementById("outputLaps").innerHTML = "";
}
for javascript use .remove()
document.getElementById("outputLaps").remove();
you can do this in jquery
$(function() {
$("li").on("click",function() {
$("#outputLaps").remove();
});
});
I have created one html which contains search box. After searching, I'm getting the data in list. But when I click on that I'm getting the value of all list item by using this
var text = $(this).text(); method
In my app, if I click on one item only it should give me only that value of list item not other. I'm making a mistake somewhere, but I don't know where.
Here is my code:
HTML
<ul data-role="listview" class="ui-li-icon">
<li id="list"></li>
</ul>
And here is my JavaScript code:
function successCallback(responseObj)
{
// alert(JSON.stringify(responseObj));
form.reset();
dataj=JSON.stringify(responseObj);
len=dataj.length;
for(i=0;i<len;i++)
{
var output = "<ul>" + responseObj.merchants[i].imageFileName+ " " + "<font size=3 color=green>" + responseObj.merchants[i].merchantName + "</font>" +"</ul>";
$('#list').append(output);
}
$('#list').click(function() {
var index = $(this).index();
var text = $(this).text();
alert('Index is: ' + index + ' and text is ' + text);
});
}
So when I'm searching for some a item. I'm getting list of:
ab
abc
But when I clicked on it. I get value of both ab and abc. I just want only one value where I have clicked.
//replace your click event by below code
$('.ui-li-icon li').click(function() {
var index = $(this).index();
var text = $(this).text();
alert('Index is: ' + index + ' and text is ' + text);
});
$('#list').append(output);
I believer list is the id you are giving to list items i.e.
Now, this will confuse the browser because id should be UNIQUE and here you are giving this id to all the list items.
If you fix this, your problem should be resolved!
Or you could simply attach click event using this
$('.ui-li-icon li').click //Your click event handler
It's very difficult to understand what you are asking. From what I can tell you're looking for something like this:
$('#list li').on('click', function(){
alert("index: "+$(this).index() + " value: "+ $(this).text());
});
Here's a fiddle http://jsfiddle.net/Jw8qz/
I need the values of the name, address, size, and topping fields to appear in a text box. Without problems the name and address appears correctly. However I can't seen to get the size function to work. It is a radio button, and thus I need only one size to appear. I haven't even tried an if else for the checkbox yet. Here is my code
<html>
<head>
<script>
function pizza() {
document.pizzaboy.comments.value = "Name:" + " " + pizzaboy.name.value + "\n" + "Address:" + " " + pizzaboy.address.value + "\n" + document.getElementById("small").value + document.getElementById("medium").value + document.getElementById("large").value + "\n" + pizzaboy.toppings.value;
{
var rslt = "";
if (document.pizzaboy.size[0].checked) {
rslt = rslt + "Size=Small\n";
} else if (document.pizzaboy.size[1].checked) {
rslt = rslt + "Size=Medium\n";
} else rslt = rslt + "Size=Large\n";
return rslt;
}
}
</head>
The second Javascript bracket might be throwing you an error, keeping your code from running correctly.
In this post, several (more general) ways to get values of radio buttons are explained:
Checking Value of Radio Button Group via JavaScript?
The first answer is using jQuery, but the following answers will help you i think.
You should try this. Answer here if you need further assistance.