Change values according to selected option

Asked

Viewed 257 times

1

I have a table of plans here, and in it I had 5 columns, for 5 planes obviously.

In each column there is a select to choose the periodicity of each plan.

According to the option selected in this select, it must change the value that is being displayed for the plan.

I tried to start a script but couldn’t get it to work as needed.

I’ll leave the full code below:

JAVASCRIPT:

<script>
$(function() {
  // PLANO BÁSICO US
  // preciso usar o str_replace por que o valor é obtido através de uma variável PHP
  var plano_basicoUS = {
    1: <? echo str_replace(',', '.', 11,90); ?>,
    2: <? echo str_replace(',', '.', 32,70); ?>,
    3: <? echo str_replace(',', '.', 59,40); ?>,
    4: <? echo str_replace(',', '.', 106,80); ?>,
 };


  $("#periodicidadeBasicoUS").on('change', function() {

    var periodo = this;
    var escolha = $(this).val();
    var multiplicar = $(this).find(':selected').data('multiplicar');

    $.each($('.periodo-item'), function(key, value) {
      var plano = $(value).data('plano');
      var preco = plano_basicoUS[1] * multiplicar;

      $(value).find('.valor_original').text('R$ '+preco);
      $(value).find('.valor_desconto').text('R$ '+plano_basicoUS[2]);
      $(value).find('.valor_mensal').text(plano_basicoUS[1]);

    });

  });

  $("#periodicidadeBasicoUS").trigger('change');


});
</script>

HTML:

<br>
<div class="periodo-item" data-plano="1">
    <span class="valor_original"></span> <span class="valor_desconto"></span>
    <br>
    <span class="valor_mensal"></span>
</div>

    <div class="select">
        <select name="periodicidadeBasicoUS" id="periodicidadeBasicoUS">
          <option value="1">Mensal - Sem desconto</option>
          <option data-multiplicar="3" value="2">Trimestral - </option>
          <option data-multiplicar="6" value="3">Semestral - </option>
          <option data-multiplicar="12" value="4">Anual - </option>
        </select>
      </div>

I need him to do the following:

  1. Return the values with comma instead of point, ex: R$ 11,90.
  2. If selected the option with value 1 (monthly) it must show any text in span classy: original value and value_discount and to the class monthly value would be the value of plano_basicoUS[1], for the other options the normal numerical values will be displayed.

How should I adjust the script?

Since there are several plans, if anyone knows how to simplify this code would be interesting, as I will need to repeat all the code for the next plan.

  • Note that you are not saving the data you are pulling from PHP in an array, but in a javascript object. That’s probably why it’s not printing when you use it plano_basicoUS[1]

  • He’s printing, only he’s showing it with a dot and no zero at the end.

  • Yes, I realized only after you had the correct object indicies... Is the data type entering str_replace really a string? Note that without the quotes, you are passing a number. Also, the order of the parameters is changed. It should be echo str_replace('.', ',', "11.90"); https://ideone.com/JqB4FD

  • So, in PHP it returns the value with comma, then as JS does not do the multiplication with comma I needed to use str_replace to convert with dot. $basicoUS_mensal > 11,90

  • I understand. Now come on. Do you get the PHP string already formatted and want to do the operation? You would have to use parseFloat in this case. You cannot multiply a string by a number for example. It would look something like this: parseFloat(<?echo str_replace(',', '.', "11,90");?>). That’ll give you the real number 11.9 in JS and will allow you to perform operations with it. Then, to print you would need to format to the way you want the final value to be printed.

  • Yes, I get the string already formatted with comma. I think it was you who helped me in the other question right? https://answall.com/questions/306283/motrar-valor-de-file-get-contents-mas-somente-o-que-esta-entre-aspas/306309#306309

  • Right, I would suggest you, if possible, to change the comma to a point, if possible, already in the PHP file that returns this data to you, and in javascript just use parseFloat() so you can do math operations using this value and then format it so you can print it as you want.

  • And how can I format the value that is printed by js?

  • Then you would have to create a function that formats that number. Example: https://ideone.com/vEFRoQ

Show 4 more comments

1 answer

2


Use a ternary to show only text in the first divs when the value of select is not 1.

The ternary has this structure:

condição ? valor se for verdadeira : valor se for falsa

Would apply here:

