2011-11-11 19 views
15

He intentado actualizar el precio total cuando alguien cambia la opción de seleccionar. Aquí está el elemento de selección que estoy usando:¿Por qué no funciona mi sentencia CoffeeScript if/else?

<select id="payment_talks_purchased" name="payment[talks_purchased]"> 
    <option value="1">One</option> 
    <option value="2">Three</option> 
</select> 

Este es el jQuery que estoy usando:

jQuery(document).ready(function() { 
    var price = $(".total-price span.price") 
    var save = $(".savings") 
    $("#payment_talks_purchased").change(function() { 
    var selection = $("#payment_talks_purchased").val() 
    if (selection == 2) { 
     price.html("$12"); 
     save.css("visibility", "visible"); 
    } else if (selection == 1) { 
     price.html("$5"); 
     save.css("visibility", "hidden"); 
    } 
    }); 
}); 

Funciona perfectamente. Cambia el precio a $ 12 y muestra el mensaje de descuento. Si cambio la opción de selección a One/1, cambia el texto a $ 5 y elimina el mensaje de descuento.

Lo convertí en CoffeeScript pero solo funciona cuando hago el primer cambio. El precio esta actualizado Sin embargo, cuando trato de volver a cambiarlo a la opción 1, no se actualiza.

jQuery -> 
    price = $(".total-price span.price") 
    save = $(".savings") 
    select = $("#payment_talks_purchased") 
    select.change -> 
    selection = select.val() 
    if selection = 2 
     price.html "$12" 
     return save.css "visibility", "visible" 
    else if selection = 1 
     price.html "$5" 
     return save.css "visibility", "hidden" 

He estado trabajando en esto durante horas y estoy en mi ingenio. Cualquier ayuda sería muy apreciada.

Respuesta

26

Su selection = 1 dentro de sus declaraciones if es (todavía) una tarea en CoffeeScript, necesita usar == para comparar. Prueba esto:

jQuery -> 
    price = $(".total-price span.price") 
    save = $(".savings") 
    select = $("#payment_talks_purchased") 
    select.change -> 
    selection = select.val() 
    if selection == '2' 
     price.html "$12" 
     return save.css "visibility", "visible" 
    else if selection == '1' 
     price.html "$5" 
     return save.css "visibility", "hidden" 

Además, == is converted to === así que es conveniente para comparar contra las cuerdas a menos que quiera "fundido" su valor a un número usando selection = +select.val() (gracias a Trevor Burnham para este truco de fundición) o parseInt(select.val(), 10).

+4

Exactamente a la derecha. Use 'selection = + select.val()' si quiere convertir la entrada del formulario en un número. –

+0

Muchas gracias por su ayuda. Eso hizo el truco. –

+0

¿No se prefiere '' 'para la comparación, a menos que explícitamente desee activar la coerción de tipo? – jpmc26

6

Puede utilizar el interruptor:

switch selection 
    when '2' 
    price.html "$12" 
    save.css "visibility", "visible" 
    when '1' 
    price.html "$5" 
    save.css "visibility", "hidden" 

También se pueden quitar los return, porque las funciones siempre devolverá su valor final.

1

Aquí está mi .50 centavos. Tenga en cuenta dos cosas: es solo mi opinión simple y no puede ser la mejor respuesta del mundo.

a) Si ya tiene un retorno en el interior instrucción IF, no hay necesidad ELSE IF

jQuery -> 
price = $(".total-price span.price") 
save = $(".savings") 
select = $("#payment_talks_purchased") 
select.change -> 
    selection = select.val() 
    if selection == '2' 
     price.html "$12" 
     // Since you return here, you dont need any other "else if" 
     return save.css "visibility", "visible" 

    price.html "$5" 
    return save.css "visibility", "hidden" 

Y no, en mi humilde opinión, pone el ELSE IF duerma mejorar la legibilidad. El regreso es un regreso. Período. Es simple como eso.

jQuery -> 
price = $(".total-price span.price") 
save = $(".savings") 
select = $("#payment_talks_purchased") 
select.change -> 
    selection = select.val() 
    // "ternary" coffee version (if then else) 
    price.html if selection == '2' then "$12" else "$5") 
    save.css "visibility" (if selection == '2' then "visible" else "hidden") 

Pero, mejor que todo está deshacerse de IF, ELSE, Switch y todos esos dados. Piense en OOP y su código puede comenzar a mejorar. Un punto de partida podría ser:

options = [ 
      {price: '$12', visible:"visible"}, 
      {price: '$5', visible:"hidden"} 
      ]; 
jQuery -> 
    price = $(".total-price span.price") 
    save = $(".savings") 
    select = $("#payment_talks_purchased") 
    select.change -> 
       // If the val of your select was 0 and 1, you wouldnt need the (-1) part 
     selection = parseInt(select.val) -1 
       price.html options[selection].price 
       save.css "visibility" options[selection].visible 

Así que, esto es todo. Casi el mismo código, pero con una mejor implementación (imho). Gracias.

Cuestiones relacionadas