Use index to set value on jquery - javascript

Could someone please tell me how I can use the index in this situation?
I have a text field, which is my multiplication factor
<input type="text" id="value">
And I have a table that has 2 fields arranged in the same tr
One with a fixed value
And one that must be the result of multiplying these two values.
Example:
In input I set value = 2
Field Value2 = Value 1 * 2
Value 1
Value 2
3
6
4
8
My jQuery function looks like this:
$( "#btn" ).on( "click", function()
{
let vlUS = $('#value').val()
$("table > tbody > tr > td > input")
.each(function (index) {
let vl1 = $('.val1').val()
let vl2 = vl1 * vlUS
$('.val2').val(vl2)
});
});
Using this way, assigns the same value to all "value2" fields
How can I use index to tune the process?

Loop over the rows and use each row instance to find() the specific inputs within that row
$("#btn").on("click", function() {
let vlUS = $('#value').val();
$("table > tbody > tr").each(function(index) {
const $row = $(this);
let vl1 = $row.find('.val1').val()
let vl2 = vl1 * vlUS
$row.find('.val2').val(vl2);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn">
Calculate
</button> US: <input id="value" value="5" />
<table>
<tr>
<td><input type="text" class="val1" value="3"></td>
<td><input type="text" class="val2"></td>
</tr>
<tr>
<td><input type="text" class="val1" value="6"></td>
<td><input type="text" class="val2"></td>
</tr>
</table>

Consider the following code.
$("#btn").on("click", function() {
$("table tbody tr").each(function(index, elem) {
$(".val2", elem).val(parseInt($(".val1", elem).val()) * parseInt($("#value").val()));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn">Calculate</button> US: <input id="value" value="5" />
<table>
<tr>
<td><input type="text" class="val1" value="3"></td>
<td><input type="text" class="val2"></td>
</tr>
<tr>
<td><input type="text" class="val1" value="6"></td>
<td><input type="text" class="val2"></td>
</tr>
</table>
Simply reduces the operation to one line. Also ensures that if the User enters a Letter; it won't fail.

Related

Rewriting JavaScript code with consequent numbers in the names of ids

I'm trying to apply a function to input field with ids that contain consequent numbers (ie. price1, price2, price3), etc.
There's no problem with the first row of field that are defined for a start. But further input fields are dynamically added by a jQuery function and their number is not known in advance.
I hoped it would be an easy loop to apply:
var i=1;
$("#quantity"+i).keyup(function() {
var price= $("#price"+i).val();
var quantity= $(this).val();
var value= price*quantity;
var value=value.toFixed(2); /* rounding the value to two digits after period */
value=value.toString().replace(/\./g, ',') /* converting periods to commas */
$("#value"+i).val(value);
});
So far so good - the outcome of the multiplication properly displays in the id="value1" field after the "quantity" field is filled up.
Now further fields should follow the pattern and calculate the value when the quantity is entered - like this:
[price2] * [quantity2] = [value2]
[price3] * [quantity3] = [value3]
etc.
So the code follows:
$('#add_field').click(function(){ /* do the math after another row of fields is added */
var allfields=$('[id^="quantity"]');
var limit=(allfields.length); /* count all fields where id starts with "quantity" - for the loop */
for (var count = 2; count < limit; count++) { /* starting value is now 2 */
$("#quantity"+count).keyup(function() {
var cena = $("#price"+count).val();
var quantity= $("#quantity"+count).val();
var value= price*quantity;
var value=value.toFixed(2);
value=value.toString().replace(/\./g, ',')
$("#value"+count).val(value);
});
}
});
The problem is that all further "value" fields are only calculated when "quantity2" is (re)entered and the "value2" is not calculated at all.
I guess there's a mistake while addressing fields and/or triggering the calculation.
How should I correct the code?
Just in case the "add_field" function is needed to solve the problem:
$(document).ready(function(){
var i=1;
$('#add_field').click(function(){
i++;
$('#offer').append('<tr id="row'+i+'">
<td><input type="text" name="prod_num[]" id="prod_num'+i+'" placeholder="Product number (6 digits)"></td><td><input type="text" name="prod_name[]" disabled></td>
<td><input type="text" name="cena[]" id="price'+i+'" placeholder="Enter your price"></td>
<td><input type="text" name="quantity[]" id="quantity'+i+'" placeholder="Enter quantity"></td>
<td><input type="text" name="value[]" id="value'+i+'" disabled></td>
<td><button type="button" name="remove_field" id="'+i+'" class="button_remove">X</button></td></tr>');
});
Incrementing IDs is a lot more trouble than it is worth, especially when you start removing rows as well as adding them.
This can all be done using common classes and traversing within the specific row instance.
To account for future rows use event delegation.
Simplified example:
// store a row copy on page load
const $storedRow = $('#myTable tr').first().clone()
// delegate event listener to permanent ancestor
$('#myTable').on('input', '.qty, .price', function(){
const $row = $(this).closest('tr'),
price = $row.find('.price').val(),
qty = $row.find('.qty').val();
$row.find('.total').val(price*qty)
});
$('button').click(function(){
// insert a copy of the stored row
// delegated events will work seamlessly on new rows also
const $newRow = $storedRow.clone();
const prodName = 'Product XYZ';// get real value from user input
$newRow.find('.prod-name').text(prodName)//
$('#myTable').append($newRow)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Add row</button>
<table id="myTable">
<tr>
<td class="prod-name">Product 1</td>
<td>Qty:<input type="number" class="qty" value="0"></td>
<td>Price:<input type="number" class="price" value="0"></td>
<td>Total:<input type="text" class="total" value="0" readonly></td>
</tr>
<tr>
<td class="prod-name">Product 2</td>
<td>Qty:<input type="number" class="qty" value="0"></td>
<td>Price:<input type="number" class="price" value="0"></td>
<td>Total:<input type="text" class="total" value="0" readonly></td>
</tr>
</table>
Understanding Event Delegation
The first thing to consider is that you can get the length of a selector. So for example:
var count = $("input").length;
If there is one, value here would be 1. if there are four, the value would be 4.
You can also use .each() option to itereate each of the items in the selector.
$('#add_field').click(function(){
var allFields = $('[id^="quantity"]');
allFields.each(function(i, el){
var c = i + 1;
$(el).keyup(function() {
var price = parseFloat($("#price" + c).val());
var quantity = parseInt($(el).val());
var value = price * quantity;
value = value.toFixed(2);
value = value.toString().replace(/\./g, ',');
$("#value" + c).val(value);
});
});
});
You could also create relationship based on the ID itself.
$(function() {
function calcTotal(price, qnty) {
return (parseFloat(price) * parseInt(qnty)).toFixed(2);
}
$('#add_field').click(function() {
var rowClone = $("#row-1").clone(true);
var c = $("tbody tr[id^='row']").length + 1;
rowClone.attr("id", "row-" + c);
$("input:eq(0)", rowClone).val("").attr("id", "prod_num-" + c);
$("input:eq(1)", rowClone).val("").attr("id", "price-" + c);
$("input:eq(2)", rowClone).val("").attr("id", "quantity-" + c);
$("input:eq(3)", rowClone).val("").attr("id", "value-" + c);
$("button", rowClone).attr("id", "remove-" + c);
rowClone.appendTo("table tbody");
});
$("table tbody").on("keyup", "[id^='quantity']", function(e) {
var $self = $(this);
var id = $self.attr("id").substr(-1);
if ($("#price-" + id).val() != "" && $self.val() != "") {
$("#value-" + id).val(calcTotal($("#price-" + id).val(), $self.val()));
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="add_field">Add Field</button>
<br />
<h2>Product</h2>
<table>
<thead>
<tr>
<td>Number</td>
<td>Name</td>
<td>Price</td>
<td>Quantity</td>
<td>Total</td>
<td></td>
</thead>
<tbody>
<tr id="row-1">
<td><input type="text" name="prod_num[]" id="prod_num-1" placeholder="Product number (6 digits)"></td>
<td><input type="text" name="prod_name[]" disabled></td>
<td><input type="text" name="cena[]" id="price-1" placeholder="Enter your price"></td>
<td><input type="text" name="quantity[]" id="quantity-1" placeholder="Enter quantity"></td>
<td><input type="text" name="value[]" id="value-1" disabled></td>
<td><button type="button" name="remove_field" id="remove-1" class="button_remove">X</button></td>
</tr>
</tbody>
</table>

Find Checkbox in HTML Table Using JQuery Find Method

I have a HTML table which has the following structure:
<table id="myTable">
<tr>
<td><input type="text" name="FullName" value="Tom" /></td>
<td><input type="checkbox" name="isActive" /></td>
<td>Edit
</tr>
</table>
When the user clicks the 'edit' link, a Javascript function is called (see below). In this function I need to get the data from the table, i.e., FullName and whether or not isActive has been checked.
$("#namedTutors").on('click', '.editTutor', function () {
var tr = $(this).closest("tr");
var fullName = tr.find("input[name=FullName]").val();
});
I can get the FullName easy enough, but I'm having difficulties retrieving the data to see if isActive has been checked/ticked or not.
Could someone please help.
Thanks.
You could select the ckeckbox input by name [name=isActive] then use the .is(':checked') to check whether the ckeckbox is checked or not, like:
$("#namedTutors").on('click', '.editTutor', function() {
var tr = $(this).closest("tr");
var fullName = tr.find("input[name=FullName]").val();
var isActive = tr.find("input[name=isActive]").is(':checked');
console.log( isActive );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="namedTutors">
<tr>
<td><input type="text" name="FullName" value="Tom" /></td>
<td><input type="checkbox" name="isActive" /></td>
<td>Edit
</tr>
</table>
if(tr.find('input[name="isActive"]:checked').length) {
console.log('it is checked');
}

How to check if all textboxes in a row are filled using jquery

I have 3 textboxes in each row. At least one of the rows should be filled completely. All the textboxes in any of the rows should not be empty. I have tried below code, it's for the first row only.
var filledtextboxes= $(".setup_series_form tr:first input:text").filter(function () {
return $.trim($(this).val()) != '';
}).length;
We want to get the maximum number of non-empty textboxes in any row, TIA.
Loop through all the rows. In each row, get the number of filled boxes. If this is higher than the previous maximum, replace the maximum with this count.
var maxboxes = -1;
var maxrow;
$(".setup_series_form tr").each(function(i) {
var filledtextboxes = $(this).find("input:text").filter(function () {
return $.trim($(this).val()) != '';
}).length;
if (filledtextboxes > maxboxes) {
maxboxes = filledtextboxes;
maxrow = i;
}
});
You are targeting only first tr here $(".setup_series_form tr:first input:text") so you will not get the expected output.
You have to iterate with every row(tr) inside form and then find the count of
text field having not empty values and store in a maxCount variable by comparing it previous tr count.
Here is a working snippet:
$(document).ready(function() {
var maxCountInRow =0;
var rowNumber;
$(".setup_series_form tr").each(function(index){
var filledtextboxes= $(this).find("input:text").filter(function () {
return $.trim($(this).val()) != '';
}).length;
if(filledtextboxes>maxCountInRow){
maxCountInRow=filledtextboxes;
rowNumber=index;
}
});
console.log("Row Number:"+rowNumber+" having maxCount: "+maxCountInRow);
});
.registrant_table{width: 100%;border: 1px solid #ccc;text-align: center;}
.registrant_table tr td{border: 1px solid #ccc;height: 42px;font-weight: bolder;}
.registrant_table input{border: 0px !important;width: 100%;height: 42px;text-align: center;font-weight: normal;}
label.error{color: red !important;}
.err-fields{background-color:red;color: white !important;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="setup_series_form">
<div>
<table class="registrant_table">
<tr class="title">
<td>No</td>
<td>Official Full Name</td>
<td>Mobile Contact</td>
<td>Email</td>
</tr>
<tr class="in-fields">
<td>1</td>
<td><input type="text" value="sas" name="firstname[]"></td>
<td><input type="text" value="" name="phone[]"></td>
<td><input type="text" value="" name="email[]"></td>
</tr>
<tr class="in-fields">
<td>2</td>
<td><input type="text" value="sas" name="firstname[]"></td>
<td><input type="text" value="sas" name="phone[]"></td>
<td><input type="text" name="email[]"></td>
</tr>
<tr class="in-fields">
<td>3</td>
<td><input type="text" name="firstname[]"></td>
<td><input type="text" name="phone[]"></td>
<td><input type="text" name="email[]"></td>
</tr>
</table>
</div>
</form>

How can i wait until all table rows in the 1st column is 100 to display "done" in the 2nd column

I have a table which the number of row is dynamic depends on database record. So regardless of the no of table row, when all the rows in the first column is 100, all rows in the 2nd column will display "done".
Right now, when i input 100 in the 1st row, all rows in the 2nd column will display "done". How can i wait until all rows in the 1st column is 100 to display "done"
$(".test").on('keyup', function() {
var set = $('.test').val();
if (set == 100 ) {
$('.result').val("done");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="number" class="test">
<td><input type="text" class="result">
</tr>
<tr>
<td><input type="number" class="test">
<td><input type="text" class="result">
</tr>
<tr>
<td><input type="number" class="test">
<td><input type="text" class="result">
</tr>
Here is one-of-the-ways to achieve it. Instead of keyup, you use input event.
On every event, you check if all input fields have values or not.
If all fields have values, check if all have values as 100 or not.
$(".test").on('input', function() {
checkAndUpdateSecondColumn();
});
function checkAndUpdateSecondColumn() {
var empty = $("input.test").filter(function() {
return this.value != "";
});
if ($("input.test").length == empty.length) {
var sum = $('.test').toArray().reduce(function(sum, element) {
return sum + Number(element.value);
}, 0);
$('.result').val('');
if (sum == $("input.test").length * 100) {
$('.result').val('done');
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="number" class="test">
<td><input type="text" class="result">
</tr>
<tr>
<td><input type="number" class="test">
<td><input type="text" class="result">
</tr>
<tr>
<td><input type="number" class="test">
<td><input type="text" class="result">
</tr>
The problem with your code is that when you assign your variable set, you are attempting to read the .val() of a jQuery collection containing multiple DOM elements. The value of the first matching element is returned; the others are not evaluated.
It sounds like what you want to do is evaluate the entire set and make certain that all match your desired value before displaying a "done" message. One way to achieve this behavior is by filtering against the values of every element in the jQuery collection (every element of class "test").
var testInputs = $('.test');
var desiredValue = 100;
testInputs.on('keyup', function() {
var testInputsSetToDesiredValue = testInputs.filter(function() {
return parseInt(this.value, 10) === desiredValue;
});
if (testInputsSetToDesiredValue.length === testInputs.length) {
$('.result').val('done');
}
});

Get value of class with dynamic id jquery

I have the table bellow and I want to get the input $('.note') value from the id of the previous input :
<tr>
<td><input type="text" id='student_1' class='student'></td>
<td><input type="text" class='note'></td>
</tr>
<tr>
<td><input type="text" id='student_2' class='student'></td>
<td><input type="text" class='note'></td>
</tr>
So it can be something like that :
$(".student").change(function () {
alert(this.id.parent('td input.note').val())
})
You could use this.value or $(this).val() :
$('.classname').on('click',function(){
console.log(this.value, $(this).val(), this.id);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' class='classname' id="id_1" value='value_1'/>
<input type='text' class='classname' id="id_2" value='value_2'/>
<input type='text' class='classname' id="id_3" value='value_3'/>
<input type='text' class='classname' id="id_4" value='value_4'/>
Edit :
Go up to the parent tr using .closest('tr') then search for the related input note using .find('.note') and get the value :
$(".student").on('input', function () {
console.log( $(this).closest('tr').find('.note').val() );
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="text" id='student_1' class='student'></td>
<td><input type="text" class='note' value="1111"></td>
</tr>
<tr>
<td><input type="text" id='student_2' class='student'></td>
<td><input type="text" class='note' value="2222"></td>
</tr>
</table>
You can use a combination of closest and find.
$(".student").on('change', function () {
// the student input to which the change event is bound
var $this = $(this);
// Get the wrapper in which the inputs are present
var $closestTr = $this.closest('tr');
// the input vale that is needed
alert($closestTr.find('.note').val());
});
Yes, you can do this $('#' + this.id).val()
You don't need to include the class in the selector because IDs are unique.

Categories

Resources