Increase counter value upon button click - javascript

I cannot seem to get the jQuery bit I need to work. I've never used jQuery before, but I'd like to have a button on my page that, when clicked, increments an initially 0 value by one. My question is similar to jQuery - Increase the value of a counter when a button is clicked and press button and value increases in text box but I can't make sense of what I'm doing wrong. Here's what I have:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script type="text/javascript">
$("#update").click(function()
{
$("#counter")++;
}
</script>
</head>
<body>
<input type="text" name="TextBox" id="TextBox" value="0" />
<input type="Button" id='AddButton' value="+" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script type="text/javascript">
$('#AddButton').on('click', function ()
{
var input = $('#TextBox');
input.val(parseInt(input.val()) + 1);
})
</script>
</body>
</html>
Any help is greatly appreciated. Please forgive any huge glaring mistakes, I have no idea how to do any of this yet. Thank you, and happy tidings! =)

It's clear you're new to jQuery, so a good read might be of help to you, I would recommand Head First jQuery.
As for the question, I rewrote your code, here's what it should be like :
<!DOCTYPE html>
<html>
<head>
<title> My first increment </title>
</head>
<body>
<input type="text" name="TextBox" id="TextBox" value="0" />
<input type="Button" id='AddButton' value="+" />
<script src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script>
$(document).ready(function(){
$('#AddButton').click( function() {
var counter = $('#TextBox').val();
counter++ ;
$('#TextBox').val(counter);
});
});
</script>
</body>
</html>
Here is a little test : test me
The idea is to increment a variable not an object, and you have some syntax mistakes as well, but try this code and we can discuss it further on comments.
Best of luck.

(This is merely a supplement to other answers)
You only need to load this once before all other js srcs:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
That's a really old jquery version. You can find the latest here.
Almost all jQuery code should be wrapped in
$(document).ready(function(){
});
Do it all of the time until you find a reason not to which is rare for pure jQuery.
Assuming $('#TextBox') can never be changed from the last counter, you might like:
$('#TextBox').val(0);
$('#AddButton').click( function() {
$('#TextBox').val(parseInt($('#TextBox').val()) + 1);
});
but if you want TextBox to be changed by the user then set back to the incrememented counter whenever AddButton's clicked, assuming counter should start at 0:
counter = 0;
$('#AddButton').click( function() {
counter++;
$('#TextBox').val(counter);
});

It should be:
var counter = 0;
$("#update").click(function()
{
counter++;
});
Demo for this here.
If counter is a variable you need to define it (var counter;) and you forgot also to close the click ")". Notice the extra ) in the end. What you were doing was increment a jQuery object (good idea to explain Ohgodwhy).
In case what you want is to put the value in another field (and now I am guessing a bit), like an input field, you can do this:
var val;
$("#update").click(function()
{
val = $('#counter').val();
val++;
$('#counter').prop('value',val )
});
Demo for this here.

This can be done using plain html and JS, Attaching the code below
<b>
<button id="btn" onclick="this.innerHTML=++this.value" value=0 >0</button>
</b>

Related

How to display real time characters count using jQuery?

