I have a site generated mainly in PHP. On one page PHP generates a number of dropdowns, the number of which is depending on items in my DB.
The number of dropdowns can change but I want to be able to count them and get the values for each of them in JS/jQuery.
At the moment the dropdowns all have the same class name but I think I'm going to have to try give them all individual IDs.
I know I could the amount of items like this:
var ammount = $(".myclass").length;
I just need some way of looping through these to get the individual values like this, without just picking up the first value of that class each time:
var input =$(".myclass").value;
I think I'm going to have to go with individual IDs being generated by the PHP but was just wondering if there was another way to do it.
$(".myclass").each(function(i,e) {
console.log(e); //e gives you current item in loop
});
or
$(".myclass").each(function() {
console.log($(this).value);
});
You can get the values in an array, by iterating over all these elements and pushing their values to the array:
var vals = [];
$(".myclass").each(function() {
vals.push($(this).val());
});
If you want to get the sum of all these inputs :
var sum = vals.reduce((a,b) => (+a + +b));
Demo:
var vals = [];
$(".myclass").each(function() {
vals.push($(this).val());
});
console.log(vals);
//Calculating sum of values
var sum = vals.reduce((a,b) => (+a + +b));
console.log(sum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="myclass" value="10" />
<br/>
<input type="text" class="myclass" value="20" />
<br/>
<input type="text" class="myclass" value="30" />
<br/>
<input type="text" class="myclass" value="40" />
<br/>
<input type="text" class="myclass" value="50" />
<br/>
Related
Im trying to delete duplicates of htmlcollections. Basically they are htmlcollection of input checkboxes with attributes name and value. I want to remove the entire <input> if the name and value are the same.
I couldn't find similar questions in stackoverflow. But what I have so far is to convert the htmlcollections first into array using
var arr = Array.from(htmlCollection);
and then use a Set to remove the duplicates, then convert it back to htmlCollection. This is way too long. Is there another way to do this?
EDIT: Just made a function undDeal to deal with elements that won't have a value AND OR a name
let removeDuplicates=(elem)=>{
let obj={} //for holding data for checking later
//below function for handling elements without a name AND OR value
//(so that <input name="undefined" value="1" /> isn't seen as <input value="1" />)
let undDeal=(val1,val2)=>{
if(val1==undefined){
if(val2==undefined){return Symbol.iterator}
return Symbol.match
}
return val1+val2
}
let elems=[...elem.children]
let check=(el)=>{
let specs=()=>undDeal(el.name,el.value)
if(obj[specs()]){return true}
obj[specs()]=1; return false
}
for(let i=0;i<elems.length;i++){
if(check(elems[i])){elem.removeChild(elems[i])}
}
}
removeDuplicates(document.body)
<body>
<input name="asdf1" value="1" />
<input name="asdf2" value="2" />
<input name="asdf1" value="2" />
<input name="asdf2" value="2" />
<input name="asdf2" value="1" />
</body>
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 am working in ASP.NET Project.My task is to Prevent the repative values occured in Textbox.Textbox is bound with autocomplete and appending text from checkboxlist as like in the below picture
! https://drive.google.com/file/d/0B5OPwgmPG6QpTHBTdVlFaldRaEE/view?usp=sharing
After i appended the content from checkbox list to textbox means it is repeating value,if i typed it inital time it won't.And my task is to show unique values based on the textbox content.
My project files are in the below link..please help me out guys
https://drive.google.com/file/d/0B5OPwgmPG6QpS3NMNElGN2k4RzQ/view?usp=sharing
Based on my answer I gave you in the other thread (https://stackoverflow.com/a/28828842/4569271) I extended my solution to only display unique values:
$(function() {
$('input[type="checkbox"]').change(function() {
// Reset output:
$("#output").html('');
// remeber all unique values in this array:
var tmpArray = new Array();
// Repeat for all checked checkboxes:
var checkboxes = $('input[type="checkbox"]:checked').each(function() {
// Get value from checkbox:
var textToAppend = $(this).val();
// Check if value from checkbox was added already:
if (jQuery.inArray(textToAppend, tmpArray) == -1) {
// add entry to array so it will be not added again:
tmpArray.push(textToAppend);
var existingText = $("#output").html();
// Append seperator (';') if neccessary:
if (existingText != '') {
existingText = existingText + ";";
}
// Print out append value:
$("#output").html(existingText + textToAppend);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Select:</h2>
<input type="checkbox" value="Jan" />Jan
<input type="checkbox" value="Jan" />Jan
<input type="checkbox" value="Jan" />Jan
<input type="checkbox" value="Feb" />Feb
<input type="checkbox" value="Feb" />Feb
<input type="checkbox" value="Feb" />Feb
<input type="checkbox" value="Mar" />Mar
<input type="checkbox" value="Mar" />Mar
<input type="checkbox" value="Mar" />Mar
<h2>Output:</h2>
<div id="output"></div>
Based on your description, I am not sure if this is the solution you were looking for? But maybe it helps.
I have the following series of checkboxes coming from the datatables in the form like below:
<input id="list-chk_1" type="checkbox" />
<input id="list-chk_2" type="checkbox" />
<input id="list-chk_3" type="checkbox" />
How can I separate that id from list-chk. Do I have to include data-id parameter?
As per my understanding, Try that
$('input[id^="list-chk"]').click(function(){
$(this).attr("id"); //Getting click control ID
$(this).val(); //Getting Value
});
You can use split if you know the ID always has that format.
var ins = document.getElementsByTagName('input');
for (var i = 0; i < ins.length; i++) {
document.write(ins[i].id.split('_')[1]);
}
// jQuery
$('input').each(function() {
$('body').append(this.id.split('_')[1]);
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="list-chk_1" type="checkbox" />
<input id="list-chk_2" type="checkbox" />
<input id="list-chk_3" type="checkbox" />
Split will make an array from the given string, splitting it where you tell it to.
"list-chk_1".split('_') // results in ["list-chk", "1"]
Other methods could be using var idnr = this.id.replace('list-chk_', '');
<html>
<head>
<title>Tip Calculator</title>
<script type="text/javascript"><!--
function calculateBill(){
var check = document.getElementById("check").value;
/* I try to get the value selected */
var tipPercent = document.getElementById("tipPercent").value;
/* But it always returns the value 15 */
var tip = check * (tipPercent / 100)
var bill = 1 * check + tip;
document.getElementById('bill').innerHTML = bill;
}
--></script>
</head>
<body>
<h1 style="text-align:center">Tip Calculator</h1>
<form id="f1" name="f1">
Average Service: 15%
<input type="radio" id="tipPercent" name="tipPercent" value="15" />
<br />
Excellent Service: 20%
<input type="radio" id="tipPercent" name="tipPercent" value="20" />
<br /><br />
<label>Check Amount</label>
<input type="text" id="check" size="10" />
<input type="button" onclick="calculateBill()" value="Calculate" />
</form>
<br />
Total Bill: <p id="bill"></p>
</body>
</html>
I try to get the value selected with document.getElementById("tipPercent").value, but it always returns the value 15.
In HTML, Ids are unique. Try changing the id attributes to tipPercent1, tipPercent2, etc.
Both radio buttons have the same ID - this is incorrect in HTML, as IDs should be unique. The consequence is that document.getElementById cannot be used.
Try document.getElementsByName and loop through the resulting array to find out which one is checked and what its value is.
<input type="radio" id="tipPercent" name="tipPercent" value="15" />
<input type="radio" id="tipPercent" name="tipPercent" value="20" />
First of all, id's are required to be unique identifiers, so giving two elements the same id will make problems. document.getElementById("tipPercent") after all tries to get one element, so which of those two different input elements should it return?
Second, you can only check if a radio input is checked or not, so you will need to loop through all those inpud fields and check which one is checked to get the current value.
You have two equal ids "tipPercent". getElementById returns only one first result
You should use different ids for each radio. Try something like follows:
<script type="text/javascript">
//a variable that will hold the index number of the selected radio button
for (i=0;i<document.f1.tipPercent.length;i++){
if (document.document.f1.tipPercent[i].checked==true)
var tipPercent= document.f1.tipPercent[i].value;
}
</script>
You may want to change the calculateBill() function with the following:
function calculateBill() {
var tipPercent = 0;
var check = document.getElementById("check").value;
var radioElements = document.getElementsByName("tipPercent");
for (var i = 0; i < radioElements.length; i++) {
if (radioElements[i].checked)
tipPercent = parseInt(radioElements[i].value);
}
var tip = check * (tipPercent / 100)
var bill = 1 * check + tip;
document.getElementById('bill').innerHTML = bill;
}
Note the use of document.getElementsByName(), as Oded suggested in another answer.
You should also remove the id attribute from your radio buttions:
<input type="radio" name="tipPercent" value="15" />
<input type="radio" name="tipPercent" value="20" />
The following is a screenshot showing that the above function works fine with the 20% radio button:
How can I read the value of a radio button in JavaScript? http://img695.imageshack.us/img695/6214/tipcalc.png
The id of an element has to be unique, so you can't have two elements with the same id.
When you try to get all radio buttons as a single element, you will get one of them. Which one you get is entirely up to how the browser choose to handle the incorrect id's that you have set. You could get either of the elements, or null, depending on the implementation. In this case you happen to use a browser that gets the first element.
Give the elements their own id:
Average Sevice: 15%<input type="radio" id="tipPercent15" name="tipPercent" value="15" />
<br />
Excellent Sevice: 20%<input type="radio" id="tipPercent20" name="tipPercent" value="20" />
Getting the value attribute from the element will only get the value that you have specified for each of them. Instead you used the checked attribute:
var tipPercent;
if (document.getElementById("tipPercent15").checked) tipPercent = 15;
if (document.getElementById("tipPercent20").checked) tipPercent = 20;