shortcut for my functions - javascript

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()--);
});

Related

Creating a store button to add/remove amount and display amount (Very Basic)

Seeking assistance with creating add and subtract buttons within a form to add and remove amount of a line of stock.
Similar to:
I'm new to html and very new to javascript.
function minus(){
var bCount = parseInt(document.calculateCart.count.value);
var count = bCount--;
document.calculateCart.count.value = count;
}
function minus(){
var bCount = parseInt(document.calculateCart.count.value);
var count = bCount++;
document.calculateCart.bCount.value = count;
}
<div class="productForm">
<form name="calculateCart" action="#">
<div class="+-Buttons">
Quantity <br>
<input type="button" value="-" onClick="minus()">
<input type="int" name="count" value=0>
<input type="button" value="+" onClick="add()">
</div>
</form>
</div>
If you want to chane your number using buttons and using text-input, you can change your code to that:
<div class="productForm">
<form name="calculateCart" action="https://titan.csit.rmit.edu.au/~e54061/wp/processing.php">
<div class="+-Buttons">
Quantity <br>
<input type="button" value="-" onClick="minus()">
<input type="number" name="count" value=0>
<input type="button" value="+" onClick="add()">
</div>
</form>
</div>
<script>
function minus(){
document.calculateCart.count.value = --document.calculateCart.count.value;
}
function add(){
document.calculateCart.count.value = ++document.calculateCart.count.value;
}
</script>
In HTML don't exist type of input - int, you need to use number or text.
If you want change value only using the buttons, you can make it like this:
<div class="productForm">
<form name="calculateCart" action="https://titan.csit.rmit.edu.au/~e54061/wp/processing.php">
<div class="+-Buttons">
Quantity <br>
<input type="button" value="-" onClick="minus()">
<span id="your-number">0</span>
<input type="button" value="+" onClick="add()">
</div>
</form>
</div>
<script>
var a = 0;
function minus(){
a -= 1;
document.getElementById('your-number').innerHTML = a;
}
function add(){
a += 1;
document.getElementById('your-number').innerHTML = a;
}
</script>
Your both functions are named 'minus'. One of them (the second one) should be 'add'.
you have s sort of a typo in your code: your function for adding valus is called minus(). So you have two functions with the same name
I believe you are getting the value of count in a wrong way. You should assign an id to the input and use getElementById
working code:
function minus(){
var bCount = document.getElementById('count').value;
bCount--;
document.getElementById('count').value = bCount;
document.getElementById('count');
}
function add(){
var bCount = document.getElementById('count').value;
bCount++;
document.getElementById('count').value = bCount;
document.getElementById('count');
}
<div class="productForm">
<form name="calculateCart" action="https://titan.csit.rmit.edu.au/~e54061/wp/processing.php">
<div class="+-Buttons">
Quantity <br>
<input type="button" value="-" onClick="minus()">
<input type="int" name="count" id="count" value=0>
<input type="button" value="+" onClick="add()">
</div>
</form>
</div>
You need to use document.getElementById in order to get old textbox value.
Please check below code:
function minus(){
var oldVal = parseInt(document.getElementById("myVal").value);
oldVal--;
document.getElementById("myVal").value = oldVal;
}
function add(){
var oldVal = parseInt(document.getElementById("myVal").value);
oldVal++;
document.getElementById("myVal").value = oldVal;
}
<div class="productForm">
<form name="calculateCart" action="https://titan.csit.rmit.edu.au/~e54061/wp/processing.php">
<div class="+-Buttons">
Quantity <br>
<input type="button" value="-" onClick="minus()">
<input type="text" id="myVal" name="count" value="0">
<input type="button" value="+" onClick="add()">
</div>
</form>
</div>
you have two function minus, one of them must be add
if you want use attributre name to select, you need to use something look like:
document.getElementsByName("count")[0].tagName

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>

How to get key (index) value of a textbox in array textboxes

