Multiply select by radiobutton

Asked

Viewed 730 times

2

We have a radio button with three different values and a select box with several different values, as I could do to multiply the radiobutton checked with the value of the select box and put the result in a field?

Radiobutton code:

 <input required="required" value="1" name="diarias" id="diaria1"  type="radio"><label
  for="diaria">Uma diaria</label>
<input required="required"  value="2" name="diarias" id="diaria2" type="radio"><label
  for="diaria">Duas diarias</label>
<input required="required"  value="3" name="diarias" id="diaria3" type="radio"><label
  for="diaria">Três diarias</label><br>

Code of the select box:

<select name="cidade" id="cidade" onclick="calcularopcoes();">
            <option name="nenhum" value=""> Escolher </option>
            <option name="saopaulo" value="244.00"> São Paulo </option>
            <option name="fortaleza" value="412.80"> Fortaleza </option>
            <option name="Blumenau" value="412.80"> Blumenau </option>
            <option name="riopreto" value="400.90"> Rio Preto </option>
            </select>

And the Javascript I tried to do but it didn’t work.

  `<script type="text/javascript">
            function calcularopcoes(){if(document.getElementById("ajudacusto").value.length < 0){
                    alert('Por favor, deve se        escolher uma opção');
                    document.getElementById("ajudacusto").focus();
                    return false
                    }
                if(document.getElementByName("diarias").value.length < 0){
                    alert('Por favor, deve se escolher uma opção');
                    document.getElementByName("diarias").focus();
                    return false
                    }


                // vamos obter o elemento select
            var elem = document.getElementById("cidade");    
            var elem2 = document.getElementByName("diarias");
            var selecionou = elem.options[elem.options.selectedIndex]*1 * elem2.options[elem2.options.selectedIndex]*1;
            // passa opção selecionada para campo
            document.getElementById("ajudacusto").value = selecionou.value;
    }  
   </script>`

What better way can we do it? That the user click on the journal and choose the city he does the multiplication calculation automatically and deposit in the field?

  • Some HTML is missing. If you can join as well. Do this with pure javascript or is OK with a library?

  • All this in a form, how so missing some html? Can be with library yes.

  • @Jorgeb. I think the other question should be duplicated of this, and not the other way around, because: 1) This question here was created before; 2) This question here has an accepted answer, the other does not. PS: I didn’t even read the contents of both, I only made one will note if they are even duplicated.

  • I think it’s not duplicate because here the goal is just to multiply while in the other question the goal is to change the values of the attributes according to the selection as well.

  • Okay, I just thought they looked alike, so I made the suggestion. Nice discussion for the finish line. When a new problem is found in the same code, edit or create new topic?

  • 1

    Beware of the chameleon questions.

Show 2 more comments

2 answers

2

There are some problems with your code:

  1. document.getElementByName does not exist. As your own code demonstrates, there may be more than one element with the same name. Replace the test with getElementsByName (Elements, in the plural):

    var diarias = document.getElementsByName("diarias");
    for ( var i = 0 ; i < diarias.length ; i++ ) { ... }
    
  2. To see if a radio button is selected, use the property checked:

    var selecionado = null;
    var diarias = document.getElementsByName("diarias");
    for ( var i = 0 ; i < diarias.length ; i++ )
        if ( diarias[i].checked )
            selecionado = diarias[i];
    if(!selecionado){
        alert('Por favor, deve se escolher uma opção');
        ...
    }
    
  3. You’re trying to multiply elements instead of multiplying their values:

    var selecionou = elem.options[elem.options.selectedIndex]*1 * elem2.options[elem2.options.selectedIndex]*1;
    

    Use values instead (using variable selecionado previously created):

     var elem2 = selecionado;
    var selecionou = elem.options[elem.options.selectedIndex].value * elem2.value;
    // passa opção selecionada para campo
    document.getElementById("ajudacusto").value = selecionou;
    

Example in jsFiddle.

P.S. Are you using floating point to represent money? This is not a good idea, see what happens when choosing "three daily in Rio Preto". These rounding errors can be "hidden" using the function toFixed value (causes it to be printed with a fixed number of decimal places), but you also need to be careful with the rest of the code.

document.getElementById("ajudacusto").value = selecionou.toFixed(2);

Updated example.

  • Good answer :) +1

  • I just realized that we don’t have a "canonical question" about how to represent money in Javascript... I opened a new question about that

  • 1

    Interesting toFixed because in addition to limiting to two decimals (as is the money) is aesthetically better because if the result is 100 for example instead of appearing 100 it shows 100.00. What makes me think of something else, I have a field type float the user can enter the money both with point (that the database accepts) both with comma (that the database does not accept and cuts the cents), do you have any PHP or JS function to handle this information correctly? But this I can then search/ask, even so, thanks because one answer completed the other.

  • 2

    @Vinicius, you can launder the money like this: function lavarDinheiro(valor){ return ('' + valor).replace(/,/g, '.')} hehe, this is replacing virgular by stitches :) mgibsonr: good new question you launched :)

1


Vinicius, here’s a suggestion:

window.onload = function () {
    var inputs = document.querySelectorAll("[name=diarias], select");
    for (var i = 0; i < inputs.length; i++) {
        inputs[i].addEventListener('click', calcularopcoes);
    }
}

function calcularopcoes() {
    var diarias = document.querySelectorAll("[name=diarias]"); // pegar em todas as checkbox
    var escolhida = false; // criar uma flag
    for (var i = 0; i < diarias.length; i++) { // percorre-las uma a uma
        if (diarias[i].checked) escolhida = diarias[i]; // se alguma estiver escolhida a flag passa a "true"
    }
    if (!escolhida) { // se nenhuma estiver escolhida lançar o alert
        alert('Por favor, deve se escolher uma opção');
        document.querySelector("[name=diarias]").focus();
        return false
    }


    // vamos obter o elemento select
    var elem = document.getElementById("cidade");
    var selecionou = elem.options[elem.options.selectedIndex].value;
    // passa opção selecionada para campo
    var valorFinal = selecionou * escolhida.value; // escolhida está em cache, é só ir buscar o valor (.value)
    document.getElementById("ajudacusto").value = valorFinal ;
}

Example

Another example, with jQuery: http://jsfiddle.net/LGpDT/3/
Another example, with Mootools: http://jsfiddle.net/LGpDT/4/

In the first part next to each checkbox and select an Event Listener to run its function every click ( so you can take the onclick of your HTML)

  • 1

    Dude, the code is way different than I thought, I swear I still can’t get used to javascript... In any case, I will test here I answer you. Thanks :) This javascript goes last or goes in the <head tag>?

  • @Vinicius, you can go to the head tag, if you go to the end you can take out the window.onload and leave only what is inside

  • 1

    Very interesting this querySelectorAll! I don’t usually work with pure Javascript, so I’m not familiar with the facilities the API offers.

  • 1

    It worked totally, still improving added toFixed() from @mgibsonbr’s reply to show only 2 houses after the comma. Thank you very much.

Browser other questions tagged

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