Java script hangman game issues - javascript

I've been working on a hangman game using an HTML template and javascript for a project for a class.
I am currently stuck with a few issues.
1. I am using an array to call the pictures for wrong guesses to add parts to the body in the gallows. only picture #4 shows up when 4 incorrect guesses have occurred.
2. I also have the issue that only for certain words do the buttons decide to actually work and the letter "o" never works
Any help would be greatly appreciated.
<!DOCTYPE HTML>
<html>
<head>
<title>Hangman</title>
<meta charset="utf-8">
<script type="text/javascript" language="JavaScript">
var NumberOfChances;
var theWord = "",oldString="";
var currentGuessed = "";
var value="";
var words = new Array();
words[0]="No strings attached";
words[1]="Never look back";
words[2]="Happy birthday";
words[3]="Against all odds";
words[4]="Break a leg";
words[5]="Off the beaten path";
words[6]="Good old days";
words[7]="Gold rush";
words[8]="Happy camper";
words[9]="Grin from ear to ear";
words[10]="Live long and prosper";
words[11]="Quartz watch";
words[12]="Jumping jacks";
words[13]="Income tax";
var image = new Array();
image[0] = '<img src="image0.jpg" align ="left" width="415" height="496">';
image[1] = "<img src='image1.jpg' align ='left' width='415' height='496'>";
image[2] = '<img src="image2.jpg" align ="left" width="415" height="496">';
image[3] = '<img src="image3.jpg" align ="left" width="415" height="496">';
image[4] = '<img src="image4.jpg" align ="left" width="415" height="496">';
image[5] = '<img src="image5.jpg" align ="left" width="415" height="496">';
image[6] = '<img src="image6.jpg" align ="left" width="415" height="496">';
NumberOfChances = image.length;
function swap(image)
{
document.getElementById("images").src =image+".gif";
}
var usedLetters = new Array();
function secretWord()
{
debugger
theWord = words[Math.floor(Math.random()*51)];
for (i=0; i<theWord.length; i++)
{
currentGuessed = currentGuessed + "*";
}
document.getElementById("secretWord").value = currentGuessed;
debugger
}
function gameProcess()
{
currentGuessed ="";
secretWord();
NumberOfChances=0;
document.getElementById("lives").value = NumberOfChances;
startImage = image[0];
}
function turn(letterGuessed)
{
debugger
value = oldString = "";
var correctGuess = false;
for (i=0; i<theWord.length; i++)
{
if (theWord.charAt(i) == letterGuessed)
{
value = value + letterGuessed;
currentGuessed = currentGuessed.replace(oldString + "*",value);
oldString = value;
correctGuess=true;
}
else
{
if(currentGuessed.charAt(i) == "*")
{
value = value + '*';
oldString = oldString + "*";
}
else
{
value = value + currentGuessed.charAt(i);
oldString = oldString + currentGuessed.charAt(i);
}
}
}
if (!correctGuess)
{
NumberOfChances++;
swap("image" + NumberOfChances );
if (NumberOfChances==6)
{
alert("You Lost!");
document.getElementById("secretWord").value = theWord;
theWord = "";
currentGuessed = "";
}
document.getElementById("lives").value = NumberOfChances;
if(correctGuess != 0)
{
takeChance();
}
}
win();
}
function win()
{
var winCount = 0;
for(var i = 0;i<theWord.length;i++)
{
if(currentGuessed.charAt(i) == "*")
{
winCount++;
}
document.getElementById("secretWord").value = currentGuessed;
}
if(winCount == 0 && currentGuessed != "")
{
alert("yay, you win!");
}
}
</script>
</head>
<body>
<H1>Lets play Hangman</H1>
<form name="userGuessForm" id="form1">
<div id="Image"><img src="image0.gif" align ="left" width="415" height="496" id="images"/></div>
<div id="wordDisplay"></div>
This is the Secret Word<br /><input id="secretWord" type="text" value="currentGuessed" />
<br />
<input id="letters" type="button" name="a" value="a" onClick="turn('a');">
<input id="Button1" type="button" name="b" value="b" onClick="turn('b');">
<input id="Button2" type="button" name="c" value="c" onClick="turn('c');">
<input id="Button3" type="button" name="d" value="d" onClick="turn('d');">
<input id="Button4" type="button" name="e" value="e" onClick="turn('e');">
<input id="Button5" type="button" name="f" value="f" onClick="turn('f');">
<input id="Button6" type="button" name="g" value="g" onClick="turn('g');">
<input id="Button7" type="button" name="h" value="h" onClick="turn('h');">
<input id="Button8" type="button" name="i" value="i" onClick="turn('i');">
<input id="Button9" type="button" name="j" value="j" onClick="turn('j');">
<input id="Button10" type="button" name="k" value="k" onClick="turn('k');">
<input id="Button11" type="button" name="l" value="l" onClick="turn('l');">
<input id="Button12" type="button" name="m" value="m" onClick="turn('m');">
<input id="Button13" type="button" name="n" value="n" onClick="turn('n');">
<input id="Button14" type="button" name="o" value="o" onClick="turn('o');">
<input id="Button15" type="button" name="p" value="p" onClick="turn('p');">
<input id="Button16" type="button" name="q" value="q" onClick="turn('q');">
<input id="Button17" type="button" name="r" value="r" onClick="turn('r');">
<input id="Button18" type="button" name="s" value="s" onClick="turn('s');">
<input id="Button19" type="button" name="t" value="t" onClick="turn('t');">
<input id="Button20" type="button" name="u" value="u" onClick="turn('u');">
<input id="Button21" type="button" name="v" value="v" onClick="turn('v');">
<input id="Button22" type="button" name="w" value="w" onClick="turn('w');">
<input id="Button23" type="button" name="x" value="x" onClick="turn('x');">
<input id="Button24" type="button" name="y" value="y" onClick="turn('y');">
<input id="Button25" type="button" name="z" value="z" onClick="turn('Z');"><br />
Number of Tries (6): <input id="lives" type="text" value="0" onfocus="lives.blur();" SIZE=2>
<input type="button" name="submit" value=" Start Over " onClick="gameProcess()">
<input type="button" name="end" value=" END " onClick="gameEnd()"><br />
</form>
</body>
</html>

