How do I compare the values in the text fields with the same data attribute in javascript?
<input type="text" name="a" id="a" data-common="candy" class="loop" value="2">
<input type="text" name="b" id="b" data-common="candy" class="loop" value="3">
<input type="text" name="c" id="c" data-common="ice" class="loop" value="7">
<input type="text" name="d" id="d" data-common="ice" class="loop" value="2">
<input type="text" name="e" id="e" data-common="water" class="loop" value="5">
<input type="text" name="f" id="f" data-common="water" class="loop" value="9">
What I want to do is to determine the higher value on each of the fields with common data attribute. If the common attribute is candy, then the program will compare the values 2 and 3.
My problem is I can't think up of a good algorithm to even start coding. Can you give me an idea? What do I need to do first.
Here you go. The below code will find all the unique data-common attributes with max value.
Working demo
var dataAttributes = {}, attrValue, inputValue, $this;
$('input[data-common]').each(function() {
$this = $(this);
attrValue = $this.attr("data-common");
inputValue = parseInt($this.val());
if(!dataAttributes[attrValue]){
dataAttributes[attrValue] = inputValue;
}
else{
if(dataAttributes[attrValue] < inputValue){
dataAttributes[attrValue] = inputValue;
}
}
});
console.log(dataAttributes);
var datum = "candy";
var maxd = Number.NEGATIVE_INFINITY;;
$('input[data-common="'+datum+'"]').each(function() {
maxd = Math.max(maxd,$(this).val());
});
http://jsfiddle.net/KaUEX/
Well they already answered it, but I did the work so I'm going to post it
var common_values = {},
result = $('#result');
$('[data-common]').each(function(){
var element = $(this),
common_key = element.attr('data-common'),
value = parseInt(element.val(), 10);
if(typeof(common_values[common_key]) === 'undefined'){
common_values[common_key] = [];
}
common_values[common_key].push(value);
});
for(var data in common_values){//or you could find the min, or average or whatever
result.append(data + ': ' + Math.max.apply(Math, common_values[data]) + '<br>');
}
http://jsfiddle.net/dtanders/QKhu7/
Related
I am currently trying to make a calculator using javascript and I have been able to add the what the user will input into textboxes and I am trying to change the value of a variable when a radio is checked. Is there any way to change the value of the variable when the ratio is checked?
Thanks in advance
let firstInput = document.querySelector('#firstInput');
let secondInput = document.querySelector('#secondInput');
let thirdInput = document.querySelector('#thirdInput');
let btnAdd = document.querySelector('button');
let result = document.querySelector('h1');
btnAdd.addEventListener('click', () =>{
let total = parseFloat(firstInput.value) + parseFloat(secondInput.value) +
parseFloat(thirdInput.value) + parseInt(genderReflection);
result.innerText = total.toFixed(3);
});
window.onload = function(){
var genderReflection = {
price: 5
}
var maleRelaxation = document.getElementById('Male');
Male.addEventListener('click' ,function(){
genderReflection.price += parseFloat(maleRelaxation.value)
})
}
<input type="number" id="firstInput">
<div id="calculator">
<input type="radio" id="Male" name="gender" value="5">
<label for="Male">Male</label>
<input type="radio" id="Female" name="gender" value="-161">
<label for="Female">Female</label>
</div>
<input type="number" id="secondInput">
<input type="number" id="thirdInput">
<button>ADD</button>
<h1>result</h1>
You could add an onClick="function_name(amount)" onto the inputs.
Where function name would add the variable to a (globally declared) list.
From there, the logic is yours.
Edit
Ofcourse, adding an eventlistener and getting the attribute as specified in comment above would probably be better. Saves typing. ;)
two errors:
1)place all the js code inside window.onload
2)to get the value out of genderReflection use generReflection.price
window.onload = function(){
let firstInput = document.querySelector('#firstInput');
let secondInput = document.querySelector('#secondInput');
let thirdInput = document.querySelector('#thirdInput');
let btnAdd = document.querySelector('button');
let result = document.querySelector('h1');
btnAdd.addEventListener('click', () =>{
let total = parseFloat(firstInput.value) + parseFloat(secondInput.value) +
parseFloat(thirdInput.value) + parseInt(genderReflection.price);
result.innerText = total.toFixed(3);
});
var genderReflection = {
price: 5
}
var maleRelaxation = document.getElementById('Male');
Male.addEventListener('click' ,function(){
genderReflection.price += parseFloat(maleRelaxation.value)
})
}
<input type="number" id="firstInput">
<div id="calculator">
<input type="radio" id="Male" name="gender" value="15">
<label for="Male">Male</label>
<input type="radio" id="Female" name="gender" value="-161">
<label for="Female">Female</label>
</div>
<input type="number" id="secondInput">
<input type="number" id="thirdInput">
<button>ADD</button>
<h1>result</h1>
I have some range sliders and input fields. From that I'm getting some equations now I want to subtract those dynamic numbers by their ID. Below is the code but I'm getting NaN value. Below the steps, I've done.
Getting #totalavgtime from the multiplication of range slider and .averagetime
Getting #timetoproduce from the multiplication of range slider and .radio-roi next input value.
Now trying to subtract #totalavgtime - #timetoproduce but getting NaN value in #timesaving.
$(document).ready(function() {
$(".range").on("change", function() {
var mult = 0;
$('.range').each(function(i) {
var selector_next = parseInt($(".averagetime:eq(" + i + ")").attr("value"))
mult += parseInt($(this).val()) * selector_next //multply..
console.log($(".averagetime:eq(" + i + ")").attr("value"), $(this).val())
})
$("#totalavgtime").val(mult)
})
});
$(document).ready(function() {
$('.range').on('change', function() {
let n = $(this).attr('id').match(/\d+/g)[0];
let total = 0;
let checkVal = $('.radio-roi:checked').next('input').val();
let multiplyFactor = parseFloat(checkVal);
console.log(multiplyFactor)
$('.range').each(function() {
total += (parseFloat($(this).val()) * multiplyFactor);
});
$('#timetoproduce').value(total);
})
});
$(document).ready(function() {
var txt1 = parseInt(document.getElementById("totalavgtime").value);
var txt2 = parseFloat(document.getElementById("timetoproduce").value);
var res = document.getElementById("timesaving");
Number(txt1);
Number(txt2);
//Substract that
res.value = txt1 - txt2;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input type="radio" id="" class="radio-roi" name="plan" value="plus" checked>
<input type="text" value="2.5" id="actualtime2" class="hiden-actual-time" disabled><br>
<input type="radio" id="" class="radio-roi" name="plan" value="pro">
<input type="text" value="3" id="actualtime3" class="hiden-actual-time" disabled><br>
<input type="text"value="6" id="avgtime-id" class="averagetime"disabled><br>
<input type="range" name="slider-1" min="0" max="12" value="0" step="1" class="range" id="range-slider"><br>
<input type="text"id="totalavgtime" value="" disabled><br>
<input type="text"id="timetoproduce" value="" disabled><br>
<input type="text"id="timesaving" value="" disabled><br>
You can merge both event handler in one as both are triggering same elements . So , inside this on each iteration get value of range slider and add total to same variable and set them in required input . Now , to subtract them check if the value is not null depending on this take value of input else take 0 to avoid NaN error.
Demo Code :
$(document).ready(function() {
$(".range").on("change", function() {
$(this).next().text($(this).val()) //for output(range)
var selector_next_avg = 0;
var timetoproduce = 0
var checkVal = parseFloat($('.radio-roi:checked').next('input').val()); //radio next input
$('.range').each(function(i) {
var selector_next = parseInt($(".averagetime:eq(" + i + ")").val()) //avg..input
selector_next_avg += parseInt($(this).val()) * selector_next;
timetoproduce += (parseFloat($(this).val()) * checkVal);
})
//set both values
$("#totalavgtime").val(selector_next_avg)
$('#timetoproduce').val(timetoproduce);
total() //call to total..(sub)
})
});
function total() {
var txt1 = $("#totalavgtime").val() != "" ? parseFloat($("#totalavgtime").val()) : 0; //if null take 0
var txt2 = $("#timetoproduce").val() != "" ? parseFloat($("#timetoproduce").val()) : 0;
$("#timesaving").val(txt1 - txt2); //set value
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input type="radio" id="" class="radio-roi" name="plan" value="plus" checked>
<input type="text" value="2.5" id="actualtime2" class="hiden-actual-time" disabled><br>
<input type="radio" id="" class="radio-roi" name="plan" value="pro">
<input type="text" value="3" id="actualtime3" class="hiden-actual-time" disabled><br>
<input type="text" value="6" id="avgtime-id" class="averagetime" disabled><br>
<input type="range" name="slider-1" min="0" max="12" value="0" step="1" class="range" id="range-slider"><output></output><br>
<input type="text" id="totalavgtime" value="" disabled><br>
<input type="text" id="timetoproduce" value="" disabled><br>
<input type="text" id="timesaving" value="" disabled><br>
I have a form to calculate the total value from a form but it results in a nan error even though the values of the html inputs is numerical. What am I doing wrong?
function myFunction() {
var y = document.getElementsByName("optradio").value;
var z = document.getElementsByName("extra-hours").value;
var x = +y + +z;
document.getElementById("result").innerHTML = x;
}
<label class="radio-inline">
<input type="radio" name="optradio" value="25">Half day (3hrs)
</label>
<label class="radio-inline">
<input type="radio" name="optradio" value="50">Full day (6hrs)
</label>
<input type="number" value="" min="0" max="6" class="form-control" name="extra-hours">
<button type="button" onclick="myFunction()">Try it</button>
<p id="result"></p>
You must cycle through the radios to get the value. getElementsByName returns multiple elements.
<label class="radio-inline">
<input type="radio" name="optradio" value="25">Half day (3hrs)
</label>
<label class="radio-inline">
<input type="radio" name="optradio" value="50">Full day (6hrs)</label>
<input type="number" value="" min="0" max="6" class="form-control" name="extra-hours">
<button type="button" onclick="myFunction()">Try it</button>
<p id="result"></p>
<script>
function valueOfRadio(name) {
// Get all of the radios by name
var radios = document.getElementsByName(name);
// Go through each one
for (var i = 0, length = radios.length; i < length; i++) {
// If it's checked, lets return it's value
if (radios[i].checked) {
return radios[i].value;
}
}
}
function myFunction() {
// Go get the right radio value
var y = valueOfRadio('optradio');
// Same problem here. Multiple returned, but we know we only have one element so we index to 0.
//You could alternatively use getElementsById for this which will return a single node.
var z = document.getElementsByName("extra-hours")[0].value;
var x = +y + +z;
document.getElementById("result").innerHTML = x;
}
</script>
getElementsByName returns an array and you have to test all the radios to see if they are checked.
Try it:
<label class="radio-inline">
<input type="radio" name="optradio" value="25">Half day (3hrs)
</label><label class="radio-inline"><input type="radio" name="optradio" value="50">Full day (6hrs)</label>
<input type="number" value="" min="0" max="6" class="form-control" id="extra-hours">
<button type="button" onclick="myFunction()">Try it</button>
<p id="result"></p>
<script>
function myFunction() {
var radios = document.getElementsByName("optradio");
var y = 0;
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
y += +radios[i].value;
}
}
var z = document.getElementById("extra-hours").value;
var x = +y + +z;
document.getElementById("result").innerHTML = x;
}
</script>
Actually getElementsByName returns array of elements with the name given, name optradio is allocated for 2 radio buttons, so you need to do like this
function myFunction() {
var radioarray = document.getElementsByName("optradio");
var y;
for (var i = 0; i < radioarray.length; i++) {
if (radioarray[i].checked) {
y = radioarray[i].value;
}
}
var z = document.getElementsByName("extra-hours")[0].value;
var x = +y + +z;
document.getElementById("result").innerHTML = x;
}
<label class="radio-inline">
<input type="radio" name="optradio" value="25">Half day (3hrs)
</label>
<label class="radio-inline">
<input type="radio" name="optradio" value="50">Full day (6hrs)
</label>
<input type="number" value="" min="0" max="6" class="form-control" name="extra-hours">
<button type="button" onclick="myFunction()">Try it</button>
<p id="result"></p>
Here is an example using a select instead of radio buttons, and it looks a little more compact and clean. I also used jQUery instead of plain Javascript because the code is a lot cleaner.
function myFunction() {
var result = parseInt($("[name=optradio]").val()) + parseInt($("[name=extra-hours]").val());
$("#result").text(result);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="optradio">
<option value="25">Half day (3hrs)
<option value="50">Full day (6hrs)
</select>
<input type="number" value="0" min="0" max="6" class="form-control" name="extra-hours">
<button type="button" onclick="myFunction()">Try it</button>
<p id="result"></p>
document.getElementsByName("...")
returns a node list, not an individual node. You should use an id to select just a single node (preferred). That is
var y = document.getElementById("optradio").value
var z = document.getElementById("extra-hours").value
The properties "name" and "id" have different meanings, so make sure you use the one you actually mean.
If you want a unique identifier, use "id", if you want to group a selection of your DOM elements, use "name".
Additionally, the value for the radio button is always the same, you need to apply it conditionally based on the 'selected' property.
function myFunction() {
var half = document.getElementById("half");
var full = document.getElementById("full");
var y = half.checked ? half.value : full.value;
var z = document.getElementById("extra-hours").value;
var x = +y + +z;
document.getElementById("result").innerHTML = x;
}
<label class="radio-inline">
<input type="radio" name="optradio" id="half" value="25" checked>Half day (3hrs)
<input type="radio" name="optradio" id="full" value="50">Full day (6hrs)
</label>
<input type="number" value="" min="0" max="6" class="form-control" id="extra-hours">
<button type="button" onclick="myFunction()">Try it</button>
<p id="result"></p>
Finally, although I'm not going to show it, you're probably best learning jQuery now; everything else uses jQuery. Everyone uses jQuery because it's better than base javascript. As Christian Juth showed in his answer, you probably want to make it a selection box, too.
So i have a dynamic input field came from append with different class name and names, i want to check each of input field value already exist or duplicate.
This would look like
The first criteria_name is default and the others are appendend.
<input type="text" name="criteria_name" class="criteria_name">
<input type="text" name="criteria_name2" class="criteria_name2">
<input type="text" name="criteria_name3" class="criteria_name3">
<input type="text" name="criteria_name4" class="criteria_name4">
<input type="text" name="criteria_name5" class="criteria_name5">
I am trying to check each one of those if there is no duplicated else proceed.
var critname_arr = [];
var input_check;
var crit_name_of_first = $('input.criteriaNames').val();
var acappended = append_crit_header+1;
var count_to = 0;
for(var ab = 2; ab<=acappended; ab++){
var crit_arr;
if(crit_name_of_first == $('input.criteria_each_name'+ab+'').val()){
alert("Criteria cannot be duplicate");
return false;
}else{
input_check = $('input.criteria_each_name'+ab);
input_check.each(function(){
crit_arr = $.trim($(this).val());
});
critname_arr.push(crit_arr);
}
if($('input.criteria_each_name'+ab+'').val() == critname_arr[count_to]){
alert('criteria cannot be duplicate');
return false;
}
count_to++;
}
console.log(critname_arr);
Here is just an example of how you can do it. In the fiddle change one of the values to one that is already in another field (make a duplicate value) to see it do something. If there are no duplicates, it will not do anything. Click the "Button" text to run the duplicate check:
jsFiddle: https://jsfiddle.net/o52gjj0u/
<script>
$(document).ready(function(){
$('.ter').click(function(e) {
var stored = [];
var inputs = $('.criteria_name');
$.each(inputs,function(k,v){
var getVal = $(v).val();
if(stored.indexOf(getVal) != -1)
$(v).fadeOut();
else
stored.push($(v).val());
});
});
});
</script>
<!-- Just use an array name for the input name and same class name as well -->
<div class="ter">Button</div>
<input type="text" name="criteria_name[]" class="criteria_name" value="1" />
<input type="text" name="criteria_name[]" class="criteria_name" value="2" />
<input type="text" name="criteria_name[]" class="criteria_name" value="3" />
<input type="text" name="criteria_name[]" class="criteria_name" value="4" />
<input type="text" name="criteria_name[]" class="criteria_name" value="5" />
How do I use javascript or jquery to find a sum and product of number values that users enter into my forms fields. Thanks for your time and help.
Input 1 Value + Input 2 Value = Input A
Input A Value * .08 = Input B Value
Input A Value + Input B Value = Total Input
<form>
<input type="text" id="1" name="1">
<input type="hidden" id="2" name="2" value="33">
<input type="text" id="A" name="A">
<input type="text" id="B" name="B">
<input type="text" id="total" name="total">
<button type="button" id="button" name="button">
</form>
WHAT IVE TRIED
<script>
var $form = $('#contactForm'),
$summands = $form.find('.sum1'),
$sumDisplay = $('#itmttl');
$form.delegate('.sum1', 'change', function ()
{
var sum = 0;
$summands.each(function ()
{
var value = Number($(this).val());
if (!isNaN(value)) sum += value;
});
$sumDisplay.val(sum);
});
</script>
<script>
function multiply(one, two) {
if(one && two){
this.form.elements.tax.value = one * two;
} else {
this.style.color='blue';
}
}
</script>
Please find Fiddle link
JSFiddle
$(document).ready(function(){
$('#calculate').on('click',function(){
var v1 = $('#1').val(); // take first text box value
var v2 = $('#2').val(); // take second hidden text box value
$('#A').val(parseInt(v1)+parseInt(v2)); // set value of A
var aval = (parseInt($('#A').val()) * parseFloat(.8)); // calculate value of b
$('#B').val(aval);// set value of B
var totalval = parseInt($('#A').val()) + parseFloat(aval);
//calculate value for total
$("#total").val(totalval); // set total
})
});
I assume you want to update the fields when you lick the button? Created a snippet instead of a fiddle:
$("#button").click(function() {
$("#A").val( parseInt($("#1").val()) + parseInt($("#2").val()) );
$("#B").val(parseInt($("#A").val()) * .8);
$("#total").val( parseInt($("#A").val()) + parseInt($("#B").val()) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="1" name="1">
<input type="hidden" id="2" name="2" value="33">
<input type="text" id="A" name="A">
<input type="text" id="B" name="B">
<input type="text" id="total" name="total">
<button type="button" id="button" name="button">
</form>