I want a jQuery function or javascript that alert the index and the value of array textboxes : e.g.
<input type="text" name="textbox[]" value="1" onblur="javascriptfunction(this.value,this.index)" />
<input type="text" name="textbox[]" value="foo" onblur="javascriptfunction(this.value,this.index)" />
<input type="text" name="textbox[]" value="banana" onblur="javascriptfunction(this.value,this.index)" />
Whenever mouse moves for example from the first input I have this alerted (1,0) and second is (foo,1) and so on. I couldn't find the function that does that. Please help.
You can use jQuery index() and val() like
$('input').blur(function(){
alert($(this).val() + ',' + ($(this).index()-1));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<input type="text" name="textbox[]" value="1" />
<input type="text" name="textbox[]" value="foo" />
<input type="text" name="textbox[]" value="banana" />
Update
To target certain elements or have this in a named function, first, put identifiers on your elements such as a class my-class. Then, make a named function and pass it to the jQuery blur function
$('.my-class').blur( alertIndexAndVal );
function alertIndexAndVal(){
alert($(this).val() + ',' + ($(this).index()-1));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<input class="my-class" type="text" name="textbox[]" value="1" />
<input class="my-class" type="text" name="textbox[]" value="foo" />
<input class="my-class" type="text" name="textbox[]" value="banana" />
var textboxes = $('input[name="textbox[]"]');
textboxes.on('blur', function() {
var index = textboxes.index( this );
alert( this.value + ', ' + index );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" name="textbox[]" value="1" />
<input type="text" name="textbox[]" value="foo" />
<input type="text" name="textbox[]" value="banana" />
I figured I'd post a javascript solution which to be honest attempts to do something like the index function of jquery although i think jquery function might be better.
var getIndexValue = function (e) {
var children = e.parentElement.children;
for (var i = 0; i < children.length; i++) {
if (children[i] == e) {
alert("Index: " + (i+1) + ", Value: " + e.value);
}
}
}
<div>
<input type="text" name="textbox[]" value="one" onblur="getIndexValue(this)">
<input type="text" name="textbox[]" value="two" onblur="getIndexValue(this)">
<input type="text" name="textbox[]" value="three" onblur="getIndexValue(this)">
</div>
Index: (i+1)
Value: (e.value);

Java script hangman game issues

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]);

return all values of input fields within div

I need to form a string with the all values input fields within a div layer - using jquery
<div id="selection">
<input class="field" id="1" type="hidden" value="A"/>
<input class="field" id="2" type="hidden" value="B"/>
<input class="field" id="3" type="hidden" value="C"/>
<input class="field" id="4" type="hidden" value="D"/>
</div>
<input type="button" id="button" value="generate"/>
in this form:
id[1]=val[A]&id[2]=val[b]...so on
jquery:
$(function() {
$('#button').click(function() {
//function goes here...
});
});
If you use name instead of (or in addition to) id:
<input class="field" name="1" type="hidden" value="A"/>
<input class="field" name="2" type="hidden" value="B"/>
<input class="field" name="3" type="hidden" value="C"/>
<input class="field" name="4" type="hidden" value="D"/>
you can use serialize:
$('#button').click(function() {
alert($('#selection input').serialize());
});
which gives you
1=A&2=B&3=C&4=D
If you really want to have the id[x] structure, you can give the elements the names id[1], id[2] etc.
Edit: Oh, somehow I overlooked that you want val[x] as well. This would not be possible with serialize, only if you really put val[x] as value in the fields. But why do you need such an obfuscated structure?
Btw. you are missing type="button" at your button.
<script>
$(function() {
$('#button').click(function() {
var str = new Array();
var count = 0;
$('.field').each(
function()
{
str[count] = 'id['+$(this).attr('id')+']=val['+$(this).val()+']';
count++;
}
);
alert(str.join('&'))
});
});
</script>
<div id="selection">
<input class="field" id="1" type="hidden" value="A"/>
<input class="field" id="2" type="hidden" value="B"/>
<input class="field" id="3" type="hidden" value="C"/>
<input class="field" id="4" type="hidden" value="D"/>
</div>
<input id="button" value="generate" type="button"/>
Another solution that gives the exact specified output and handles missing attributes gracefully:
See it in action at jsFiddle:
$(function() {
$('#button').click(function() {
var ResStr = $('#selection input.field');
ResStr = ResStr.map (function () {
var jThis = $(this);
var ID = jThis.attr ("id");
if (!ID) ID = "null";
var VAL = jThis.val ()
if (!VAL) VAL = "null";
return 'id[' + ID + ']=val[' + VAL + ']';
} ).get () .join ('&');
alert (ResStr);
} );
} );
this returns all the html combined of all the inputs inside the div
var h = '';
var c = 0;
$('#selection input.field').each(function(){
h += '&id['+(++c)+']=val['+$(this).val()+']';
});
h = h.slice(1);
alert(h);

Categories