Increment and decrement buttons - javascript

I am novice in jQuery but trying to learn something very basic. I am just trying to build up auto increment/decrement input fields like this:
<!DOCTYPE html>
<html>
<head>
<link href="stile_prenota.css" rel="stylesheet" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div class="riga numero">
<input type="text" name="numero" value="0" readonly="readonly">
<button class="bottone piu">+</button>
<button class="bottone meno">-</button>
</div>
<script>
$(document).ready(function(){
$('.bottone').on("click", function() {
var $button = $(this);
var vecchioVal = $button.parent().find("input").val();
var nuovoVal = parseFloat(vecchioVal);
if ($button.text() == "+") {
nuovoVal += 1;
} else {
if (vecchioVal > 0) {
nuovoVal -= 1;
} else {
nuovoVal = 0;
}
}
$button.parent().find("input").val(nuovoVal);
});
});
</script>
</body>
</html>
Why if i put the div inside a form it doesn't work?
EDIT Thank you very much

Buttons are submit type by default. So when you put it inside the form and click on button your form gets submitted. Changing the type will solve your problem like this
<!DOCTYPE html>
<html>
<head>
<link href="stile_prenota.css" rel="stylesheet" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<form>
<div class="riga numero">
<input type="text" name="numero" value="0" readonly="readonly">
<button type="button" class="bottone piu">+</button>
<button type="button" class="bottone meno">-</button>
</div>
</form>
<script>
$(document).ready(function() {
$('.bottone').on("click", function() {
var $button = $(this);
var vecchioVal = $button.parent().find("input").val();
var nuovoVal = parseFloat(vecchioVal);
if ($button.text() == "+") {
nuovoVal += 1;
} else {
if (vecchioVal > 0) {
nuovoVal -= 1;
} else {
nuovoVal = 0;
}
}
$button.parent().find("input").val(nuovoVal);
});
});
</script>
</body>
</html>

