How to increment a JavaScript variable using a button press event - javascript

Can I create a javascript variable and increment that variable when I press a button (not submit the form).
Thanks!

Yes:
<script type="text/javascript">
var counter = 0;
</script>
and
<button onclick="counter++">Increment</button>

The purist way to do this would be to add event handlers to the button, instead of mixing behavior with the content (LSM, Layered Semantic Markup)
<input type="button" value="Increment" id="increment"/>
<script type="text/javascript">
var count = 0;
// JQuery way
$('#increment').click(function (e) {
e.preventDefault();
count++;
});
// YUI way
YAHOO.util.Event.on('increment', 'click', function (e) {
YAHOO.util.Event.preventDefault(e);
count++;
});
// Simple way
document.getElementById('increment').onclick = function (e) {
count++;
if (e.preventDefault) {
e.preventDefault();
}
e.returnValue = false;
};
</script>

<script type="text/javascript">
var i=0;
function increase()
{
i++;
return false;
}</script><input type="button" onclick="increase();">

I needed to see the results of this script and was able to do so by incorporating the below:
var i=0;
function increase()
{
i++;
document.getElementById('boldstuff').innerHTML= +i;
}
<p>var = <b id="boldstuff">0</b></p>
<input type="button" onclick="increase();">
add the "script" tag above all and a closing script tag below the function end curly brace. Returning false caused firefox to hang when I tried it. All other solutions didn't show the result of the increment, in my experience.

Use type = "button" instead of "submit", then add an onClick handler for it.
For example:
<input type="button" value="Increment" onClick="myVar++;" />

Yes.
<head>
<script type='javascript'>
var x = 0;
</script>
</head>
<body>
<input type='button' onclick='x++;'/>
</body>
[Psuedo code, god I hope this is right.]

yes, supposing your variable is in the global namespace:
<button onclick="myVar += 1;alert('myVar now equals ' + myVar)">Increment!!</button>

I believe you need something similar to the following:
<script type="text/javascript">
var count;
function increment(){
count++;
}
</script>
...
and
<input type="button" onClick="increment()" value="Increment"/>
or
<input type="button" onClick="count++" value="Increment"/>

