Read dynamically updated attribute value jquery - javascript

I have a situation over here. I'm writing this situation in a chronology.
Assume that there are an input[type=number] and a button.
When the button is clicked, it will change the attribute value (data-oldval="") to the current value of the input number.
The next time I click the button, it supposed to add the current value in the input with the number in the data-oldval attribute.
But the problem is, I can't read the newly updated attribute value.
To make the situation clearer, I included the code snippet below. I hope that anybody here can help me with this.
var response = $('.response');
$('body').on('click', '.btn', function() {
var btn = $(this),
t = btn.parent('.dummy'),
n = t.find('input[type=number]'),
val = n.val(),
oldval = n.data('oldval');
n.attr('data-oldval', val+oldval);
response.text(n.data('oldval'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dummy">
<input type="number" value="1" data-oldval="0">
<button class="btn" type="submit">Add</button>
</div>
<div class="response"></div>

Two issues; you need to retrieve the value using data('oldval'), not attr(), and you also need to convert val() to an integer so it can be added to the old value. Try this:
var response = $('.response');
$('body').on('click', '.btn', function() {
var btn = $(this),
t = btn.parent('.dummy'),
n = t.find('input[type=number]'),
val = parseInt(n.val(), 10),
oldval = n.data('oldval');
n.data('oldval', val + oldval);
response.text(n.data('oldval'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dummy">
<input type="number" value="1" data-oldval="0">
<button class="btn" type="submit">Add</button>
</div>
<div class="response"></div>

You need to parse the number entered into the input or it will be returned as a string and concatenated when setting val + oldval
console.log(typeof(val)) // string
val = parseInt(n.val());
You can also set the attribute by using the jQuery data method, the same way you're retrieving it to update the response element.
n.data('oldval', val + oldval);
See https://jsfiddle.net/aso1s0xz/

There is already a great answer but here is solution without data-oldval as I don't see why is it needed in this case.
$('body').on('click', '.btn', function() {
var response = parseInt($('.response').text());
if(isNaN(response))response=0;
var val = parseInt($('input').val());
var sum = val+response;
$('.response').text(sum);
})

To get dynamic Value Try JS, It will work perfectly
document.getElementById('element-id').getAttribute('data-oldval');

Use the Data() method in jQuery to set the value too:
var response = $('.response');
$('body').on('click', '.btn', function() {
var btn = $(this),
t = btn.parent('.dummy'),
n = t.find('input[type=number]'),
val = n.val(),
oldval = n.data('oldval');
n.data('oldval', parseInt(val)+parseInt(oldval));
response.text(n.data('oldval'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dummy">
<input type="number" value="1" data-oldval="0">
<button class="btn" type="submit">Add</button>
</div>
<div class="response"></div>

Related

The input number value on click and on change using control buttons

What event should I use to get an input number value where the value is changed typing or changed with button,
<p><input id="multiplier" type="number"></p>
change doesn't work when types only using the buttons
$('#multiplier').change(function(){
var value = $(this).val();
});
let multiplier = document.getElementById("multiplier");
multiplier.addEventListener("input",function(){
let value = this.value;
console.log(value)
})
<p><input id="multiplier" type="number"></p>
You can combine two event triggers like this:
$('#multiplier').on('keyup change', function(){
var value = $(this).val();
console.log(value)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><input id="multiplier" type="number"></p>

Javascript - prevent onclick event from being attached to all elements with same class

I'm working on a simple form that includes an input field where the user will fill in the required amount by clicking the incrementor/decrementor. The form is created based on data pulled dynamically from the database
Below is the problematic part: html and the jquery handling it:
The incrementor, decrementor and the input field:
-
<input type="text" id="purchase_quantity" class = "purchase_quantity" min="1" max="6" delta="0" style = "width: 32px;" value="1">
+
and the jquery handling the above:
jQuery(function ($) {
$('.addItem').on('click', function () {
var inputval = $(this).siblings('.purchase_quantity').val();
var num = +inputval;
num++;
if(num>6)num=6;
console.log(num);
$(".purchase_quantity").val(num);
return false;
});
$('.removeItem').on('click', function () {
var inputval = $(this).siblings('.purchase_quantity').val();
var num = +inputval;
num--;
if(num<1)num=1;
console.log(num);
$(".purchase_quantity").val(num);
return false;
});
});
Now, what's happening is: onclick of the incrementor/decrementor (+ and -) the value on the input field changes across all the fields in the page instead of the one clicked only. Have spent quite some time on this with no success and will appreciate some help
The line
$(".purchase_quantity").val(num);
says, literally, to change the value on all the fields. Earlier you used
$(this).siblings('.purchase_quantity').val()
to get the value, so why not also use
$(this).siblings('.purchase_quantity').val(num)
to set it?
That's because siblings will get you all items on the same level.
Get the siblings of each element in the set of matched elements,
optionally filtered by a selector.
Place them in separate div elements, and adjust your setter to actually only update the siblings inside that div.
jQuery(function ($) {
$('.addItem').on('click', function () {
var inputval = $(this).siblings('.purchase_quantity').val();
var num = +inputval;
num++;
if(num>6)num=6;
console.log(num);
$(this).siblings('.purchase_quantity').val(num);
return false;
});
$('.removeItem').on('click', function () {
var inputval = $(this).siblings('.purchase_quantity').val();
var num = +inputval;
num--;
if(num<1)num=1;
console.log(num);
$(this).siblings('.purchase_quantity').val(num);
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
-
<input type="text" id="purchase_quantity2" class = "purchase_quantity" min="1" max="6" delta="0" style = "width: 32px;" value="1">
+
</div>
<div>
-
<input type="text" id="purchase_quantity1" class = "purchase_quantity" min="1" max="6" delta="0" style = "width: 32px;" value="1">
+
</div>
you should change $(".purchase_quantity").val(num) to $("#purchase_quantity").val(num)

jquery, attribute selector, get current attribute value

I have an input:
<input type="text" size="5" maxlength="5" decimals="2">
where "decimals" could be a value from 0 to 4.
In the onblur event, whatever number the user types in will be changed to conform, thus:
decimals="2"
User enters: 123.456
Input is changed to: 123.46
That's trivial, no problem. My question is about the most efficient way to get the value of "decimals." Ordinarily, I'd write (jquery):
$('[decimals]').blur(function(){
val = $(this).attr('decimals');
// *** do stuff with val ***
});
...but it seems to me there ought to be a more efficient way to get the value of "decimals" since we've already selected the input based on that attribute. Is there, or is my code as written the only way?
You may take a look to attributes. This is a NamedNodeMap with some functions.
If you are referring to attributes and not to custom data attributes you can do:
$(function () {
$('[decimals]').blur(function(){
var val = this.attributes.decimals.value;
var val1 = this.attributes.getNamedItem('decimals').value;
var val2 = this.getAttribute('decimals');
console.log('this.attributes.decimals.value = ' + val);
console.log('this.attributes.getNamedItem("decimals").value = ' + val1);
console.log('this.getAttribute("decimals") = ' + val);
// *** do stuff with val ***
}).trigger('blur');
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<form>
<input type="text" size="5" maxlength="5" decimals="2">
</form>
Instead if you are referring to custom data attributes:
decimals="2"
User enters: 123.456
Input is changed to: 123.46
You can do:
$(function () {
$('[data-decimals]').on('blur', function(e){
var val = +$(this).data('decimals');
var txtNumber = +this.value;
this.value = txtNumber.toFixed(2);
});
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<form>
<input type="number" size="5" maxlength="5" data-decimals="2">
</form>

Jquery :How to store textbox value clientside and display?

The below code will update the display value enter by user in textbox when button clicked but in this code it will not preserve the previous value enter by user .
<h1>Type your comment below </h1>
<input id="txt_name" type="text" value="" />
<button id="Get">Submit</button>
<div id="textDiv"></div> -
<div id="dateDiv"></div>
jQuery(function(){
$("button").click(function() {
var value = $("#txt_name").val();
$("#textDiv").text(value);
$("#dateDiv").text(new Date().toString());
});
});
Now I want preserve all the value enter by user and when user will submit the button show both value previous as well as current.
How to achieve this ?
Can below code will help to preserve all the value
var $input = $('#inputId');
$input.data('persist', $input.val() );
If yes how to display all value previous,current etc. when user click on button ?
If i got this right, this is what you need?
<h1>Type your comment below </h1>
<input id="txt_name" type="text" value="" />
<button id="Get">Submit</button>
<script type="text/javascript">
jQuery(function(){
$("button").click(function() {
var value = $("#txt_name").val();
$("#section").prepend('<div class="textDiv">'+value+'</div>')
$("#section").prepend('<div class="dateDiv">'+new Date().toString()+'</div>')
$("#txt_name").val('');
});
});
</script>
<!-- each time you press submit, a new line will be pushed here -->
<div id="section">
</div>
If you want to display only the previous and current value the user submitted and use the data function then:
$("button").click(function() {
var input = $("#txt_name").val();
var previous = $("#textDiv").data('previous') || '';
$("#textDiv").text(previous+input);
$("#textDiv").data('previous',input);
$("#dateDiv").text(new Date().toString());
});
If you want all the values and you want to store them, then I would create an array. But you could always concatenate the string.
var arr = [];
$("button").click(function() {
var input = $("#txt_name").val();
arr.push(input);
var previous = $("#textDiv").data('previous') || '';
$("#textDiv").text(previous+input);
$("#textDiv").data('previous',previous+input);
$("#dateDiv").text(new Date().toString());
});
Without using .data() you can do this:
$("button").click(function() {
var input = $("#txt_name").val();
$("#textDiv").text($("#textDiv").text()+input);
$("#dateDiv").text(new Date().toString());
});
Instead of using two separate divs for message and date, you can use a single div.
<h1>Type your comment below </h1>
<input id="txt_name" type="text" value="" />
<button id="Get">Submit</button>
<div id="msgDiv"></div>
$(document).ready(function() {
var preservedTxt = '';
$("button").click(function() {
var input = $("#txt_name").val();
var date = new Date().toString();
var msg = input + ' - ' + date;
preservedTxt = preservedTxt + '<br>' + msg;
$('#msgDiv').html(preservedTxt);
});
});
Jsfiddle : https://jsfiddle.net/nikdtu/p2pcwj2f/
Storing values in array will help
jQuery(function(){
var name=[];
var time=[];
$("button").click(function() {
var value = $("#txt_name").val();
name.push(value);
$("#textDiv").text(name);
time.push(new Date().toString())
$("#dateDiv").text(time);
});
});

How do I get all the inputs in a element with jQuery?

I'm new to jQuery. I'm trying to get all inputs inside a div element. Here is what I have coded so far:
$(".pros_earnings_delete_annual_earning").click(function(e) {
e.preventDefault();
var target = $(e.target);
var parent = target.parent(".total-for-earnings");
var inputs = parent.children(":input");
console.log(inputs);
$.each(inputs, function(index, value) {
console.log(value);
});
});
When I click I get this:
[prevObject: v.fn.v.init[0], context: button.pros_earnings_delete_annual_earning, selector: ".parent(.total-for-earnings).children(:input)", constructor: function, init: function…]
The each method does not seem to output anything.
HTML:
<div class="total-for-earnings" style='background-color:#ccc;padding:10px;overflow:hidden;'>
<div style='width:160px;float:left;'><strong>Total for 2013:</strong>
<input type='hidden' name='pros_earnings_annual_year[]' value='2013'>
</div>
<input type='text' name='pros_earnings_annual_amount_mul[]' placeholder='0' value='10' size='8' style='width:80px;' />
<select name='pros_earnings_annual_amount_sup[]' style='width:110px;'>
<option value='Thousand'>Thousand</option>
<option value='Million' selected>Million</option>
<option value='Billion'>Billion</option>
</select><span>USD</span>
<div style="float:right;">
<button class="pros_earnings_save_annual_earning" style="margin-left:15px; width:auto; height:25px;">Save</button>
<button class="pros_earnings_delete_annual_earning" style="margin-left:15px; width:25px; height:25px;">-</button>
</div>
</div>
Change
var target = $(e.target);
var parent = target.parent(".total-for-earnings");
var inputs = parent.children(":input");
to,
var parent = $(this).closest(".total-for-earnings");
var inputs = parent.find(":input"); //Unlike children(), find() will go any depth to match.
Simply put:
var $inputs = $(':input',parent)
Will match all inputs in the context of the parent element.
You're console.log is outputting the jQuery object which represents each item in this collection, if you want the value of the input, just ask:
$inputs.each(function(){
console.log($(this).val());
})
Also, there was one other bug - target.parent(..) should have been target.parents(..) (plural)
Live example: http://jsfiddle.net/3aJuZ/
the problem is in this line
var parent = target.parent(".total-for-earnings");
change to
var parent = target.parents(".total-for-earnings");

Categories

Resources