Please check my code below. I want to display input characters number real time using jquery javascript. But problem is when i am doing it with "textarea" it works but when i do same with normal input type text its not work.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.11.1.js" type="text/javascript"></script>
</head>
<body>
<!-- Works -->
<!-- <textarea></textarea>
<span id="characters"><span>
<script type='text/javascript'>
$('textarea').keyup(updateCount);
$('textarea').keydown(updateCount);
function updateCount() {
var cs = $(this).val().length;
$('#characters').text(cs);
}
</script> -->
<!-- Not works -->
<input type="text" name="name">
<span id="characters"><span>
<script type='text/javascript'>
$('text').keyup(updateCount);
$('text').keydown(updateCount);
function updateCount() {
var cs = $(this).val().length;
$('#characters').text(cs);
}
</script>
</body>
</html>
Here is a working fiddle with combining your two events keyup and keydown into one line :-)
Your selector was wrong, text doesn't exist. So I call input[name="name"] instead to get the input by your name value:
$('input[name="name"]').on('keyup keydown', updateCount);
function updateCount() {
$('#characters').text($(this).val().length);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="name">
<span id="characters"><span>
$("input").keyup(function(){
$("#characters").text($(this).val().length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="name">
<span id="characters"><span>
With "textarea" version you are selecting "textarea" by $('textarea').keyup(updateCount) and
$('textarea').keydown(updateCount) nicely but with text input you are doing wrong to select input text.
I have fix it by placing a id called "foo" on input text. This should be working now.
<script src="http://code.jquery.com/jquery-1.11.1.js" type="text/javascript"></script>
<input type="text" id="foo" name="">
<span id="characters"><span>
<script type='text/javascript'>
$('#foo').keyup(updateCount);
$('#foo').keydown(updateCount);
function updateCount() {
var cs = $(this).val().length;
$('#characters').text(cs);
}
</script>
If you want to get an input with the type text you must use a selector like this
$('input[type="text"]').keyup(updateCount);
$('input[type="text"]').keydown(updateCount);
Here is a list of all jQuery selectors
You are not selecting the input field here.
Try the following
$('input').keyup(updateCount);
$('input').keydown(updateCount);
Here you go with a solution https://jsfiddle.net/mLb41vpo/
$('input[type="text"]').keyup(updateCount);
function updateCount() {
var cs = $(this).val().length;
$('#characters').text(cs);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" name="">
<span id="characters"><span>
Mistake was $('text').keyup(updateCount);, you can refer input textbox using 'text'.
It should be $('input').keyup(updateCount);
Everything is correct in your code, you just need to add ":" beore your type. This will make it identify, it is input type.
Example:
<script type='text/javascript'>
$(':text').keyup(updateCount);
$(':text').keydown(updateCount);
function updateCount() {
var cs = $(this).val().length;
$('#characters').text(cs);
}
</script>
I changed your script only. Just find the change, you will get it.

What's wrong with this code(JavaScript, buttons, HTML)?

<!DOCTYPE html>
<html>
<head>
<title>Question 2</title>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
</head>
<body>
<button onClick="myFunction()">Alphabetical order</button>
<button onClick="countFunction">Count</button>
<p id="i"></p>
<p id="ii"></p>
<script>
var products = ["Printer", "Tablet", "Router", "Keyboard"];
document.getElementById("i").innerHTML = products;
function myFunction() {
products.sort();
document.getElementById("i").innerHTML = products;
}
function countFunction() {
document.getElementById("i").innerHTML = products.length;
}
</script>
</body>
</html>
I think it's just a spelling or formatting error. If you can change the code as little as possible while still fixing it I would appreciate it a lot. If you need any more details please just ask. I would be happy to provide as much information as I can to help you help me.
This is for my son - he loves traffic lights!
Modify these lines:
<button onClick="myFunction();">Alphabetical order</button>
<button onClick="countFunction();">Count</button>
Set type of buttons to button. Default type is submit so on
clicking your function doesn't execute and page is submitted.
onClick should be onclick.
You are missing () after countFunction so add () at end of
countFunction
<button type="button" onclick="myFunction()">Alphabetical order</button>
<button type="button" onclick="countFunction()">Count</button>
You missed the brackets inside the second onclick attribute:
<!DOCTYPE html>
<html>
<head>
<title>Question 2</title>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
</head>
<body>
<button onClick="myFunction()">Alphabetical order</button>
<button onClick="countFunction()">Count</button>
<p id="i"></p>
<p id="ii"></p>
<script>
var products = ["Printer", "Tablet", "Router", "Keyboard"];
document.getElementById("i").innerHTML = products;
function myFunction() {
products.sort();
document.getElementById("i").innerHTML = products;
}
function countFunction() {
document.getElementById("i").innerHTML = products.length;
}
</script>
</body>
</html>
Now if you use the code, the first button will sort the array into alphabetical order and the second one will display the number of values, hope this helps :)
Modify this:
countFunction changed to countFunction()
See here for a working version: https://jsfiddle.net/BrechtDeMan/hzg4zefb/
1. Add brackets to the function call in the onclick= bit
I.e. <button onClick="countFunction()">Count</button> instead of <button onClick="countFunction">Count</button>.
2. Get the right HTML element
Your code now has
document.getElementById("i").innerHTML = products.length;
meaning the array is then replaced with the number '4'.
Presumably you want
document.getElementById("ii").innerHTML = products.length;
so that the output is
Printer,Tablet,Router,Keyboard
4
3. Best practices
This will change your code as little as possible, like you asked.
However, there are other improvements that might improve the style of your code.
Technically the code works like this (barring compatibility issues I'm not aware of - it works for me).

Javascript / jQuery to obtain the id of the textarea that I am typing in [duplicate]

This question already has answers here:
How do I find out which DOM element has the focus?
(20 answers)
Closed 9 years ago.
I have a simple form with three textareas each with a different id. I want to be able to press the button and return the id of the textarea where I am typing in. Instead when I press the button I receive the id of the button which is button1:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
function printTagName() {
$("#p1").html($(":focus").attr("id"));
}
</script>
</head>
<body>
<form>
<textarea id="textarea1"></textarea>
<textarea id="textarea2"></textarea>
<textarea id="textarea3"></textarea>
</form>
<p id="p1"></p>
<button type="button" id="button1" onclick="printTagName()">Press</button>
</body>
</html>
How can I fix this problem?
When the button is clicked focus shifts to the button. Save the element when a textarea receives focus, then print out the id of the textarea.
var focusElement = {};
$("textarea").focus(function(){
focusElement = this;
});
$("#button1").click(function(e){
e.preventDefault();
$("#p1").html(focusElement.id);
});
JS Fiddle: http://jsfiddle.net/ZYK7f/
This would work unless you need to know if whatever had focus no longer has it.
For example if the user clicks something that is NOT a textarea before hitting the button and you need to know this, the code will become quite complex
var hadFocus;
$(function() {
$("textarea").on("focus",function() { hadFocus=this.id; });
});
function printTagName() {
$("#p1").html(hadFocus || "No textarea had focus");
}
Save the TextArea that has focus last using:
var lastFocus;
$("TextArea").focus(function () {
lastFocus = this;
});
And this call the printTagName function
function printTagName() {
$("p").html(lastFocus.id);
});
Thank you very much Kevin Bowersox and everyone else for answering my question. Here is the complete code for Kevin's solution (I added a $(document).ready(function() {...}); to his solution):
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
var focusElement = {};
$("textarea").focus(function(){
focusElement = this;
});
$("#button1").click(function(e){
e.preventDefault();
$("#p1").html($(focusElement).attr("id"));
});
});
</script>
</head>
<body>
<form>
<textarea id="textarea1"></textarea>
<textarea id="textarea2"></textarea>
<textarea id="textarea3"></textarea>
</form>
<p id="p1"></p>
<button type="button" id="button1">Press</button>
</body>
</html>

jquery selectors, what is wrong with my code?

What i want to do is that when i click on the button "1" it should display the number "1" in the textbox above it.
what is wrong with my jquery code?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JQuery Tutorial</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<input id="textbox" type="text" />
<div>
<input id="1" type="button" value="1" />
<input id="2" type="button" value="2" />
<input id="3" type="button" value="3" />
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script type="text/javascript" src="js/ext.js"></script>
</body>
My jquery
$('#1').click(function)({
var txt = $('#textbox');
$('#1').html('txt');
});
Try this code
$('input[type="button"]').click(function() {
var txt = $(this).val();
$('#textbox').val(txt);
});
Will explain your problem with your jQuery code:
Line 1:
You registered with #1 button so this will be triggered on when button 1 is click, I made it generalised
Line 2:
You are getting value from textbox, whereas you are supposed to take value from button text.
Line 3:
You are assigning value in button, whereas you are supposed to assign to textbox and always use val() for input type of control and html() for other html container controls
The above were your errors explained.
Queries welcomed!
Fiddle demo
$(function(){
$('input[type="button"]').click(function(){
$('#textbox').val($(this).val());
});
});
You have to get the value using val() method. Also, you are passing variable txt as string to the html() function which is wrong. Try the below...
var txt = $('#textbox').val();
$('#input1').html(txt);
Try this
$('input[type="button"]').click(function() {
$('#textbox').val($(this).val());
});
You can try this one
$('div').on('click', 'input', function () {
$('#textbox').val(this.value);
});

Why does this give "undefined" error?

I am trying to get the user to put something into the text area and the output should be what he wrote repeapiting x amount of times, but I get an error "document.forme is undefined".
Can you please help me understand why it is undefined?
My code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>input home work</title>
<script type="text/javascript">
var help= document.forme.tryout.value;
for (x=1; x<=10;x++){
function numberCheak (){
document.write("this is"+" "+help++);
}
}
</script>
</head>
<body>
<form name="forme">
<input name="tryout" type="text" />
<input type="button" value="click me" onClick="numberCheak();"/>
</form>
</body>
</html>
Ok, you have a few problems. The first is that you are trying to access a form element that doesn't exist yet: the script is above the form element, so the form doesn't exist when you try to get it. If you move the script to the bottom of the page it will work better.
Second, the loop should be inside the function, not wrapped around the function.
Third, document.write has weird side effects and causes the document to be rewritten and will stop the script from continuing correctly.
Here's my revised script
function numberCheak() {
var help = document.forme.tryout.value;
for (var x = 1; x <= 10; x++) {
document.getElementById("output").innerHTML += help;
}
}
and the HTML form that goes with it
<form name="forme" id="forme">
<input name="tryout" type="text" />
<input type="button" value="click me" onclick="numberCheak();" />
<span id="output"></span>
</form>
You can see it in action on jsFiddle.
Forms are stored in collection and can be accessed like this:
var form = document.forms[i];
or
var form = document.forms[name];
In your case, i is 0 and name is forme.

Categories

Resources