The form submites because buttons are `type="submit" by default and submit the form. So set the type to button so they do not submit
<button type="button" ..>

Buttons are by default submit here is a working version:
$(document).ready(function(){
$('.bottone').on("click", function() {
var $button = $(this);
var vecchioVal = $button.parent().find("input").val();
var nuovoVal = parseFloat(vecchioVal);
if ($button.text() == "+") {
nuovoVal += 1;
} else {
if (vecchioVal > 0) {
nuovoVal -= 1;
} else {
nuovoVal = 0;
}
}
$button.parent().find("input").val(nuovoVal);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="riga numero">
<input type="text" name="numero" value="0" readonly="readonly">
<button type="button" class="bottone piu">+</button>
<button type="button" class="bottone meno">-</button>
</div>
</form>

Related

Edit dynamically created li into input for a to do list jquery

I have a to do list and I can swap,delete and edit my li.
Right now I use the contenteditable prop for my edit function.
I would like to replace that with an input when I press the editButton and save the input in list if I press editButton again, but I don't know how to do it.
This is my html code:
var aux = 0;
$(document).ready(
function() {
$('#button').click(
function() {
var toAdd = $('input[name=listItem]').val();
var editTxt = $('<input type="text"/>');
if (toAdd == '')
alert("U must input something!");
else {
$("#list").append('<li><span>' + toAdd + " </span> <button class='edit'>" + "Edit</button>" +
" <button class='delete'>" + "Delete</button></li>");
$('input').val("");
}
});
$(document).on('click', '.delete', function() {
$(this).closest("li").fadeOut('slow', function() {
$(this).remove();
});
});
$(document).on('click', '.edit', function() {
if ($(this).closest("li").find("span").prop("contenteditable") == "true")
$(this).closest("li").find("span").prop("contenteditable", false).focus();
else
$(this).closest("li").find("span").prop("contenteditable", true).focus();
});
$('ol').sortable();
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<h>My list:</h>
<form name="toDoList">
<input type="text" name="listItem" />
</form>
<button id="button">Add</button>
<br/>
<ol id="list"></ol>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script src="v4.js" type="text/javascript"></script>
</body>
Just add hidden input along with span. and on Edit click check if span is visible then show input with span html and if hidden then replace input value to span and hide input field.
var aux = 0;
$(document).ready(
function() {
$('#button').click(
function() {
var toAdd = $('input[name=listItem]').val();
var editTxt = $('<input type="text"/>');
if (toAdd == '')
alert("U must input something!");
else {
$("#list").append('<li><span>' + toAdd + "</span> <input hidden></input><button class='edit'>" + "Edit</button>" +
" <button class='delete'>" + "Delete</button></li>");
$('input').val("");
}
});
$(document).on('click', '.delete', function() {
$(this).closest("li").fadeOut('slow', function() {
$(this).remove();
});
});
$(document).on('click', '.edit', function() {
/* if ($(this).closest("li").find("span").prop("contenteditable") == "true")
$(this).closest("li").find("span").prop("contenteditable", false).focus();
else
$(this).closest("li").find("span").prop("contenteditable", true).focus(); */
if ($(this).closest("li").find("span").is(':visible')) {
var val = $(this).closest("li").find("span").html();
$(this).closest("li").find("span").hide();
$(this).closest("li").find("input").show();
$(this).closest("li").find("input").val(val);
$(this).html("Save");
} else {
var val = $(this).closest("li").find("input").val();
$(this).closest("li").find("input").hide();
$(this).closest("li").find("span").show();
$(this).closest("li").find("span").html(val);
$(this).html("Edit");
}
});
$('ol').sortable();
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<h>My list:</h>
<form name="toDoList">
<input type="text" name="listItem" />
</form>
<button id="button">Add</button>
<br/>
<ol id="list"></ol>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script src="v4.js" type="text/javascript"></script>
</body>
Try this,
$(document).on('click', '.edit', function() {
var span = $(this).parent().children(':first-child'); // gets the first input (edit input)
if (span.children().length > 0) { // checks if it is edit mode or not
var spanText = span.children(':first-child').val(); // gets the inputs value
span.html(spanText); // set it to input
} else {
var spanText = span.text(); // get span input
var input = "<input value=" + spanText + ">"; // set it to input for edit
span.html(input); // paste inside span
}
});
Hope helps,

live update value if checkbox is checked or not

I am trying to update a textbox based on whether or not a checkbox is checked or not. Thanks to this post I got a text box working fine, but I can't get a checkbox to update the value. What am I missing?
<html>
<head>
<title>sum totals</title>
<script type="text/javascript">
function calculate(t){
var j = document.getElementById("output");
var rege = /^[0-9]*$/;
if ( rege.test(t.tons.value) ) {
var treesSaved = t.tons.value * 17;
j.value = treesSaved;
}
else
alert("Error in input");
}
$('input[name="selectedItems1"]').click(function(){
var j = document.getElementById("output");
if (this.checked) {
j.value=j.value+300
}else{
j.value=j.value-300
}
});
</script>
</head>
<body>
<form>
<input type="text" placeholder="Tons" id="tons" onkeyup="calculate(this.form)"/>
<br />
<input type="checkbox" name="selectedItems1" value="val1" />I have a car
<br/>
<input type="text" id="output" value="Output" />
</form>
</body>
</html>
Place the <script> tag after <form>
Reason:
When the html page loads, it'll be interpreted line by line. When it come to click(), jQuery will try to find the element input[name="selectedItems1"] which won't be loaded into the DOM at that time. So, jQuery won't attach the click() event handle to that checkbox. That's the reason why your code didn't work.
Try this :
<html>
<head>
<title>sum totals</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script><!-- load jquery -->
<script type="text/javascript">
function calculate(){
var j = document.getElementById("output");
var rege = /^[0-9]*$/;
var tons = $('#tons').val();
if ( rege.test(tons) ) {
val = parseInt(tons);
var treesSaved = val * 17;
if($('input[name="selectedItems1"]').is(":checked"))
{
treesSaved = treesSaved +300;
}
else
{
treesSaved = treesSaved -300;
}
if(isNaN(treesSaved))
j.value=0
else
j.value=treesSaved;
}
else
alert("Error in input");
}
$(function(){
$('input[name="selectedItems1"]').change(function(){
calculate();
});
});
</script>
</head>
<body>
<form>
<input type="text" placeholder="Tons" id="tons" onkeyup="calculate()"/>
<br />
<input type="checkbox" name="selectedItems1" value="val1" />I have a car
<br/>
<input type="text" id="output" value="Output" />
</form>
</body>
</html>

How to increase and decrease a text value with two buttons

I'm trying to increase a text value using two buttons, one on each side of the text, which either increase the value by 10 or decrease it by 10, and the value can't go under 10km or over 90km.
Here is the app screen so you can see what I mean:
Update: I've now been given code to work with but it doesn't have the "km" value after the number so it goes 10,20,30 instead of 10km, 20km, 30km. Does anyone know how to adjust this code to do what I want?
<script language='javascript' type='text/javascript'>
$(document).ready(function(){
$("#increment").click(function(){
if($('#number').val() !="90"){
var $n = $("#number");
$n.val(Number($n.val())+10);
}
});
$("#decrement").click(function(){
if($('#number').val() !="10"){
var $n = $("#number");
$n.val(Number($n.val())-10);
}
});
});
</script>
</head>
<style>
.Radius{
font-size:14px;
font-family:"gillsans";
color: #4361AD;
text-align: center;
}
</style>
<body>
<div id="Maincontainer">
<input type="text" value="10" id="number" class="Radius" style="background-color:transparent; border:0px solid white; width:110px; margin-left:15px;"/>
<input type="button" id="increment" value="Increment"/>
<input type="button" id="decrement" value="decrement"/>
</div>
</body>
https://jsfiddle.net/deepanv29/4b7adopb/
<!DOCTYPE>
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
</head>
<body>
<div>
<body>
<input type="text" value="10Km" id="number"/>
<input type="hidden" value="10" id="number1"/>
<input type="button" id="increment" value="Increment"/>
<input type="button" id="decrement" value="decrement"/>
</body>
</div>
<script language='javascript' type='text/javascript'>
$(document).ready(function(){
$("#increment").click(function(){
if($('#number1').val() !="90"){
var $n = $("#number1");
$n.val(Number($n.val())+10);
var value = $n.val();
$("#number").val(value +'Km');
}
});
$("#decrement").click(function(){
if($('#number1').val() !="10"){
var $n = $("#number1");
$n.val(Number($n.val())-10);
var value = $n.val();
$("#number").val(value +'Km');
}
});
});
</script>
</body>
</html>
updates Js fiddle demo for the above code
you just need to increment and decrement the value at button click.
int value = 10;
protected void BtnIncre_Click(Object sender, EventArgs e)
{
if (value < 90)
{
value += 10;
Session["Value"] = value;
}
}
protected void BtnDecre_Click(Object sender, EventArgs e)
{
if (value > 10)
{
value -= 10;
Session["Value"] = value;
}
}
<!DOCTYPE>
<html>
<head>
</head>
<body>
<input type="button" id="dec" value="DEC" onclick="dec();">
<input type="text" id="Number_value" value="0" readonly>
<input type="button" id="inc" value="INC" onclick="inc();">
<script language='javascript' type='text/javascript'>
function inc()
{
var val = parseInt(document.getElementById('Number_value').value);
val+=10;
if(val>90) val = 90;
document.getElementById('Number_value').value = val;
}
function dec()
{
var val = parseInt(document.getElementById('Number_value').value);
val-=10;
if(va<10) val = 10;
document.getElementById('Number_value').value = val;
}
</script>
</body>
</html>

Form always submits even when not validated

I want to build a form that only submits after validation (using ajax, for both the validation and the submit).
From what I have now, it always submits. It shows the messages that the fields are not correct, but it still inserts empty fields into the database.
Any idea on how to insert it after validation?
Thanks
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<meta charset="utf-8">
<title>Form</title>
</head>
<script type="text/javascript" src="js/validate.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<body>
<div id="wrap">
<table>
<td>
<form name="form">
<tr>
<p class="names">Voornaam:</p> <p><input type="text" name="voornaam" id="voornaam"></p>
</tr>
<tr>
<p class="names">Achternaam:</p> <p><input type="text" name="achternaam" id="achternaam"></p>
</tr>
<tr>
<p class="names">Telefoonnummer:</p> <p><input type="text" name="telefoonnummer" id="telefoonnummer"></p>
</tr>
<tr>
<p class="names">Emailadres:</p> <p><input type="text" name="email" id="email"></p>
</tr>
<tr>
<input class="knop" type="submit" name="insert" value="Opsturen" id="insert">
</tr>
</form>
</td>
</table>
<br>
<div id="berichten">
</div>
<script>
var validator = new FormValidator('form', [{
name: 'voornaam',
display: 'Voornaam',
rules: 'required'
}, {
name: 'achternaam',
display: 'achternaam',
rules: 'required'
},{
name: 'telefoonnummer',
display: 'telefoon',
rules: 'required|numeric'
},{
name: 'email',
display: 'email',
rules: 'required|valid_email'
}], function(errors, event) {
var berichten = document.getElementById('berichten');
berichten.innerHTML = '';
if (errors.length > 0) {
for (var i = 0, l = errors.length; i < l; i++) {
berichten.innerHTML += errors[i].message + '<br>';
}
}
});
</script>
<script type="text/javascript">
$(function(){
$('#insert').click(function(){
var voornaam = $('#voornaam').val();
var achternaam = $('#achternaam').val();
var telefoonnummer = $('#telefoonnummer').val();
var email = $('#email').val();
$.post('action.php',{action: "submit", voornaam:voornaam, achternaam:achternaam, telefoonnummer:telefoonnummer, email:email},function(res){
$('#result').html(res);
});
document.getElementById('berichten').innerHTML = 'Verstuurd!';
});
});
</script>
</div>
</body>
</html>
Its because, your submit button works even if we have javascript validations has errors.
You should add a return false in the function to stop it submitting the form.
Also, error count should also be considered.
So, the updated code:
<script type="text/javascript">
$(function(){
$('#insert').click(function(){
var voornaam = $('#voornaam').val();
var achternaam = $('#achternaam').val();
var telefoonnummer = $('#telefoonnummer').val();
var email = $('#email').val();
if (errors.length > 0) {
for (var i = 0, l = errors.length; i < l; i++) {
berichten.innerHTML += errors[i].message + '<br>';
return false;
}
} $.post('action.php',{action: "submit", voornaam:voornaam, achternaam:achternaam, telefoonnummer:telefoonnummer, email:email},function(res){
$('#result').html(res);
});
document.getElementById('berichten').innerHTML = 'Verstuurd!';
return false;
});
});
</script>
instead of using type="submit" use type="button" i think this will solve your problem.....
you should use return false; statement
if (errors.length > 0) {
for (var i = 0, l = errors.length; i < l; i++) {
berichten.innerHTML += errors[i].message + '<br>';
return false;
}
http://api.jquery.com/event.preventdefault/
add:
event.preventDefault();
Within your click function.
$(function(){
$('#insert').click(function(e){
e.preventDefault();

writing to the iframe causes the browser to reload with different url

My markup is written as follows. Pay more attention to the click handler of the uploadBtn button.
<!DOCTYPE html>
<html>
<head>
<title>Cleansing Workbench</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="Content/bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
</head>
<body>
<div class="container">
<h1>Cleansing Workbench</h1>
<h3>Upload File</h3>
<form class="form-inline well">
<label class="span3">Enter the file to upload</label><button id="uploadBtn" class="btn btn-default">...</button><label id="filename"></label>
<br />
<label class="span3">Enter Delimiter</label>
<select name="delimiter" id="delimiter">
<option value="comma">Comma</option>
<option value="tab">Tab</option>
<option value="pipe">Pipe</option>
<option value="other">Other</option>
</select>
<label>Specify Delimiter</label>
<input type="text" name="otherDelimiter" id="txtdelimiter" value="Comma (,)" />
<br />
<br />
<div class="text-right">
<input type="submit" class="btn btn-primary" value="Upload" />
</div>
</form>
<iframe name="upload" id="upload" src="about:blank" style="display:none"></iframe>
</div>
<script src="Scripts/jquery-1.7.1.min.js"></script>
<script src="Scripts/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript">
(function ($) {
$.fn.toggleDisabled = function () {
return this.each(function () {
var $this = $(this);
if ($this.attr('disabled')) $this.removeAttr('disabled');
else $this.attr('disabled', 'disabled');
});
};
})(jQuery);
$(function () {
var arrDelimiterEnums = ['Comma (,)',
'Tab Separated ( \\t )',
'Pipe ( | )'];
$txt = $('#txtdelimiter').toggleDisabled();
$('#delimiter').change(function () {
var obj = this;
var indx = obj.selectedIndex;
var val = obj.options[indx].value;
if (val == 'other') {
$txt.val('').toggleDisabled();
}
else {
if (!$txt.attr('disabled'))
$txt.toggleDisabled();
$txt.val(arrDelimiterEnums[indx]);
}
});
$('#upload').load(function () {
});
$('#uploadBtn').click(function () {
var ifr = document.getElementById('upload');
var doc = ifr.contentWindow.document;
if (doc.getElementById('uploader') == null) {
var frm = document.createElement('form');
frm.action = "fileupload.ashx";
frm.method = "post";
frm.id = 'uploader';
var inp = document.createElement('input');
inp.type = "file";
inp.name = 'uploadFile';
inp.id = 'uploadbtn';
var i = $(inp).click(function () {
console.log('hello');
console.log(this.value);
});
frm.appendChild(inp);
doc.body.appendChild(frm);
//i.trigger('click', null);
}
else {
var btn = doc.getElementById('uploadbtn');
$(btn).trigger('click', null);
}
});
});
</script>
</body>
</html>
As soon as the following line executes, the url in my browser gets appended with ?delimiter=comma.
doc.body.appendChild(frm);
I expected this would not reload. So what do I do to not make it reload?
Take your inputs out of the form <form class="form-inline well"> & just manipulate them with jQuery or vanilla javascript.
When buttons are in a form they automatically "submit"/refresh the page.

Categories

Resources