Add all textbox value inside the tabel using javascript - javascript

i want to add all text box value inside the tabel using jquery.
<script>
str =0;
$(document).ready(function(){
$('#btn_res').click(function(){
$('#calculate').find("input[type=text]").each(function(){
str+=$(this).text();
})
$('#result').text(str);
});
});
</script>

you need
$(document).ready(function() {
$('#btn_res').click(function() {
var str = 0;
$('#calculate').find("input[type=text]").each(function() {
//need to use .val()
//also need to convert it to a numerical value for addition else string concatenation will be done
str += (+$(this).val() || 0);
})
$('#result').text(str);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="calculate">
<tr>
<td>
<input type="text" />
</td>
<td>
<input type="text" />
</td>
</tr>
<tr>
<td>
<input type="text" />
</td>
<td>
<input type="text" />
</td>
</tr>
<tr>
<td>
<input type="text" />
</td>
<td>
<input type="text" />
</td>
</tr>
</table>
<button id="btn_res">Sum</button>
<div id="result"></div>

Use val() bacause you are getting form input fields values
$('#btn_res').click(function(){
$('#calculate').find("input[type=text]").each(function(){
str+=$(this).val();
})
$('#result').text(str);
});

My own suggestion would be the following:
$(document).ready(function() {
$('#btn_res').click(function() {
// find all the relevant input elements directly (no need
// to use 'find()'; then iterate over those elements with 'map()':
var str = $('#calculate input[type="text"]').map(function() {
// this returns the value of the input (as a number) or a 0 (if
// the input is not a valid number):
return parseFloat((this.value || 0));
// 'get()' converts the object to an array,
// 'reduce' reduces the array to a single result:
}).get().reduce(function(a, b) {
// returns the sum of the array's elements:
return a + b;
});
$('#result').text(str);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="calculate">
<tr>
<td>
<input type="text" />
</td>
<td>
<input type="text" />
</td>
</tr>
<tr>
<td>
<input type="text" />
</td>
<td>
<input type="text" />
</td>
</tr>
<tr>
<td>
<input type="text" />
</td>
<td>
<input type="text" />
</td>
</tr>
</table>
<button id="btn_res">Sum</button>
<div id="result"></div>
References:
JavaScript:
Array.prototype.reduce().
parseFloat().
jQuery:
get().
map().
text().

Related

JQuery - Finding Model[n].FieldName and adding values

I am trying to the find, and add, the value of indexed fields in each row of a table.
<tr>
<td><input name="Model[0].Name" type="hidden" value="0" /></td>
<td><input name="Model[0].Sched" type="hidden" value="0" /></td>
<td><input name="Model[0].Comp" type="hidden" value="0" /></td>
<td><input name="Model[0].NoShow" type="hidden" value="0" /></td>
<td><input name="Model[0].TotalHours" type="hidden" value="0" /></td>
</tr>
<tr>
<td><input name="Model[1].Name" type="hidden" value="0" /></td>
<td><input name="Model[1].Sched" type="hidden" value="0" /></td>
<td><input name="Model[1].Comp" type="hidden" value="0" /></td>
<td><input name="Model[1].NoShow" type="hidden" value="0" /></td>
<td><input name="Model[1].TotalHours" type="hidden" value="0" /></td>
</tr>
I would like to add Model[n].Sched + Model[n].Comp + Model[n].NoShow = Model[n].TotalHours for each row.
I think there must be a simple solution to this, but I must be searching for a solution using in the incorrect keywords.
TIA!
As I mentioned in my commend, iterate over each row and search for all inputs in each row. If you have to only get the inputs with the specific name, you can use the attribute contains selector:
$('tr').each(function() {
// Find the the input we want to set the value of
$(this).find('input[name*="TotalHours"]').val(
// Find the inputs we want to sum
$(this).find('[name*="Sched"], [name*="Comp"], [name*="NoShow"]')
// Get their values and convert them to numbers
.map(function() { return Number(this.value); })
.get()
// sum the values
.reduce(function(sum, v) { return sum + v; })
);
});
$('tr').each(function() {
// Find the the input we want to set the value of
$(this).find('input[name*="TotalHours"]').val(
// Find the inputs we want to sum
$(this).find('[name*="Sched"], [name*="Comp"], [name*="NoShow"]')
// Get theirs values and convert them to numbers
.map(function() {
return Number(this.value);
})
.get()
// sum the values
.reduce(function(sum, v) {
return sum + v;
})
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input name="[0].Sched" value="1" />
</td>
<td>
<input name="[0].Comp" value="2" />
</td>
<td>
<input name="[0].NoShow" value="3" />
</td>
<td>
<input name="[0].TotalHours" value="0" />
</td>
</tr>
<tr>
<td>
<input name="[1].Sched" value="4" />
</td>
<td>
<input name="[1].Comp" value="5" />
</td>
<td>
<input name="[1].NoShow" value="6" />
</td>
<td>
<input name="[1].TotalHours" value="0" />
</td>
</tr>
</table>
Iterate over each row and then inside iterate over each column. If the name doesn't contain TotalHours add it's value to the sum. If it does contain TotalHours then set the value equal to the sum. Here is an example with values not 0 and not hidden.
$('tr').each(function(index) {
var sum=0;
$('td input',this).each(function(){
if($(this).attr('name').indexOf('TotalHours')==-1){
sum+=parseInt($(this).val());
}else{
$(this).val(sum);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input name="[0].Sched" value="10" />
</td>
<td>
<input name="[0].Comp" value="20" />
</td>
<td>
<input name="[0].NoShow" value="30" />
</td>
<td>
<input name="[0].TotalHours" value="0" />
</td>
</tr>
<tr>
<td>
<input name="[1].Sched" value="5" />
</td>
<td>
<input name="[1].Comp" value="2" />
</td>
<td>
<input name="[1].NoShow" value="3" />
</td>
<td>
<input name="[1].TotalHours" value="0" />
</td>
</tr>
</table>
You can use JavaScript String search() Method to match the input name.
Searches a string for a specified value, and returns the position of the match. The value can be string or a regular expression. If no match is found the method returns -1.
Below, an iteration occurs through each tr
then each input, which searches for
a specific name, if not equal -1, the variable
totalHours receives the value:
$('tr').each(function() {
var totalHours = 0;
$(this).find('input').each(function() {
if ($(this).attr("name").search("Sched") != -1
|| $(this).attr("name").search("Comp") != -1
|| $(this).attr("name").search("NoShow") != -1) {
totalHours += Number($(this).val());
}
});
$(this).find('input[name*="TotalHours"]').val(totalHours);
});
Check it out:
JSFiddle

Trying to find previous DOM elements and get input value jquery

I am trying to create a table that when a user click update, it will get the first and second input value. I am trying to use prev to find the first two DOM element and get the value, but fail, what should I do? Any help is appreciated.
$('.update_button').on("click",function(){
var update_val_1 = $(this).prev().find('input:first').val();
var update_val_2 = $(this).prev().find('input:nth-child(2)').val();
alert(update_val_1);
alert(update_val_2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr class="gridtable">
<td><input type="text" value="apple" /></td>
<td><input type="text" value="one" /></td>
<td><button type="button" class="update_button">UPDATE</button></td>
</tr>
<tr class="gridtable">
<td><input type="text" value="banana" /></td>
<td><input type="text" value="three" /></td>
<td><button type="button" class="update_button">UPDATE</button></td>
</tr>
<tr class="gridtable">
<td><input type="text" value="berry" /></td>
<td><input type="text" value="ten" /></td>
<td><button type="button" class="update_button">UPDATE</button></td>
</tr>
The problem is that prev looks for sibling nodes. Your input elements are in different td's so they aren't siblings. Instead, you need to go to the parent row then grab the inputs from there.
Explicit example:
$('.update_button').on("click", function() {
var $parentRow = $(this).closest('.gridtable');
var $firstCell = $parentRow.find('td:first-child');
var $secondCell = $parentRow.find('td:nth-child(2)');
var $firstInput = $firstCell.find('input');
var $secondInput = $secondCell.find('input');
var update_val_1 = $firstInput.val();
var update_val_2 = $secondInput.val();
console.log(update_val_1);
console.log(update_val_2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr class="gridtable">
<td>
<input type="text" value="apple" />
</td>
<td>
<input type="text" value="one" />
</td>
<td>
<button type="button" class="update_button">UPDATE</button>
</td>
</tr>
<tr class="gridtable">
<td>
<input type="text" value="banana" />
</td>
<td>
<input type="text" value="three" />
</td>
<td>
<button type="button" class="update_button">UPDATE</button>
</td>
</tr>
<tr class="gridtable">
<td>
<input type="text" value="berry" />
</td>
<td>
<input type="text" value="ten" />
</td>
<td>
<button type="button" class="update_button">UPDATE</button>
</td>
</tr>
</table>
Simplified example:
$('.update_button').on("click", function() {
var $parentRow = $(this).closest('.gridtable');
var update_val_1 = $parentRow.find('td:first-child input').val();
var update_val_2 = $parentRow.find('td:nth-child(2) input').val();
console.log(update_val_1);
console.log(update_val_2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr class="gridtable">
<td>
<input type="text" value="apple" />
</td>
<td>
<input type="text" value="one" />
</td>
<td>
<button type="button" class="update_button">UPDATE</button>
</td>
</tr>
<tr class="gridtable">
<td>
<input type="text" value="banana" />
</td>
<td>
<input type="text" value="three" />
</td>
<td>
<button type="button" class="update_button">UPDATE</button>
</td>
</tr>
<tr class="gridtable">
<td>
<input type="text" value="berry" />
</td>
<td>
<input type="text" value="ten" />
</td>
<td>
<button type="button" class="update_button">UPDATE</button>
</td>
</tr>
</table>
I'm a big fan of the .closest(selector) and .find('selector') methods.
The first one goes up the dom until it finds the first match of the given selector.
The second one goes down the dom and finds all matches.
.eq(index) is like array[index] for jQuery. It takes a collection of jQuery elements and returns the one at the given index.
$('.update_button').on("click",function(){
var inputs = $(this).closest('.gridtable').find('input');
var value1 = inputs.eq(0).val();
var value2 = inputs.eq(1).val();
});

Javascript UK Sort code validation with three input field

I have one payment page where I have three field called sort code each field can have 2 two digit I want to write java script code to validate this field and as user type 2 digit in first field its should jump to next field. how to validate static sort code.
$('.input').on('keyup', function(e) {
if ($(this).length == 2) {
$('.next-input').focus();
}
}
You'll have to create a collection of your inputs, and proceed to the next item in the collection after the second letter is typed.
var $inputs = $('.input-class');
$inputs.on('keyup', function() {
if ($(this).val().length == 2) {
$inputs.eq($inputs.index(this) + 1).focus();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
<table>
<tr>
<td>
<input type="text" class="input-class input-1">
</td>
<td>
<input type="text" class="input-class input-2">
</td>
<td>
<input type="text" class="input-class input-3">
</td>
<td>
<input type="text" class="input-class input-4">
</td>
<td>
<input type="text" class="input-class input-5">
</td>
</tr>
</table>
</form>
If you'd like a more fine tuned solution, you can add as a data-attribute the selector of the next input
var $inputs = $('.input-class');
$inputs.on('keyup', function() {
if ($(this).val().length == 2) {
$($(this).data('next')).focus();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
<table>
<tr>
<td>
<input type="text" class="input-class input-1" data-next=".input-3">
</td>
<td>
<input type="text" class="input-class input-2" data-next=".input-4">
</td>
<td>
<input type="text" class="input-class input-3" data-next=".input-5">
</td>
<td>
<input type="text" class="input-class input-4" data-next=".input-1">
</td>
<td>
<input type="text" class="input-class input-5" data-next=".input-2">
</td>
</tr>
</table>
</form>
This is just the "go to next" code, no validation is performed.

Check if the number of a textbox is greater than number entered array of textbox's

I am trying to compare value of a single text box value "totalmarkstoall" with multiple array of text box's "marksscored", the below my java script is comparing as well on key up function.
what am unable to do is if the value of "marksscored" that perticuler text box is greater then the "totalmarkstoall" then is shows the pop up :But it should erase the value also or should not allow to enter.
function scorecompare(idval) {
var marksscored = idval;
var totalmarkstoall = document.getElementById("totalmarkstoall").value;
if (parseInt(marksscored) > parseInt(totalmarkstoall))
{
alert("greater than Total Mrks");
} else {
}
}
<input id="totalmarkstoall" type="number" style="border: 1px solid #dbdbdb;" placeholder="Enter Total Marks"></input>
<table>
<tr>
<td>
<input type="text" name="marksscored[]" id="marksscored[0]" value="" onkeyup="scorecompare(this.value);"/>
</td>
</tr>
<tr>
<td>
<input type="text" name="marksscored[]" id="marksscored[1]" value="" onkeyup="scorecompare(this.value);"/>
</td>
</tr>
<tr>
<td>
<input type="text" name="marksscored[]" id="marksscored[2]" value="" onkeyup="scorecompare(this.value);"/>
</td>
</tr>
</table>
If you do something like this you know which inputfield the value came from.
HTML:
<table>
<tr>
<td>
marksscored Array of text box's
</td>
</tr>
<tr>
<td>
<input type="text" name="marksscored[]" id="marksscored[0]" value="" onkeyup="scorecompare(this);">
</td>
</tr>
<tr>
<td>
<input type="text" name="marksscored[]" id="marksscored[1]" value="" onkeyup="scorecompare(this);">
</td>
</tr>
<tr>
<td>
<input type="text" name="marksscored[]" id="marksscored[2]" value="" onkeyup="scorecompare(this);">
</td>
</tr>
</table>
JS:
function scorecompare(idval) {
var marksscored = idval;
var totalmarkstoall = document.getElementById("totalmarkstoall").value;
if (parseInt(marksscored.value) > parseInt(totalmarkstoall))
{
alert("greater then Total Mrks");
//do things with inputfield marksscored
} else {
}
}
Try this. Use keyUp event like this way.
$( ".marksscored" ).keyup(function() {
var marksscored = $(this).val();
var totalmarkstoall = document.getElementById("totalmarkstoall").value;
if (parseInt(marksscored) > parseInt(totalmarkstoall))
{
alert("greater then Total Mrks");
$(this).val("");
} else {
// do something
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input id="totalmarkstoall" type="number" STYLE=" border: 1px solid #dbdbdb;" placeholder="Enter Total Marks"></input>
<table>
<tr>
<td>
<input type="text" class="marksscored" name="marksscored[]" id="marksscored[0]" value="" />
</td>
</tr>
<tr>
<td>
<input type="text" class="marksscored" name="marksscored[]" id="marksscored[1]" value="" />
</td>
</tr>
<tr>
<td>
<input type="text" class="marksscored" name="marksscored[]" id="marksscored[2]" value="" />
</td>
</tr>
</table>
You can do something like this using jquery :
On keyup calculate the sum of all text fields
Check if the is greater than the Total
If it is the case Alert and erase the current text field $(this).val("");
see fiddle
Update:
Fiddle

How to get all text from all textboxes with class txt_Answer

<table id="tb_Answers">
<tbody>
<td>
<input class="txt_Answer" placeholder="Enter Answer">
</td>
<td>
<td colspan="4">
</tr>
</tbody>
<tr>
<td>
<input class="txt_Answer" placeholder="Enter Answer">
</td>
<td>
<td>
</tr>
<tr>
<td>
<input class="txt_Answer" placeholder="Enter Answer">
</td>
</tr>
</table>
I got 3 inputs with answers.How to get all this text/answer by class txt_Answer i tried this
$('*[class="txt_Answer"]').val()
but this returns me only the first value not all of thaem
By iterating and creating an array with $.map :
var values = $.map($('input.txt_Answer'), function(el) {return el.value;});
FIDDLE
You should also validate your HTML, as it's not valid
Try this code which is using the each method :
$('.txt_Answer').each(function() {
text = $(this).val()
alert(text)
})

Categories