$(value)
.find('.valor_original')
.text(escolha != 1 ? 'R$ '+preco.toFixed(2).replace(".",",") : '');
            ↑                      ↑                           ↑
//      condição          se for verdadeira,             se for falsa,
//                     insere o texto com o valor           esvazia

To format the values, you use .toFixed(2).replace(".",",") (2 decimal places and replace the point with the comma).

Behold:

$(function() {
  // PLANO BÁSICO US
  // preciso usar o str_replace por que o valor é obtido através de uma variável PHP
  var plano_basicoUS = {
    1: 11.90,
    2: 32.70,
    3: 59.40,
    4: 106.80,
 };


  $("#periodicidadeBasicoUS").on('change', function() {

    var periodo = this;
    var escolha = $(this).val();
    var multiplicar = $(this).find(':selected').data('multiplicar');

    $.each($('.periodo-item'), function(key, value) {
      var plano = $(value).data('plano');
      var preco = plano_basicoUS[1] * multiplicar;
      
      $(value).find('.valor_original').text(escolha != 1 ? 'R$ '+preco.toFixed(2).replace(".",",") : ''); // ternário
      $(value).find('.valor_desconto').text(escolha != 1 ? 'R$ '+plano_basicoUS[2].toFixed(2).replace(".",",") : '');  // ternário
      $(value).find('.valor_mensal').text(plano_basicoUS[1].toFixed(2).replace(".",","));

    });

  });

  $("#periodicidadeBasicoUS").trigger('change');


});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="periodo-item" data-plano="1">
    <span class="valor_original"></span> <span class="valor_desconto"></span>
    <br>
    <span class="valor_mensal"></span>
</div>

<div class="select">
  <select name="periodicidadeBasicoUS" id="periodicidadeBasicoUS">
    <option value="1">Mensal - Sem desconto</option>
    <option data-multiplicar="3" value="2">Trimestral - </option>
    <option data-multiplicar="6" value="3">Semestral - </option>
    <option data-multiplicar="12" value="4">Anual - </option>
  </select>
</div>

  • Very good indeed, but I was in doubt on the following: The first value of valor_original appears correctly because it should only multiply the value of plano_basicoUS[1], however the valor_desconto is not being changed according to the selected option. Each option has a different value. The other question is how do I change the text that is displayed when option 1 is selected?

  • Perfect, I managed to solve. I forgot a detail, I need that in the monthly value, it displays the value of a division, I tried to do the following: var equivalente = preco / multiplicar; $(value).find('.valor_mensal').text(escolha != 1 ? equivalente.toFixed(2).replace(".",",") : plano_basicoUS[escolha].toFixed(2).replace(".",","));. What did I do wrong? It didn’t work.

  • I was able to adjust!

  • One more question, it is possible to put a <strike></strike> at the printed value in value_discount? I tried here and could not apply this css property. Or it could be text-Decoration:line-through instead of strike.

  • Correcting would be for the value printed in: original value, being only for the numeric value.

  • Yes, already ta thus, the problem is that when it is selected the first option it will display the text, and in the text can not be crossed out.

  • No, you put that on JS: $(value).find('.valor_original').text(escolha != 1 ? 'R$ '+preco.toFixed(2).replace(".",",") : '<span class="strike">texto aqui</span>'); // ternário

  • So it would have to be the other way around, the text can’t be crossed out, I need only the numerical value to be crossed out. I can put the first part inside the quotes tbm?

  • Sorry for my lack of knowledge, I tried the following but it didn’t work: $(value).find('.valor_original').text(escolha != 1 ? '<span class="strike">R$ '+preco.toFixed(2).replace(".",",")'</span>' : 'Altere a');

  • Missed the + to concatenate: $(value).find('.valor_original').text(escolha != 1 ? '<span class="strike">R$ '+preco.toFixed(2).replace(".",",")+'</span>' : 'Altere a');

  • I had tried too, but he printed the span, did not understand as html.

  • Printed exactly this way: <span class="strike">R$ 35,70</span> R$ 32,70

  • ah tah.. forgot... exchange text for html

  • Jeez, now yes, 100%! One last question, last even kk, would you have any way to simplify the code so you don’t have to repeat all the code for each plan? Why in the example the var plano_basicoUS = refers to the foreground, and there are more than 10, which will be under other names, ex: var plano_proUS =

  • can help me adjust the replace to put the point in thousand, ex: 1,000.00

Show 11 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.