Your images aren't working correctly because you're using an array as a string.
document.getElementById("images").src =image+".gif";
should be
document.getElementById("images").src ="image"+NumberOfChances+".gif";
otherwise, what you're doing is taking the html of all the images and setting it as the src attribute for your image.
<img src="<img src="image0.jpg" align ="left" width="415" height="496">, <img src="image1.jpg" align ="left" width="415" height="496">, <img src="image2.jpg" align ="left" width="415" height="496">..." id="images"> This isn't what you want!
And also, I think you've got your jpgs and gifs mixed up. Check your file extensions.
Also, do you have 50 words that you aren't showing here? Your array contains 13, but later you write
theWord = words[Math.floor(Math.random()*51)];
And that seems to suggest you have one less than 51, or 50, words.
In your letterGuessed function, I don't think you're quite grasping the concept of for loops. What you seem to be thinking is that a new iteration happens each time you call the function, but that isn't the case. Rather, the for loop goes through the entire word each time you call the function with the one letter you guessed. So unless every single letter in the word is o, if you guess the letter o, you'll get one point for every o in the word, and -1 chance for every character that isn't o, which isn't what you want. Ditch the for loop and just use i++ for each time the function runs.

function swap(image)
{
document.getElementById("images").src =image+".gif";
}
Try changing gif to jpg

