Question

I have a form with a drop down selection and a text field. If option 1 is selected in the dropdown, I need the number to be to 2 decimal places, but if option 2 is selected in the dropdown, I need the number to be rounded with no decimals. I think this can be achieved with JQuery. Please can someone help?

Thanks in advance!

----EDIT----

At the moment I am using

$('#form').change(function() {
    if ($('#options').val()=='1') {
        $('#text1_1').css("display","");
        $('#text1_2').css("display","none");
        $('#text2_1').css("display","");
        $('#text2_2').css("display","none");
    } else{
        $('#text1_1').css("display","none");
        $('#text1_2').css("display","");
        $('#text2_1').css("display","none");
        $('#text2_2').css("display","");
    }

This shows the appropriately formatted inputs relevant to what is selected, but I'm sure there is a cleaner way of doing it.

Was it helpful?

Solution

As per my understanding, I think that you want something like.

var fomate_value = function(selected_option_value, number){
  var formated_number = 0;
  if(selected_option_value == 1){
    formated_number = parseFloat(number).toFixed(2);
  }else{
    formated_number = Math.round(number);
  }
  return formated_number;
}

jQuery("pass_id of class").bind('change', function(){
  var option_value = $(this).val();
  var number = 100.45; /*for ex 110.45, put code or actual number*/;
  var formated_number = fomate_value(option_value, number);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top