I want to get an updated value from an input field. So I setup a listener
$('.product-quantity input').change( function() {
console.log($(this).parents('.product')[0].id)
var id = $(this).parents('.product')[0].id;
var classgroup = $(this).parents('.product')[0]
for (var i = 0; i < classgroup.childNodes.length; i++){
if (classgroup.childNodes[i].className == "product-quantity") {
console.log(classgroup.childNodes[i])
var target = classgroup.childNodes[i]
}
}
});
classgroup.childNodes[i] output this html
<div class="product-quantity">
<input type="number" id="productquantity" value="1" min="1">
</div>
what I want to do now is get the user input in value. It is suppose to be simple but I can't figure it out
I've tried these but no success
console.log(target.attr('value'))
target.each(function(){
console.log(this.value)
})
how can I get the value number for the output html?
Is this what you are trying to do? You can grab the val of the input itself, and log on change (or whatever you would like to do).
$('#productquantity').change(function() {
console.log($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="product-quantity">
<input type="number" id="productquantity" value="1" min="1">
</div>
Related
I want to get value from "data-val" input field which is hypen separated and after removimg hypen individual value should get assigned to separate text box which have same class name, but instead of separate value only last value is assigning to every text box.
for example if data-val class have value like this 3-4-5 then it should get separated by "-" and individual value get assigned to separated text filed.
<input type="text" class="form-control data-val" onblur="assign_val('data-val','input_val')"value=""/>
<input type="text" class="form-control input_val" name="">
<input type="text" class="form-control input_val" name="">
<input type="text" class="form-control input_val" name="">
<script>
function assign_val(data-val,input_val) {
var data-val = $(".data-val").val();
var count = $('.' + input_val).length;
var i;
var data-val= data-val.split("-");
for (i = 1; i <= data-val.length; i++)
{
$(".input_val").val(data-val[i]);
}
}
</script>
You can do this using JQuery .each https://api.jquery.com/each/
$( ".input_val" ).each(function( index ) {
$(this).val(data-val[index]);
});
i am creating a voucher, for an Management Program, i have an input field which counts value and add in the last colum, as sum of debits and credits in all rows for that i am using counters to track sum, i am using onchange or onblur click event, it works well it counts wih increase in rows, but when i try to remove the value from input it still couns i counter
here is the code
var credit_counter = 0;
$(document).on('blur', 'input[name="credit[]"]', function () {
idName = $(this).attr('id');
id = idName.substring(6, idName.length);
var value = $(this).val();
credit_counter = credit_counter + Number(value);
var credit_balance = $("#get_credit").val(credit_counter)
});
var debit_counter = 0;
var total_balance = 0;
$(document).on('blur', 'input[name="debit[]"]', function () {
idName = $(this).attr('id');
id = idName.substring(6, idName.length);
var value = $(this).val();
$("#credit" + id).val(value)
debit_counter = debit_counter + Number(value);
var debit_balance = $("#get_debit").val(debit_counter);
});
I want to remove the value in case I erase value from input field thanks
Here is a complete example which achieves what you are looking to do (warning: no styling has been added so it is ugly). You can copy and paste this into a .html file and open it in with the web browser of your choice to see it in action:
<!DOCTYPE html>
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
</head>
<body>
<input placeholder="credit field 1" type="text" name="credit" /><br/>
<input placeholder="credit field 2" type="text" name="credit" /><br/>
<input placeholder="credit field 3" type="text" name="credit" /><br/>
<input placeholder="credit field 4" type="text" name="credit" /><br/>
<input placeholder="debit field 1" type="text" name="debit" /><br/>
<input placeholder="debit field 2" type="text" name="debit" /><br/>
<input placeholder="debit field 3" type="text" name="debit" /><br/>
<input placeholder="debit field 4"type="text" name="debit" /><br/>
<input placeholder="credit total" id="get_credit" type="text" /><br/>
<input placeholder="debit total" id="get_debit" type="text" /><br/>
<script>
$(document).on('blur', 'input[name="credit"]', function () {
var total = 0;
$('input[name="credit"]').each(function( index, element ) {
if(!isNaN($(this).val())){
total += Number($(this).val());
}
$('#get_credit').val(total);
});
});
$(document).on('blur', 'input[name="debit"]', function () {
var total = 0;
$('input[name="debit"]').each(function( index, element ) {
if(!isNaN($(this).val())){
total += Number($(this).val());
}
$('#get_debit').val(total);
});
});
</script>
</body>
</html>
Your issue is that the way you are keeping track of the total debits and total credits does not allow you to know the values stored in each input individually. The problem that creates is that when a value is removed, there is no way for you to know what to subtract from the total. (Likewise, if someone were to change the value from 3 to 30 then your total would go up by 30 instead of 27).
There is definitely more than one way to fix that however the answer I posted is what I believe to be most simple: On blur of the input, iterate through the appropriate inputs and add them together then assign the total to the appropriate input.
Note I've excluded your logic of acting on the ids of the inputs as it is unclear what you're doing with them without further explanation or seeing your view markup. It also seems to be unrelated to the issue you're posting about.
I understood your problem. Can we do like this.
1) Trigger an event on focus.
2) Subtract the focused element value from total.
If user doesn't removed complete value from the input. anyway we are triggering event on blur. So it will take whatever the value remained in the text box and counts that!
I have 41 checkboxes like this
HTML
<input id="1" type="checkbox" onclick="updatebox()" />
<input id="2" type="checkbox" onclick="updatebox()" />
<input id="3" type="checkbox" onclick="updatebox()" />
<input id="4" type="checkbox" onclick="updatebox()" />
Javascript
<script type="text/javascript">
function updatebox()
{
var textbox = document.getElementById("list");
var values = [];
if(document.getElementById('1').checked) {values.push("1");}
if(document.getElementById('2').checked) {values.push("2");}
if(document.getElementById('3').checked) {values.push("3");}
if(document.getElementById('4').checked) {values.push("4");}
textbox.value = values.join(", ");
}
</script>
When checkbox is checked the value is posted in textbox,
now what i want is when the user clicks the checkbox the jquery dialog popups and the user will have two radio buttons with Male or Female options along with ok button so when the user will click on ok the value should be posted on textbox depending on selection M for male F for female along with number like 1M or 1F, 2M or 2F and so on.
P.S user can select multiple checkboxes.
Thanks You!
Here is something that does what you want. HTML:
<body>
<form id="form">
<input id="1" type="checkbox" /> 1
<input id="2" type="checkbox" /> 2
<input id="3" type="checkbox" /> 3
<input id="4" type="checkbox" /> 4
...
<input id="10" type="checkbox" /> 10
...
<input id="41" type="checkbox" /> 41
<input id="list" />
</form>
<div id="prompt" style="display:none;" title="Gender">
<form>
<input type="radio" name="gender" id="radio" value="male" />
<label for="radio">Male</label>
<input type="radio" name="gender" id="radio2" value="female" />
<label for="radio2">Female</label>
</form>
</div>
</body>
The JavaScript:
$(function() {
var form = document.getElementById("form");
var textbox = document.getElementById("list");
var $prompt = $("#prompt");
// We record what is currently checked, and the user's answers in this `pairs` object.
var pairs = [];
// Listen to `change` events.
$("input[type='checkbox']", form).on('change', function (ev) {
var check = ev.target;
if (check.checked) {
// Checked, so prompt and record.
$prompt.dialog({
modal: true,
buttons: {
"Ok": function() {
var gender = $prompt.find("input[name='gender']:checked")[0];
var letter = {"male":"M", "female":"F"}[gender.value];
pairs[check.id] = '' + check.id + letter;
$( this ).dialog( "close" );
refresh();
}
}
});
}
else {
// Unchecked, so forget it.
delete pairs[check.id];
refresh();
}
function refresh() {
// Generate what we must now display in the textbox and refresh it.
// We walk the list.
var keys = Object.keys(pairs);
var values = [];
for (var i = 0, key; (key = keys[i]); ++i) {
values.push(pairs[key]);
}
textbox.value = values.join(", ");
}
});
});
Here is a jsbin with the code above.
Salient points:
This code adds the event handlers using JavaScript rather than use onclick in the HTML. It is not recommended to associated handlers directly in the HTML.
It listens to the change event rather than click. Some clicks can sometimes not result in a change to an input element.
It uses $.dialog to prompt the user for M, F.
The refresh function is what recomputes the text field.
It keeps a record of what is currently checked rather than requery for all the check boxes when one of them changes.
function updatebox()
{
var textbox = document.getElementById("list");
var values = [];
for (var i = 1; i <= 41; ++i) {
var id = '' + i;
if (document.getElementById(id).checked) {
var gender = prompt('Male (M) or female (F)?');
values.push(gender + id);
}
}
textbox.value = values.join(", ");
}
A few things to note:
I got rid of all that code repetition by simply using a for loop from 1 to 41.
I also fixed the strange indentation you had there.
You may want to use a method of getting user input other than prompt, but it'll work the same way.
(If you're going to keep using prompt, you might also want to add input validation as well to make sure the user didn't input something other than M or F.)
I'm trying to build a form where if you update any of the inputs, it will update the sum. Right now only the first input is working. I want to use a single class across all of the inputs as the page is dynamic and the ID's can change often.
Here is the jsfiddle:
jsfiddle
Here is the code:
var productCost = function (input, output, changeOn) {
var reloadCalcs = function () {
var sum = 0;
$(input).each(function() {
sum += parseFloat($(input).val());
});
$(output).html(sum);
};
$(function () {
$(changeOn).change(function () {
reloadCalcs();
});
$(changeOn).trigger('change');
});
};
productCost('.product','.sum','input');
By using
sum += parseFloat($(input).val());
You are telling the sum to add the value of .product to itself, since the .product selector will have multiple elements, it will choose the first one.
To fix this, you should use this:
sum += parseFloat($(this).val());
2 changes
var productCost = function(input, output, changeOn) {
var reloadCalcs = function() {
var sum = 0;
$(input).each(function() {
//use the value of current element
sum += (+this.value || 0)
});
$(output).html(sum);
};
//use event delegation to support dynamic elements
$(document).on('change', changeOn, function() {
reloadCalcs();
}).trigger('change');
};
productCost('.product', '.sum', 'input');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" class="product" id="design" value="5" />
<br>
<input type="number" class="product" id="features" value="5" />
<br>
<input type="number" class="product" id="performance" value="5" />
<br>
<input type="number" class="product" id="usability" value="5" />
<br>
<h3>TEST</h3>
<div class="sum"></div>
When you use $(input).val(), it will always return the value of the first input element instead of returning the value of current input in the loop
I have a set of number input fields, labeled small & medium.., and a set of div's with the label small and medium. When you add a number to the small number input field a text input insertsAfter the div labeled small. When you subtract a number from the small number input field, the text input field that was recently added is removed. the adding and removing of the text input is be the last one in the list. This same thing goes for the medium number field and medium label/textfield
please see JSFiddle for reference
http://jsfiddle.net/7PhJZ/53/
Right now my script is working correctly when I click the up or down buttons on the number field. But When I type in, for instance 5 in the small number field, only one new div/name input fields appears under the label small. I need the adding and subtracting of these input fields to be generated when I use the arrows and when I type in a number. So when I type in "5" 5 name/text input fields should appear under the associated label.
html :
<div id="product-1">
<div class="size-field">
<div id="size-label">s</div>
<div class="number-input">
<input id="Small" class="product-quantity" type="number" name="Small"
min="0" max="9999" data-product-id="1"></input>
</div>
</div>
<div id="size-label">m</div>
<div class="number-input">
<input id="Medium" class="product-quantity" type="number"
name="Medium" min="0" max="9999" data-product-id="1"></input>
</div>
<div class="name-number-header">
<h5>HEADER<h5></div>
<div class="name-number-field-container" data-size="Small">small:
</div>
<div class="name-number-field-container" data-size="Medium">medium:
</div>
</div>
<br clear="all">
<div id="product-2">
<div class="size-field">
<div id="size-label">s</div>
<div class="number-input">
<input id="Small" class="product-quantity" type="number" name="Small"
min="0" max="9999" data-product-id="2"></input>
</div>
</div>
<div id="size-label">m</div>
<div class="number-input">
<input id="Medium" class="product-quantity" type="number" name="Medium"
min="0" max="9999" data-product-id="2"></input>
</div>
<br clear="all">
<div class="name-number-header"><h5>HEADER<h5></div>
<div class="name-number-field-container" data-size="Small">small:
</div>
<div class="name-number-field-container" data-size="Medium">medium:
</div>
</div>
js :
$('.product-quantity').each(function () {
$(this).data('val', this.value);
}).on('change', function () {
var val = $(this).val(),
old = $(this).data('val'),
input = $('<div/>', {'class': 'name-number-field'}).html('<input
class="name-field" name="name" placeholder="Name" type="text">'),
ele = $(this).closest('[id^="product"]').find('[data-size="' + this.name + '"]'),
inc = val >= old;
if (inc) {
$(input).insertAfter(ele.nextUntil(':not(.name-number-field)').last()
.length ? ele.nextUntil(':not(.name-number-field)').last() : ele);
} else {
ele.nextUntil(':not(.name-number-field)').last().remove();
}
$(this).data('val', this.value);
});
See this fiddle
You need to put a for loop outside the code that created the elements:
}).on('change', function () {
var val = $(this).val(),
old = $(this).data('val');
for (var count=0; count<Math.abs(val-old) ; count++)
{
...
}
Update based on comments
See this updated fiddle. There were some problems that were in the original code:
The data was not initialised. Fix: if( !startVal || startVal.length == 0 )
The comparison was not with ints. Fix: inc = (parseInt(val) >= parseInt(old));
Your code is checking for the direction of change between old and new only, not how much difference there is. If it's an increase (of any amount), you add an element; if it's a decrease, you remove one.
You need to wrap that code in a loop and execute it as many times as the difference between old and new.
for (var i=0 ; i<Math.abs(val-old) ; i++) {
if (inc) {
$(input).insertAfter(ele.nextUntil(':not(.name-number-field)').last()
.length ? ele.nextUntil(':not(.name-number-field)').last() : ele);
} else {
ele.nextUntil(':not(.name-number-field)').last().remove();
}
}