if (!correctGuess)
{
NumberOfChances++;
swap(image[NumberOfChances]);

Related

Javascript how to sum tables

Hello I have a problem with such a task I totally don't know how to get down to it, I hope someone will help me to write an application allowing to calculate the sum and the difference of two 2-dimensional numerical tables. Each of these tables should have 2 lines and 3 columns. Input data - the values of individual array elements - enter the keypads. Present the results on screen, on the same website.
My code is below:
<!DOCTYPE html>
<html lang="pl">
<head>
<title> JavaScript: tablice 2-wymiarowe. </title>
<meta charset="UTF-8">
</head>
<body>
<form id="form1">
Podaj 12 liczb <br />
Pierwsza: <input id="input1" type="text" value="1" /><br />
Druga: <input id="input2" type="text" value="2" /><br />
Trzecia: <input id="input3" type="text" value="3" /><br />
Czwarta: <input id="input4" type="text" value="4" /><br />
piata: <input id="input5" type="text" value="5" /><br />
szosta: <input id="input6" type="text" value="6" /><br />
</form>
<button onclick="przetwarzanie();"> Oblicz </button>
<div id="div1"> </div>
<script>
function przetwarzanie() {
var input1 = document.getElementById("input1");
var input2 = document.getElementById("input2");
var input3 = document.getElementById("input3");
var input4 = document.getElementById("input4");
var input5 = document.getElementById("input5");
var input6 = document.getElementById("input6");
var div1 = document.getElementById("div1");
var tablica = [];
tablica[0] = Number(input1.value, input2.value, input3.value);
tablica[1] = Number(input4.value, input5.value, input6.value);
suma = tablica[0] + tablica[1];
}
document.getElementById("div1").innerHTML = "Suma = " + suma;
</script>
</body>
</html>
First of all the last line of your script is outside the function while it uses a variable that is inside, this will not work but can easily be fixed by moving the line inside the function.
The second issue is that Number converts a string to a number. It does not sum them up. Instead move each input value to it's own Number function and add them together with the + sign.
For the difference in the two numbers you can just subtract one from the other. With Math.abs() we turn the number into a positive. This way we don't need to think about which of the two numbers is higher.
<!DOCTYPE html>
<html lang="pl">
<head>
<title> JavaScript: tablice 2-wymiarowe. </title>
<meta charset="UTF-8">
</head>
<body>
<form id="form1">
Podaj 12 liczb <br />
Pierwsza: <input id="input1" type="text" value="1" /><br />
Druga: <input id="input2" type="text" value="2" /><br />
Trzecia: <input id="input3" type="text" value="3" /><br />
Czwarta: <input id="input4" type="text" value="4" /><br />
piata: <input id="input5" type="text" value="5" /><br />
szosta: <input id="input6" type="text" value="6" /><br />
</form>
<button onclick="przetwarzanie();"> Oblicz </button>
<div id="div1"> </div>
<div id="div2"> </div>
<script>
function przetwarzanie() {
var input1 = document.getElementById("input1");
var input2 = document.getElementById("input2");
var input3 = document.getElementById("input3");
var input4 = document.getElementById("input4");
var input5 = document.getElementById("input5");
var input6 = document.getElementById("input6");
var div1 = document.getElementById("div1");
var tablica = [];
tablica[0] = Number(input1.value) + Number(input2.value) + Number(input3.value);
tablica[1] = Number(input4.value) + Number(input5.value) + Number(input6.value);
var suma = tablica[0] + tablica[1];
var roznica = Math.abs(tablica[0] - tablica[1]);
document.getElementById("div1").innerHTML = "Suma = " + suma;
document.getElementById("div2").innerHTML = "Różnica = " + roznica;
}
</script>
</body>
</html>
Suma undefined means you never created a variable and then you used it which caused the error below code is working just put all your code inside onclick function so when clicked it calculates and add it to html.
<!DOCTYPE html>
<html lang="pl">
<head>
<title> JavaScript: tablice 2-wymiarowe. </title>
<meta charset="UTF-8">
</head>
<body>
<form id="form1">
Podaj 12 liczb <br />
Pierwsza: <input id="input1" type="text" value="1" /><br />
Druga: <input id="input2" type="text" value="2" /><br />
Trzecia: <input id="input3" type="text" value="3" /><br />
Czwarta: <input id="input4" type="text" value="4" /><br />
piata: <input id="input5" type="text" value="5" /><br />
szosta: <input id="input6" type="text" value="6" /><br />
</form>
<button onclick="przetwarzanie();"> Oblicz </button>
<div id="div1"> </div>
<script>
function przetwarzanie() {
var input1 = document.getElementById("input1");
var input2 = document.getElementById("input2");
var input3 = document.getElementById("input3");
var input4 = document.getElementById("input4");
var input5 = document.getElementById("input5");
var input6 = document.getElementById("input6");
var div1 = document.getElementById("div1");
var tablica = [];
tablica[0] = Number(input1.value, input2.value, input3.value);
tablica[1] = Number(input4.value, input5.value, input6.value);
let suma = tablica[0] + tablica[1];
document.getElementById("div1").innerHTML = "Suma = " + suma;
}
</script>
</body>
</html>

input a button value on corresponding textbox that is on focus

I am trying to create a touchscreen calculator like where the button value will be placed on the textbox after i set it on a focus by clicking but it appears on all the textboxes.I tried to use the code
if ($(impo).is(":focus")) {
but it doesnt work. Please see my snippet
Thanks in advance!
var impo = document.getElementById("imp_text");
var tess = document.getElementById("tess_text");
var FKeyPad = document.Keypad;
var Accumulate = 0;
var FlagNewNum = false;
var PendingOp = "";
document.getElementById('tess').onclick = function() {
document.getElementById('tess_text').focus();
}
document.getElementById('imp').onclick = function() {
document.getElementById('imp_text').focus();
}
function NumPressed(Num) {
if (impo) {
if (FlagNewNum) {
FKeyPad.ReadOut.value = Num;
FlagNewNum = false;
} else {
if (FKeyPad.ReadOut.value == " ")
FKeyPad.ReadOut.value = Num;
else
FKeyPad.ReadOut.value += Num;
}
}
if (tess) {
if (FlagNewNum) {
FKeyPad.readtess.value = Num;
FlagNewNum = false;
} else {
if (FKeyPad.readtess.value == " ")
FKeyPad.readtess.value = Num;
else
FKeyPad.readtess.value += Num;
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html lang="en">
<head>
</head>
<body>
<form name="Keypad" action="">
<input type="button" value="Imp" id="imp" /> Importo :
<input name="ReadOut" id="imp_text" type="Text" value=" "> <br>
<input type="button" value="Tes" id="tess" /> Card Tess :
<input name="readtess" id="tess_text" type="Text" value=" ">
<br>
<input type="button" value=" 1" onclick="NumPressed(1)" />
<input type="button" value=" 2" onclick="NumPressed(2)" />
<input type="button" value=" 3" onclick="NumPressed(3)" /> <br>
</form>
</body>
</html>
if (impo) and if (tess) just tests whether the element exists, which they do, so the value gets written to both of them because they both exist. In a desktop environment, you can't do what you're asking - you can give a textbox the focus, but once the user clicks on one of the buttons in order to select that number, the textbox no longer has the focus (because the button has it).
You need a separate way to maintain which textbox is currently selected, something like the snippet below. It will update the currently "selected" element both on the click of the Imp/Tes buttons and whenever either of the textbox gains focus (e.g. by mouse click or touch).
var impo = document.getElementById("imp_text");
var tess = document.getElementById("tess_text");
var current_input = impo;
impo.onfocus = function() {
current_input = impo;
}
tess.onfocus = function() {
current_input = tess;
}
document.getElementById('tess').onclick = function() {
current_input = tess;
tess.focus();
}
document.getElementById('imp').onclick = function() {
current_input = impo;
impo.focus();
}
function NumPressed(Num) {
current_input.value += Num;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html lang="en">
<head>
</head>
<body>
<form name="Keypad" action="">
<input type="button" value="Imp" id="imp" /> Importo :
<input name="ReadOut" id="imp_text" type="Text" value=""> <br>
<input type="button" value="Tes" id="tess" /> Card Tess :
<input name="readtess" id="tess_text" type="Text" value="">
<br>
<br>
<input type="button" value="1" onclick="NumPressed(this.value)" />
<input type="button" value="2" onclick="NumPressed(this.value)" />
<input type="button" value="3" onclick="NumPressed(this.value)" /> <br>
<input type="button" value="4" onclick="NumPressed(this.value)" />
<input type="button" value="5" onclick="NumPressed(this.value)" />
<input type="button" value="6" onclick="NumPressed(this.value)" /> <br>
<input type="button" value="7" onclick="NumPressed(this.value)" />
<input type="button" value="8" onclick="NumPressed(this.value)" />
<input type="button" value="9" onclick="NumPressed(this.value)" /> <br>
<input type="button" value="0" onclick="NumPressed(this.value)" /> <br>
</form>
</body>
</html>

Change a variable when button is clicked

Trying to make simple tic-tac-toe game. I'm trying to change the button's value when clicked, but I don't know which one the user will click first. Obviously, I've got 9 buttons like this:
<input type="button" id="Button1" onclick="Button1_Click()" />
and a function like this, to handle their onclick event.
<script>
var Caption = "X";
function Button1_Click() {
document.getElementById('Button1').value = Caption;
if (Caption=="X") {
Caption = "O";
Caption="X";
}
}
</script>
But the thing is, when i click other buttons, The caption is always the same (X), how can I change it?
I think you may just change your Button1_Click() like below:
function Button1_Click() {
document.getElementById('Button1').value = Caption;
if (Caption=="X") {
Caption = "O";
} else {
Caption="X";
}
}
But, in this way, you said you have 9 buttons. Then you have to create 9 separated but look quite the same function like the one above.
How about this:
<!--You need to make it look better..-->
<div id='buttonParent'>
<input type='button' id='btn1'>
<input type='button' id='btn2'>
<input type='button' id='btn3'>
<input type='button' id='btn4'>
<input type='button' id='btn5'>
<input type='button' id='btn6'>
<input type='button' id='btn7'>
<input type='button' id='btn8'>
<input type='button' id='btn9'>
</div>
<script>
// wrap all your 9 buttons in a tag <div id='buttonParent'> or whatever you like.
var buttonParentNode = document.getElementById('buttonParent');
var button_click = function(e) {
// this function handle all button click event
var btn = e.target; // DOM element which was click. It must be any tag inside buttonParentNode
if (btn.tagName == 'INPUT') { // if DOM element is a input tag.
if (btn.innerHTML == 'X') {
btn.innerHTML = 'O';
} else {
btn.innerHTML = 'X';
}
}
};
buttonParentNode.addEventListener('click', button_click, false);
</script>
Method 1: Closure
One way to do it is using a closure for the click handler, so it knows which button was pressed. Keep track of who'se turn it is in a variable.
// Do this only when the page is loaded.
window.addEventListener('DOMContentLoaded', function() {
// Variable to keep track of turns in.
var Xturn = true;
// A function that returns a specific click handler for a button.
function createClickHandler(element, index) {
// The anonymous function that is returned is the actual click handler.
return function() {
// Logs text in the console (press F12 to view it). Very useful for testing/debugging!
console.log('Button ' + index + ' clicked');
// Only do something if this button was still open.
if (element.innerText == '') {
element.innerText = Xturn ? 'X' : 'O';
Xturn = !Xturn; // Toggle player
};
}
}
// Now for the actual initialisation:
// Find all buttons.
var buttons = document.querySelectorAll('button');
// Attach a click handler to each of them.
for (n = 0; n < buttons.length; n++) {
buttons.item(n).addEventListener('click', createClickHandler(buttons.item(n), n));
}
});
button {
width: 50px;
height: 50px;
line-height: 50px;
vertical-align: bottom;
}
<div>
<button/><button/><button/>
</div>
<div>
<button/><button/><button/>
</div>
<div>
<button/><button/><button/>
</div>
Method 2: Event target
When an event is triggered, the event handler gets an event object as a parameter. This object contains information about the event, like the element that triggered it. This way you can also find the button. If you give every button an id or other recognizable property, you can distinguish between the buttons.
You can bind an event handler on every button, but it's even easier to bind it to a parent element. You can even bind the click handler to the document. That way you also don't have to wait for the DOM to be loaded. The even handler will capture every click, and it will even capture clicks on elements that are dynamically added later.
Inside the event handler, you can get the element that triggered it, and only respond if it is one of the buttons of the game:
// Variable to keep track of turns in.
var Xturn = true;
document.addEventListener('click', function(event) {
var event = event || window.event;
var element = event.target || event.srcElement;
// Only respond to button clicks
if (element.tagName == 'BUTTON') {
console.log('Button ' + element.id + ' clicked');
// Only do something if this button was still open.
if (element.innerText == '') {
element.innerText = Xturn ? 'X' : 'O';
Xturn = !Xturn; // Toggle player
}
}
});
button {
width: 50px;
height: 50px;
line-height: 50px;
vertical-align: bottom;
}
<div>
<button id='b1' /><button id='b2' /><button id='b3' />
</div>
<div>
<button id='b4' /><button id='b5' /><button id='b6' />
</div>
<div>
<button id='b7' /><button id='b8' /><button id='b9' />
</div>
function button_Click(e) {
if(e.value === 'X') {
e.value = 'O';
} else {
e.value = 'X';
}
}
<input type="button" id="button1" onclick="button_Click(this)" value="X" />
<input type="button" id="button2" onclick="button_Click(this)" value="O" />
<input type="button" id="button3" onclick="button_Click(this)" value="X" />
<input type="button" id="button4" onclick="button_Click(this)" value="O" />
<input type="button" id="button5" onclick="button_Click(this)" value="X" />
<input type="button" id="button6" onclick="button_Click(this)" value="O" />
<input type="button" id="button7" onclick="button_Click(this)" value="X" />
<input type="button" id="button8" onclick="button_Click(this)" value="O" />
<input type="button" id="button9" onclick="button_Click(this)" value="X" />
<input type="button" id="button10" onclick="button_Click(this)" value="O" />
However a better approach would be as follows:
document.addEventListener("DOMContentLoaded", buttonClickHandler);
function buttonClickHandler() {
var buttons = document.getElementsByClassName('button');
for(var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', function() {
if(this.value === 'X') {
this.value = 'O';
} else {
this.value = 'X';
}
});
}
}
<input type="button" class="button" value="X" />
<input type="button" class="button" value="O" />
<input type="button" class="button" value="X" />
<input type="button" class="button" value="O" />
<input type="button" class="button" value="X" />
<input type="button" class="button" value="O" />
<input type="button" class="button" value="X" />
<input type="button" class="button" value="O" />
<input type="button" class="button" value="X" />
<input type="button" class="button" value="O" />
try this,
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
</head>
<body>
<div>
<input type="button" id="Button1" class="btn" onclick="Button1_Click(this)" />
<input type="button" id="Button2" class="btn" onclick="Button1_Click(this)" />
<input type="button" id="Button3" class="btn" onclick="Button1_Click(this)" />
</div>
<div>
<input type="button" id="Button4" class="btn" onclick="Button1_Click(this)" />
<input type="button" id="Button5" class="btn" onclick="Button1_Click(this)" />
<input type="button" id="Button6" class="btn" onclick="Button1_Click(this)" />
</div>
<div>
<input type="button" id="Button7" class="btn" onclick="Button1_Click(this)" />
<input type="button" id="Button8" class="btn" onclick="Button1_Click(this)" />
<input type="button" id="Button9" class="btn" onclick="Button1_Click(this)" />
</div>
<script>
var Caption = "X";
function Button1_Click(btn) {
$(btn).val(Caption);
if (Caption == "X") {
Caption = "O";
} else {
Caption = "X";
}
}
</script>
</body>
</html>
<input type="button" value=' ' onclick="Button_Click(this)" />
<input type="button" value=' ' onclick="Button_Click(this)" />
<input type="button" value=' ' onclick="Button_Click(this)" /> <br/>
<input type="button" value=' ' onclick="Button_Click(this)" />
<input type="button" value=' ' onclick="Button_Click(this)" />
<input type="button" value=' ' onclick="Button_Click(this)" /> <br/>
<input type="button" value=' ' onclick="Button_Click(this)" />
<input type="button" value=' ' onclick="Button_Click(this)" />
<input type="button" value=' ' onclick="Button_Click(this)" /> <br/>
<script>
var turn = 'x';
function Button_Click(btn) {
if (btn.value == ' ') {
btn.value = turn;
turn = (turn == 'x') ? 'o' : 'x';
}
}
</script>
You may try it here

shortcut for my functions

I have hundreds of counter buttons and i found out how to do simple one in javascript.
But doing this function over and over again really boring, is there any way more easier than this?
Here is my code.
Javascript:
var cnt = 0;
function add() {cnt++;set();}
function sub() {cnt--;set();}
function set() {myform.shesha.value = cnt;}
function price() {myform.shesha1.value = cnt*.500;};
var cnt1 = 0;
function add1() {cnt1++;set1();}
function sub1() {cnt1--;set1();}
function set1() {myform.shesha01.value = cnt1;}
function price1() {myform.shesha11.value = cnt1*.750;};
HTML:
0<input type="button" value="shesha" onclick="add()" />   
<input type="input" value="0" size="3" name="shesha" onblur="set();" />
<input type="button" value=" - " onclick="sub()" />
<input type="input" value="0" size="3" name="shesha1" onblur="price();" /></br>
1<input type="button" value="anab " onclick="add1()" />   
<input type="input" value="0" size="3" name="shesha01" onblur="set1();" />
<input type="button" value=" + " onclick="sub1()" />
<input type="input" value="0" size="3" name="shesha11" onblur="price1();" /></br>`
There are a number of ways to do this, Here is one:
cnt = []
Here, instead of having a bunch of variables, have an array and change the values in the array corresponding with your position.
. . .
onclick="add(1)"
. . .
function add(pos) {
cnt[pos]++
}
HTML:
<div class="calc">
<input type="button" class="add" value="add" />
<input type="input" class="addVal" />
<input type="button" class="sub" value="add" />
<input type="input" class="subVal" />
</div>
JS: (presumes jQuery)
$('.add').click(function (e) {
var add = $(this).parent().find('.addVal');
add.val(add.val()++);
});
$('.sub').click(function (e) {
var add = $(this).parent().find('.subVal');
add.val(add.val()--);
});

getting selected value of radio button in case of action

Hi here is the codes bellow, I've tried many things but I couldnt get value of selected radio button.As you can see I need to get that value for diffrent situations.
<div style="display: inline-block">
<div>
Log Out<span> Welcome </span>YS User 1 noName </div>
<br />
<br />
<br />
<br />
<input type="button" onclick="submitCreate();" value="New Survey" /><br />
<input type="button" onclick="submitEdit();" value="Edit Survey" /><br />
<input type="button" onclick="submitDelete();" value="Delete Survey" /><br />
<input type="button" onclick="submitPreview();" value="Preview Survey" />
</div>
<div style="display: inline-block">
<div>
<table class="MyTable"><thead><tr class="columnHead"><th scope="col"></th><th scope="col">CreatedBy</th><th scope="col">Created Date</th><th scope="col">Is Running</th></tr></thead><tbody><tr><td> <input name="selected" id="1"
type="radio" value="1" /></td><td>1</td><td>12/12/2011 3:43:57 PM</td><td>False</td></tr><tr class="altRow"><td> <input name="selected" id="2"
type="radio" value="2" /></td><td>1</td><td>12/13/2011 4:42:37 PM</td><td>False</td></tr><tr><td> <input name="selected" id="3"
type="radio" value="3" /></td><td>1</td><td>12/13/2011 6:27:38 PM</td><td>False</td></tr></tbody></table>
</div>
</div>
</body>
</html>
<script type="text/javascript">
// var value = $$('input[name=selected]:checked')[0].get('value');
// var selectFoo;
// $$('input[name=selected]').each(function (el) {
// if (el.checked == true) {
// selectFoo = el.value;
// }
// });
function getCheckedValue(radioObj) {
if (!radioObj)
return "";
var radioLength = radioObj.length;
if (radioLength == undefined)
if (radioObj.checked)
return radioObj.value;
else
return "";
for (var i = 0; i < radioLength; i++) {
if (radioObj[i].checked) {
return radioObj[i].value;
}
}
return "";
};
function submitCreate() {
var adress = "/User/CreateSurvey/";
document.location = adress;
};
function submitEdit() {
var adress = "/Den/Index/" + getCheckedValue('selected');
document.location = adress;
};
function submitDelete() {
var adress = "/User/DeleteSurvey/" + getCheckedValue('selected');
document.location = adress;
};
function submitPreview() {
var adress = "/User/PreviewSurvey/" + getCheckedValue('selected');
document.location = adress;
};
</script>
You can use document.getElementsByName(<button_name>) or document.getElementsByTagName("input") to get an array of input elements. Loop through those elements to check which is checked.
Here is an example of how to get the value of the checked button from a set of radio buttons with the name "selected":
<html>
<head>
<script type="text/javascript">
function get_radio_value() {
var inputs = document.getElementsByName("selected");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
return inputs[i].value;
}
}
}
function onSubmit() {
var id = get_radio_value();
alert("selected input is: " + id);
}
</script>
</head>
<body>
<form onsubmit="onSubmit();">
<input name="selected" value="1" type="radio"/>1<br/>
<input name="selected" value="2" type="radio"/>2<br/>
<input name="selected" value="3" type="radio"/>3<br/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
I choose let number of code for a required function. The one worked for me is given below from api.jquery.com. Hope this helps others.
HTML
<input type="radio" name="option" value="o1">option1</input>
<input type="radio" name="option" value="o2">option2</input>
JavaScript
var selectedOption = $("input:radio[name=option]:checked").val()
The variable selectedOption will contain the value of the selected radio button (i.e) o1 or o2

Categories