Get previous value on input event - javascript

I have a value that I must change dynamically : the original value is 6 and I can customize it. If I put 7 on an inputbox, I now have 13. When I add another number, for example 71 my value change by 13 + 71. I want to substract the 13 with the previous value (7) to get my original one which is 6.
Here is my snippet :
$('.test :input').on('input', function(){
var ok = $('.ok');
ok.text(parseFloat(ok.text()) + parseFloat($(this).val()))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ok" style="background-color: white">
6
</div>
<div class="test">
<input type="text"/>
</div>
If you try to type 45 you should have 51 and you have 55.
I already tried with "focusing" as shown on some threads but I'm not leaving the input so it doesn't work. I don't know how to get my previous value.

It's not entirely clear what you are asking for. But I can see your selector is wrong. Also you want to make sure the document is loaded before you query elements in it.
I change the event listener to an onChange so that the addition doesn't happen for every keypress.
$(document).ready(function() {
$('.test input').on('change', function() {
var ok = $('.ok');
ok.text(parseFloat(ok.text()) + parseFloat($(this).val()))
})
});
Here's a plunker of it running.
Here's another guess at what you're asking, plunker. Which stores the initial value as an attribute.
$(document).ready(function() {
var ok = $('.ok');
$('.ok').text(ok.attr('data-initial-value'));
$('.test input').on('change', function() {
ok.text(parseFloat(ok.attr('data-initial-value')) + parseFloat($(this).val()))
})
});
<div class="ok" data-initial-value="6" style="background-color: white">
</div>

As #Doug suggested, you might use an attribute to store the initial value:
$('input').on('input', function() {
var ok = $('.ok');
ok.text(+(ok.attr('i')) + +($(this).val() || 0))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ok" i="6">6</div>
<input type="text" />

Thanks all for helping and hints, and sorry for messy explanations...
Here is what I did and it works : when I focus I put the old value in an attribute then when I add numbers I substract my actuel number with the stored number.
$('.test input').on('focus', function(){
$(this).attr('value', $(this).val());
});
$('.test input').on('change', function(){
var valActuelle = 0;
if($(this).attr('value') !== ''){
valActuelle = $(this).attr('value');
}
var ok = $('.ok');
ok.text(( parseFloat(ok.text()) - parseFloat(valActuelle)) + parseFloat($(this).val()) );
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ok" style="background-color: white">
6
</div>
<div class="test">
<input type="text"/>
</div>
It works only if you lose the focus but in my case I'm ALWAYS losing the focus

Related

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 multiple plus/minus script

I have multiple forms on a page and also multiple input boxes with plus/minus signs.
I'm having trouble to get those input boxes to work seperately. Probably because of some wrong/same id's or something like that or maybe a wrong setup of my code. The thing is I can't find my error in the code and I don't get any errors in my console.
What I have:
function quantity_change(way, id){
quantity = $('#product_amount_'+id).val();
if(way=='up'){
quantity++;
} else {
quantity--;
}
if(quantity<1){
quantity = 1;
}
if(quantity>10){
quantity = 10;
}
$('#product_amount_'+id).val(quantity);
}
And my html:
//row 1
<div class="amount"><input type="text" name="quantity" value="1" id="product_amount_1234"/></div>
<div class="change" data-id="1234">
+
-
</div>
//row 2
<div class="amount"><input type="text" name="quantity" value="1" id="product_amount_4321"/></div>
<div class="change" data-id="4321">
+
-
</div>
I thought something like this would do the trick but it doesn't :(
$(document).ready(function(){
$('.change a').click(function(){
var id = $(this).find('.change').data('id');
quantity_change(id)
});
});
Any help greatly appreciated!
You should use closest() method to get access to the parent div with class change, then you can read the data attribute id's value.
var id = $(this).closest('.change').data('id');
alert(id);
Since you are already binding the click event using unobutrusive javascript, you do not need the onclick code in your HTML markup.
Also your quantity_change method takes 2 parameters and using both, but you are passing only one. You may keep the value of way in HTML 5 data attributes on the anchor tag and read from that and pass that to your method.
<div class="change" data-id="1234">
+
-
</div>
So the corrected js code is
$(document).ready(function(){
$('.change a').click(function(e){
e.preventDefault();
var _this=$(this);
var id = _this.closest('.change').data('id');
var way= _this.data("way");
quantity_change(way,id)
});
});
Here is a working sample.

converting input type text to plain text

i'm working on a small html form with 1 textbox input, after the user enters any text and he presses a button on the end of the page i want the to change to a normal plain html text(so the whole page can be copy pasted into a word file including the written down text in the textbox).
as an example:
<input type="text" id="fileserver">
<button onclick="disable_all();">click!</button>
after the button is pressed i want the textbox to be converted to plain html text with no more textbox like this:
this is an example text after pressing the button!
click!
i have been searching around and have not found a working solution yet, hope someone can help me out
$('button').click(function(){
$('body *').replaceWith(function(){
return this.value || this.innerHTML;
});
});
http://jsfiddle.net/pYw9P/
This should do it I think.
function disable_all() {
var fs = $("#fileserver"), span = $( "<span>" + fs.val() + "</span>");
span.insertAfter(fs);
fs.remove(); // or fs.hide(); in case you want it later.
}
Try:
HTML:
<input type="text" id="fileserver">
<button id="but">click!</button>
JS:
$( "#but" ).click(function() {
var text=$( "#fileserver" ).val();
$( "body" ).html(text);
});
DEMO
This should be helpful to you -
There are several way to achieve your task :
Solutions 1 -
function disable_all()
{
$('#content').remove();
$('#fileserver, button').hide();
$('body').append("<div id='content'>" + $('#fileserver').val() + "</div>")
}
Working Fiddle
Solution 2 -
function disable_all()
{
$("body").html($("#fileserver").val());
}
Working Fiddle
you can do this hiding the textbox
<input type="text" id="fileserver">
<div id="result"></div>
<button id="btn" >click!</button>
and
$(document).ready(function(){
$("#result").hide();
$("#btn").click(function(){
$("#result").text($("#fileserver").val());
$("#fileserver").hide();
$("#result").show();
});
});
demo
The first "non-jQuery" answer...
your HTML:
<input type="text" id="fileserver">
<div style="display: none;" id="fileserver_text"></div>
<button id="btn">click!</button>
your Javascript:
document.getElementById('btn').onclick = disable_all;
function disable_all() {
var input = document.getElementById('fileserver');
var disp = document.getElementById('fileserver_text')
disp.innerHTML = input.value; // get the text from the input and set the div text
disp.style.display = 'block'; // show the div
input.style.display = 'none'; // hide the input
}
JSFiddle
If you are using jQUery, this will help you,
http://jsfiddle.net/DCak6/
function save(){
$('input,textarea').each(function(){
var $this = $(this);
$this.after('<span class="value">' + $this.val() + '</span>');
$this.remove();
})
}
You may be better off with taking the text from the text field, copying the value and putting it into another div
<div id="textToCopy"></div>
<input type="text" id="fileserver">
<button onclick="disable_all();">click!</button>
<script type="text/javascript">
function disable_all() {
$('#textToCopy').html($('#fileserver').val());
$('#fileserver').hide();
}
</script>

problem with adding input in jQuery

why after two click this code adding several input together?
$('.add_input').live('click', function () {
var scntDiv = '.'+$(this).closest('div.find_input').find('div').attr('class');
var i = $('.adding').size();
var input = $(scntDiv).clone().wrap("<div>").parent().html();
alert(scntDiv)
$(scntDiv + ' .add_input').remove();
$(input).appendTo(scntDiv);
$('<div></div>').appendTo('.add_in');
$(scntDiv + ' .add_in div a:first').remove('')
i++;
return false;
});
html: (i use of this html twice)
<div class="column find_input">
<div class="ai_service">
<div class="column">
<div class="mediumCell">
<input type="text" name="name" style="width: 160px;" placeholder="خدمات دیگر" title="نام پکیج تور خارجی">
</div>
</div>
<div class="column" style="margin: 5px 3px;">
<div class="mediumCell add_in">
</div>
</div>
</div>
</div>
Hmm if you're just trying to add an extra input field, your code seems a little overcomplicated for that... Try this?
$('a.add_input').live('click', function(e) {
e.preventDefault();
var $this = $(this);
var $wrapper = $this.closest('div.find_input');
var $input = $wrapper.find('input[name=name]').eq(0).clone();
$wrapper.children('div').eq(0).append($input);
};
I didn't replicate everything from your code, just the cloning/adding new input. If you posted simplified code and my example doesn't apply, I apologize. Also, I think you wanted to append your cloned input into div.ai_service?
In terms of why your original code adds multiple inputs, the cloning process you go through probably first clones one input, adds it, clones the whole thing again (2 inputs), adds 2, and so on. You can use $().eq(0) to limit your jQuery object to the first element it finds that matches your selector.
Try this
$('a.add_input').live('click', function (e) {
e.preventDefault();
var $column = $(this).closest("div.column");
var input = $column.prev("div.column").clone().wrap("<div />").parent().html();
$column.before($(input));
});

Get the values of input fields within child elements of a specific div

I have my form broken up into sections, and I'm trying to have a script check the number of fields empty in each section. Previously I had written an array with the id's of each section and had it cycle through that array, but i'd like to find a more universal solution that doesn't depend on predefined data.
at first I was trying .find() like so
function blankFields(section){
var totblank = 0;
var inputs = $('#' + section).find('input');
$.each(inputs, function(){
if(this.val() == '') { totblank++; );
}
when that didn't work i tried .serializeArray()
function blankFields(section){
var totblank = 0;
var inputs = $('#' + section + ' input').serializeArray();
$.each(inputs, function(i, field) {
if (field.value == '') { totblank++; }
});
and it gets followed up with
if(totblank > 0){
$("#"+section+"B").html(totblank+" Empty");
} else {
$("#"+section+"B").html("All full!");
}
}
section is the id of a div, the div has a table with form inputs.
This is my first time using these functions so I'm not really sure where I'm going wrong. Feels like I'm expecting the output to be something its not.
There are a few syntax errors in your code. Fixed:
function blankFields(section){
var totblank = 0;
var inputs = $('#' + section).find('input');
inputs.each(function(){
if($(this).val() == '') totblank++;
});
alert(totblank);
}
I think you can try to find all empty fields, and browse back the DOM to retrieve the parent section.
After, store results in associative array like "section" => count. If the section isn't in array, add an entry "newsection" => 1, else if section is in, increment section's count.
I think this part should give you an error
+= totblank
Or maybe I don't know JavaScript syntax well enough..
Anyway, try this instead
totblank++;
Overall, it's also good to make sure you're really dealing with Numbers. Common mistake is to get .val() and do some maths for example '1' + 1. Result is 11 and is something you probably didn't want
Wrote a little snippet that does the trick : http://jsfiddle.net/9jdmH/
$('#check').click(function() {
$('.section').each(function() {
checkSection($(this));
});
})
function checkSection(section) {
//assuming we're getting a jquery object. easily modifieable
section.find('input[type="text"]').each(function() {
if ($(this).val() == '') {
$('#log').prepend('<p>Found an empty input section ' + section.index() + '</p>');
}
})
}
This will work for a general markup type.
You'll need to make some changes depending on what kind of information you want. I haven't used IDs so I'm just using the .index() point out which ones are empty. As long as you get/make a jquery reference in the checkSection method you'll be fine.
My take on this:
http://jsfiddle.net/fqBrS/
function findNumberOfEmptyInputs(section) {
var inputs = $('#'+section+' input[type="text"]');
alert(inputs.filter(":empty").length);
}
findNumberOfEmptyInputs("section2");
The good thing is that you do not have to (explictly at least) use a loop.
Comments appreciated :)
code with sample. Should give pretty much the same output you have now.
<html>
<head>
<script type="text/javascript" src="Scripts/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
function checkBlank(f){
$(f).find(".section").each(function () {
var c = $(this).find("input[value='']").size()
$("#" + $(this).attr("id") + "B").text(c ? c + " Empty" : "All full");
})
return false
}
</script>
</head>
<body>
<form onsubmit="return checkBlank(this)">
<div class="section" id="section1">
<input type="text">
<input type="text">
</div>
<div class="section" id="section2">
<input type="text">
<input type="text">
</div>
<input type="submit" value="Click">
</form>
<div id="section1B"></div>
<div id="section2B"></div>
</body>
</html>

Categories