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>
Related
I am trying to do 2 things:
Balance out 3 inputs into 100
$input1 = $('#input1 ');
$input2 = $('#input2 ');
$input3 = $('#input3 ');
$input1.on('input', function () {
$input2 .val(100 - this.value);
$input3 .val(100 - this.value - $input2.value)
});
$input2 is displayed well yet doesn't output into $input3 (NaN).
I also tried to create a callback for input3 and that didn't work out well either.
How to block the input from showing numbers out of the range of 0-100.
Here's a JSF
Try to get rid of jQuery because you are confusing both the DOM API and jQuery API. The DOM is what you should learn, not jQuery.
let $input1 = document.querySelector('#input1');
let $input2 = document.querySelector('#input2');
let $input3 = document.querySelector('#input3');
$input1.addEventListener('input', function () {
$input2.value = (100 - this.value)/2;
$input3.value = 100 - this.value - $input2.value;
});
<form>
<input id='input1'/><br/>
<input id='input2'/><br/>
<input id='input3'/>
</form>
$input2 is a jQuery wrapped element. You cannot call value on it directly. You need to get the value using val() instead. Since value will return undefined, the final output is NaN.
Change this:
$input3.val(100 - this.value - $input2.value)
to this:
$input3.val(100 - this.value - $input2.val())
Alternatively, you can get the native element out of the jQuery wrapper and call value on it. The following should work seamlessly as well:
$input3.val(100 - this.value - $input2[0].value)
For #2, you may want to look into input[type=number] and restrict the range using min and max attributes.
As in other answer by #31piy you need to use $input2.val() or $input2[0].value. And balancing of values in field input2 and input3 can be done as below.
$input1 = $('#input1 ');
$input2 = $('#input2 ');
$input3 = $('#input3 ');
$input1.on('input', function() {
$input2.val(parseInt((100 - this.value) / 2));
$input3.val(100 - this.value - $input2.val())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input id="input1" type=number min="0" max="100">
<input id="input2" type=number min="0" max="100">
<input id="input3" type=number min="0" max="100">
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)
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>
I'm playing around with the todos.js backbone.js demo.
In the demo, they have one input text box where they take data from in the initialize function like this:
<input id="new-todo" type="text" placeholder="Todo item...">
initialize: function () {
this.input = this.$("#new-todo");
My question is, would it be possible to take the data from 3 input textboxes instead of just one?
I could try this, but this doesn't seem to scale very well:
<input id="new-todo1" type="text" placeholder="Todo item...">
<input id="new-todo2" type="text" placeholder="Todo item...">
<input id="new-todo3" type="text" placeholder="Todo item...">
initialize: function () {
this.input = this.$("#new-todo1");
this.input =+ this.$("#new-todo2");
this.input =+ this.$("#new-todo3");
Is there a better way?
Thanks
I assume you want to take the values from multiple inputs, and put them as title in a todo item. I suggest storing references to inputs in initialize with:
initialize: function () {
this.input = this.$("#new-todo");
...
}
And the createOnEntermethod should change into this:
createOnEnter: function(e) {
//concatenate the values from all inputs
var val = "";
this.input.each(function() {
val += ($(this).val());
});
if (e.keyCode != 13) return;
if (!val) return;
Todos.create({title: val});
//reset all the input elements
this.input.each(function() {
$(this).val('');
});
}
The input elements should all have the same id - "new-todo".
I am not very experienced with Backbone.js but you could use jQuery each to loop through all of the inputs and get their value.
if you have:
<input class="todo" type="text" placeholder="Todo item...">
<input class="todo" type="text" placeholder="Todo item...">
<input class="todo" type="text" placeholder="Todo item...">
then
initialize: function () {
this.$inputs = this.$(".todos");
will cache those inputs (not get the value as you said).
then
this.$inputs.each(function() {
console.log($(this).val());
});
will print their values, or you could put their values in an array like so:
var values = this.$inputs.map(function() {
return $(this).val();
});
then you can make a string out of those values with
values.join(' ');
or you can use Underscore's reduce for extra style points:
var string = _(this.$inputs).reduce(function(memo, el) {
return memo + ' ' + $(el).html();
}, '');
i have code it can be sum two textbox values using javascript but problem is that when i entered amount into recamt textbox value and javascript count again and again recamt textbox values it should be count only one time recamt textbox value not again and again?
<script type="text/javascript">
function B(){
document.getElementById('advance').value
=(parseFloat(document.getElementById('advance').value))+
(parseFloat(document.getElementById('recamt').value));
return false;
}
</script>
<input class="input_field2" type="text" readonly name="advance"
id="advance" value="50" onfocus="return B(0);" /><br />
<input class="input_field2" type="text" name="recamt" id="recamt">
You could keep a property on the read-only text field to keep the old value:
function B()
{
var adv = document.getElementById('advance'),
rec = document.getElementById('recamt');
if (typeof adv.oldvalue === 'undefined') {
adv.oldvalue = parseFloat(adv.value); // keep old value
}
adv.value = adv.oldvalue + parseFloat(rec.value));
rec.value = '';
return false;
}
You're calling the sum function every time the readonly input is focused using the new value. If you only want it to add to the original value, you need to store it somewhere.
HTML:
<input type="text" id="advance" readonly="readonly" value="50" /><br />
<input type="text" id="recamt">
JS:
var advanceBox = document.getElementById('advance');
var originalValue = advanceBox.value;
advanceBox.onclick = function() {
this.value = parseFloat(originalValue) +
parseFloat(document.getElementById('recamt').value);
return false;
};
http://jsfiddle.net/hQbhq/
Notes:
You should bind your handlers in javascript, not HTML.
The javascript would need to exist after the HTML on the page, or inside of a window.load handler, otherwise it will not be able to find advanceBox.