Dividing a column of <td> by a an input value - javascript

I'm stumped by this current project I'm trying to solve. I'm able to print out the exact results that I want in the console, however I can't figure out how to insert those back into their respective tds within the table.
var calc = $('.calc'),
odds = $('.weight');
$(document).on('keyup keydown', '.calc', function(e){
var curVal = calc.val();
$(document).find('.weight').each(function(){
var oddsVal = ($(this).text() / curVal);
console.log(oddsVal);
});
});
I'm trying to divide the text in each cell of the weight column by the input.calc while a user is entering data into the input so that it updates live.
You can see a Fiddle of it here, with the results printing to the console. How can I make it so each cell in the weight column updates?
Thanks in advance for your help!

The problem is that the cells are getting updated before a value is in the input, which results in 'Infinity' being created 4 times. You can even see it in your console log.
Instead, make sure there is a value in calc before executing the function.
Furthermore, if you repeatedly change the calc field, it will do a new calculation based on the newly replaced values, which does not seem like the correct behavior. So, instead, capture the original values on page load and use those in the calculation:
var originalWeights = getOriginalWeights();
function getOriginalWeights() {
var weights = [];
$('.weight').each(function(index) {
weights[index] = $(this).text();
});
return weights;
}
$(document).on('keyup keydown', '.calc', function(e){
if (!calc.val()) return;
var curVal = calc.val();
$(document).find('.weight').each(function(index){
var oddsVal = (originalWeights[index] / curVal);
$(this).text(oddsVal);
});
});
Fiddle

To solve this you have to edit both HTML and JS code. You should store the original value in a data attribute, and then print it inside the loop using the value parameter of the jquery each function. Here is your fiddle edited, hope it helps!
http://jsfiddle.net/ch1qui/LoLrotkn/3/

You should remove the keydown event from the event delegation as the value on the input box would not be available during keydown. Also having keyup and keydown would trigger the events simultaneously, triggering each block twice. Also you don't need to declare the var calc = $('.calc'), globally since the element would be available during the event target on the document.
$(document).on('keyup', '.calc', function(e){
var curVal = $(this).val();
$('table td.weight').each(function(){
var oddsVal = $(this).text() / curVal;
alert(oddsVal);
});
});
Example : http://jsfiddle.net/LoLrotkn/4/

Related

count char of TextArea (retrieved from database)

I am dynamically creating combination of textarea and label, each combination having different ids. e.g: text-1, text-2 .... for textarea and lab-1, lab-2, .... for labels.
Each label displays the number of characters in each textarea. I am doing this by using following piece of code.
function updateCount(textAreaId, labelId) {
var cs = $('#'+textAreaId).val().length;
$('#'+ labelId').text(cs);
}
Calling above function onkeyUp and onKeyDown on textarea and its working fine.
In some of the textareas I am filling the data from the users last submission from database, In that case it shows default length as 0 till some key in not pressed in the textarea.
I want that as soon as page loads.
You can manually trigger keyup
$('textarea[id^="text-"]').keyup();
Make sure to place this line after binding the keyup events to all textareas
On page load, get the value of the textareas where the value has been added. Get the length of the value, and subtract the length from the maximum length.
$(window).load(function(){
var length = $('textarea').val().length;
Maxmlength = maxmlength - length;
$('span').text(Maxmlength); //element to display the remaiing character.
});
Hope this will help.
<script>
$( document ).ready(function() {
var textAreaId="textArea1";
$('#'+textAreaId).keyup(function() {
updateCount(textAreaId, labelId);
});
});
</script>

Applying increasing values to text field on focus or on click

I have 18 rows of text fields and in each one I need to give it an increasing ID, however they're not just straight forward, as the bottom row in the grid could need ID 1 and the first one could need ID 15 depending on what is chosen. It doesn't need to look that pretty as long as it does the job. I will be using it to insert data in to a database from an iPad and ideally having an onclick event on the row title, and that adding the next incremental number would be perfect, however if that's not possible adding an onfocus event would be fine.
I already have the following
$('.played').on('focus', function(){
var $this = $(this);
if($this.val() == ''){
$this.val('1');
} else {
$this.val('');
}
});
Which adds the number 1 in the clicked text field and if you click on it when it has the value of 1, it removes it. What I'd now like to do is when the next 'played' class text field that's clicked, it populates it with 2, and so on up to 18. Is this possible?
Maybe something like the following to get the max value that you can check against yourself to know if you need to set it or clear it out, and additionally if you don't have a value and you do have a max value, your new value would be max + 1
var valueArray = $('.played').map(function(played){ return $(played).val(); }).toArray();
var maxValue = Math.max(valueArray);

Product price calculator isn't working

I'm creating an order form in which users can select an amount of products and it should immediately change total prices. I made some HTML markup and jquery code to achieve this, but I can't get it working. Can anyone see what I'm doing wrong?
Fixed script:
$("input[type=number]").change(function () {
var value = parseFloat($(this).attr("title"));
var total = (value * this.value).toFixed(2);
if (total < 0) total = 0;
$(this).parent().next().find("input").val('€' + total);
});
Inside of event handler this refers to HTMLInputElement, not jQuery instance so you have to wrap it in $(this).
Also you need to traverse one level up to the parent node and then use next() to get target input field.
Finally I added basic validation to prevent negative prices. You can also add min="0" attribute to input fields.
Demo: http://jsfiddle.net/dfsq/X33pS/

Populating div in real time with form input data

I have a form (just one field) which I am populating with some data. I would like to get me Div container populated with the data I put there in a real time. So no refresh, after I type in some text in the form field, I get it in the div as well. Does anybody know how to do it? JQuery, AJAX?Any advice appreciated.
var div = $('div')[0];
$('input').bind('keyup change', function() {
div.innerHTML = this.value;
});
Try it out: http://jsfiddle.net/H6P2z/
Of course you should make the selectors specific to your actual elements.
With jQuery you can do this very easily:
$('#textFieldId').bind('change', function (event, previousText) {
$('#divId').html($(this).val());
});
You could bind an onkeyup event to the input field. When the event fires, you can grab the contents of the field and do what you want with it.
This might look like this:
$(selector).keyup(function(e) {
// find the value of the field
var text = $(this).val();
// do something with it
$(yourDivSelector).html(text);
});

Finding Changed Form Element With jQuery

i have a form(id="search_options") and i tracking changes in form by:
$("#search_options").change(function() {
// Bla Bla Bla
});
In this form i have many inputs and one of is select(id="project_category") and i want to catch if user changed project_category select or another input. How can i done this ? Thanks
What you are looking to do could be accomplished 2 ways I can think of off the top of my head.
First, Capture the change event for all input items in your form individually
$("#search_options input,#search_options select").change(function() {
// "this" is the input that has changed so you would check if it had id = "project_category" here
});
Alternatively you could track the current value of the "project_category" on every change
var current_Project_Category = "";
$("#search_options").change(function() {
if(current_Project_Category != $(this).find("#project_category").val())
{
//project category has changed so mark this as the current one
//also run any change code here
current_Project_Category = $(this).find("#project_category").val()
}
});
There is a plugin made for exactly this purpose:
jQuery Form Observe
This plugin observes values of form
elements. When end-user changes any
values of input elements, observer
shows which values were changed. And
observer also alerts to users when
they try to move out from the page
before submitting changes.
Try this instead:
$("#search_options").find('input,select').change(function() {
var changedId = $(this).attr('id');
var newVal = $(this).val();
});

Categories

Resources