Had a similar problem. Needed to append as many text inputs as the user wanted, to a form. The functionality of it using jQuery was the answer to the question:
<div id='inputdiv'>
<button id='mybutton'>add an input</button>
</div>
<script>
var thecounter=0; //declare and initialize the counter outside of the function
$('#mybutton').on('click', function(){
thecounter++;
$('#inputdiv').append('<input id="input'+thecounter+'" type="text/>);
});
</script>
Adding the count to each new input id resulted in unique ids which lets you get all the values using the jQuery serialize() function.

Related

HTML Form to display output by using a button

Please let me know what I am doing wrong, I have tried to debug but it hasn't been working. I want to enter information into a text field and then display that after clicking a button.
<!DOCTYPE html>
<html>
<head>
<script type = 'text/javascript'>
var name; //name
console.log("hi from script");
function getName() { //get name
return document.getElementById("name").value;
}
function display() { //get the name and display
name = getName();
alert(name);
}
document.getElementById("Submit").onclick = display();
</script>
</head>
<body>
<form id='form'method = 'post'>
<p> Name: <input type="text" id="name"/></p>
<p><input id ="Submit" type = "button" value = 'Submit' /></p>
</form>
</body>
</html>
The problem is that you are making use of a <form> POST. The default behaviour is to navigate away from the page (or refresh if you're posting to the same page), and doing so would mean that the script cannot execute any further functionality. To prevent this, you need to use .preventDefault() to prevent the default behaviour of the form submission.
In order to do this, I've changed your .onclick = display() functionality to add an event listener on the click, which prevents the default behaviour, and then calls display():
.addEventListener("click", function(event) {
event.preventDefault();
display();
});
Adding this provides the following working example:
var name; //name
console.log("hi from script");
function getName() { //get name
return document.getElementById("name").value;
}
function display() { //get the name and display
name = getName();
alert(name);
}
document.getElementById("Submit").addEventListener("click", function(event) {
event.preventDefault();
display();
});
<form id='form' method='post'>
<p> Name: <input type="text" id="name" /></p>
<p><input id="Submit" type="button" value='Submit' /></p>
</form>
Hope this helps! :)
Create an empty p tag and give it an id, then call the id and .html to input the text into the field. Like so
so get your html ready
<p><span id="youridhere"><p>
then add this to your function instead of using alert.
$('#youridhere').html(name);
that should do it
here's a jsfiddle of what I think you are looking for
https://jsfiddle.net/uzdt715L/
$('button').click(function(){
var thing = $('#whatever').val();
$('#final').html(thing);
});
You need to update your click handler syntax. The following should work for you,
document.getElementById("Submit").addEventListener("click", display);
See this related question - addEventListener vs onclick
Your code is not really wrong.
But because the JavaScript is placed before htm code, so the onlick event is not registered.
You must replace
document.getElementById("Submit").onclick = display();
With
document.onload = function() {
document.getElementById("Submit").onclick = display();
}
Sorry for the formatting as I'm answering via mobile.

how do i check values individually of appended inputs

how do i check values individually of appended inputs
example i want to get the value of only the second appended input thanks
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
$(".addinput").click(function(){
$('.samplediv').append('<input type="text" class="sampleinput">');
});
</script>
<div class="samplediv">
<input type="text" class="sampleinput">
</div>
<button class="addinput"></button>
</body>
</html>
Add a unique class for each input and use that class to get the value. For the second one, use something like:
$("input.num-2).val();
var num = 1;
$(".addinput").click(function(){
$('.samplediv').append('<input type="text" class="sampleinput num-' + num + '">');
num++;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="samplediv">
</div>
<button class="addinput">Add input</button>
This is just one way (not the best way) to accomplish what you are asking for.
Here is a working example: https://jsfiddle.net/zzukok0j/
$(".addinput").click(function(){
$('.samplediv').append('<input type="text" class="sampleinput">');
var counter = 0;
$('.sampleinput').each(function(poop) {
if(counter===1) {
alert( $(this).val() );
} else {
counter++;
}
});
});
use jquery each function to select each field and do whatever you want...
$('input[type="text"]').each(function(){
//do something
});
The following piece of code will allow you to get the value of each of the appended inputs.
var $inputs = $('.samplediv input');
$inputs.each(function(index) {
value = this.val();
// now you can use value for whatever you need
console.log(value);
});
I hope this helps. Happy coding!

jQuery method to add a TextBox

UPDATED
I am new to jQuery but have been programming for about two years in C#. I wanted to create a jQuery method that would be used several times to add Textboxes. I thought that I create a jQuery function with parameters which I would set from the buttons when they get clicked. Here is my jQuery code, this wont necessarily work as I am a newbie but will definitely give a workflow of what I intended to achieve
$(document).ready(function () {
function add(someClass) {
var count = $("."+someClass).length;
if (count <= 20) {
var newTextBox = $(document.createElement('text'));
newTextBox.appendTo("."+ someClass+":last");
//$('.approvers:last').append($("<input type='text' value='' />"));
}
}
});
This is how I intend to call the function from a buttons onclick.
<input type="button" value="+" id="someId" class="someCssClass" onclick="addText('approvers')" />
I am doing this to avoid writing the same code to insert textboxes having different classes. Is this how it can be done? All I want is to add a new TextBox at the same time specifying its class from jquery.
Your code is a little off, try this:
<input type="button" value="+" id="someId" class="addButton" data-target-class="someClass"/>
<div class="someClass">
</div>
And the javascript:
$(document).ready(function(){
// Define a click handler for any input with the class addButton
$('input.addButton').click(function(){
// Extract the class that this input button is targeting
var target_class = $(this).attr('data-target-class');
// Add a textarea to that target
$("."+target_class).append("<textarea></textarea>");
});
});
Here is an example:
http://jsfiddle.net/1sfz4sda/
I tested below code and it works, do not put your function inside document.ready
DEMO : http://liveweave.com/RkHq5o
Here is the javascript
function addText(cssClass) {
var count = $("."+cssClass).length;
if (count <= 20) {
var newTextBox = $(document.createElement('textarea'));
newTextBox.appendTo("."+cssClass);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="button" value="+" id="someId" class="someCssClass" onclick="addText('approvers')" />
<div class="approvers"></div>

How to clear a text field?

I want to place a cross button next to a text field, which, on clicking it, clears the value entered by the user. In other words, it empties the field. Please help..
And I also want to focus the field, but after some 2 or 3 seconds..
Like this:
$('#myButton').click( function () {
$('#myField').val('');
});
Or without jQuery
document.getElementById('myButton').onclick = function () {
document.getElementById('myField').value = '';
});
Try this,
$('#button').click(function(){
$('#inputBox').val('');
});
Have you tried anything at all? But this should do (edit after misread, see below):
$('#your_button').click(function() { $('#your_textbox').val(''); });
In Javascript:
document.getElementById('textField1').value = "";
Well, learn to break your tasks into smaller one and everything will become much easier. Here, for example, you have 2 tasks:
1) Place a "X" button near input. This is achieved by CSS and HTML. You HTML might look like:
Then you should align your image with you input
2) Actual erasing. In jQuery:
$("#x_button").click( function() {
$("#input_id").val( "" );
});
But this is real basics of web development, so you should really consider to read some kind of book on it.
You can do it with html5 value.
<input type="text" placeholder="Your text here">
Assuming your text field looks like this one :
<input type="text" id="myText"></input>
and your button looks like this one :
<input type="button" id="myButton"></input>
You just have to do this in javascript :
<script type="text/javascript">
var myButton = document.getElementById('myButton');
myButton.addEventListener("click", function () {
document.getElementById('myText').value = '';
}, false);
</script>
If you're using jQuery it's even easier :
<script type="text/javascript">
$('#myButton').click(function() {
$('#myText').val('');
});
</script>
here is a sample:
Html:
<input type="text" id="txtText" value="test value" />
<input type="button" id="btnClear" value="Clear" />
javascript:
$(document).ready(function () {
$("#btnClear").click(ClearText);
});
function ClearText() {
$("#txtText").val("");
}

Copy value from one textbox to another using submit button

I know this can be accomplished by Javascript, and I am learning so please tell me, when I click an update button I want the text from a textbox to be copied into another one.
Assuming you have this:
<textarea id="source"></textarea>
...
<textarea id="target"></textarea>
...
<button type="button" onclick="update();">Update</button>
Then your JS function can be:
function update() {
document.getElementById('target').value = document.getElementById('source').value;
}
jQuery solution - check it out (jQuery that is)
$('#button').click(function(e) {
e.preventDefault();
$('#totextarea').val($('#fromtextarea').val());
...then submit the form if you wish to or whatever...
$('#theform').submit();
});
Try the following
<script>
function onSubmitClick() {
var box1 = document.getElementById('box1');
var box2 = document.getElementById('box2');
box2.value = box1.value;
}
</script>
<textarea id='box1'></textarea>
<textarea id='box2'></textarea>
<button onclick='onSubmitClick(); return false'>Click Me</button>
JSFiddle Demo
http://jsfiddle.net/Wr8L8/
<script>
function sync()
{
// Take first and second value by element ID
var n1 = document.getElementById('n1');
var n2 = document.getElementById('n2');
// Assign the value of the 1st to the 2nd text box
n2.value = n1.value;
}
</script>
<input type="text" name="n1" id="n1" />
<input type="text" name="n2" id="n2"/>
<!-- you put a function sync to be executed on click on the button -->
<button onclick="sync()">Synchronize</button>

Categories