i have this script and it works. when radio button value is "" than 0 eur and when != value "" than 3.57.
<script>
$(":radio").on("change", function(){
var total = 0;
$(":radio:checked").each(function(){
if(this.value != 0){
total = Number(3.57);
}
});
$("#total").text(total);
});
</script>
this is the html output:
<span id="total" style="color: red;">0</span>
but how can i output it in format X,XX? i get X.XXXXXXXXXXX
CodePudding user response:
This is a very very simple solution that will take the Number
and will call on it the function toFixed(2)
to have a string representation with 2 fixed digits after the decimal separator (also when not needed, eg.: 1,00
) and will replace the decimal separator with comma.
I added some extra things like labels, styles and better dealt with the currently changed value inside the event handler instead of fetching all the radio buttons existing in the page. Anyway this details was not clearly covered in the question so I made some assumptions.
edit: After reading your comment I also added a select element that will behave like the radio buttons, showing the result in the output target as the radio buttons did on change.
$(":radio").on("change", function() {
//target value is the value of the element triggering the event
//!warning.. it gets fetched as string (if you meant to have it as number you shoud use parseInt or parseFloat)
const targetValue = $(this).val();
showOutput(targetValue);
});
$("select").on("change", function() {
//target value is the value of the element triggering the event
//!warning.. it gets fetched as string (if you meant to have it as number you shoud use parseInt or parseFloat)
const targetValue = $(this).find('option:selected').val();
showOutput(targetValue);
});
function showOutput(value){
var total = 0;
//if the currently changing radio option has value != 0 (only the first radio option has value == 0 and they all belong to the same group)
if ( value != 0 ){
total = Number(3.574545);
}
//here it serializes the number to string using 2 digits after decimal separator and will replace that with comma
totalToString = total.toFixed(2).replace('.', ',');
//updates the content in #total with the computed totalToString
$("#total").text(totalToString);
}
input[type=radio]{
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="v0">Value: 0</label>
<input id="v0" type="radio" name="group" value="0">
<br>
<label for="v1">Value: 1</label>
<input id="v1" type="radio" name="group" value="1">
<br>
<label for="v2">Value: 2</label>
<input id="v2" type="radio" name="group" value="2">
<br>
<select>
<option value="0">Value: 0</option>
<option value="1">Value: 1</option>
<option value="2">Value: 2</option>
</select>
<br>
<span id="total" style="color: red;">0</span>