Cambia una entrada cuando cambias otra en javascript

Hard to define the title ^^

I want to have to input fields. For example: one where you type in a color (string) and another for the code of the color (varchar).

Like this: |Green| |#657EC9| (just random color-code)

No quiero aprender cómo encontrar el código de color sino cómo hacer coincidir un valor o variable con otro. Fue solo un ejemplo.

Lo que quiero saber es cómo puedo generar automáticamente uno de los campos cuando completo el segundo. Cuando escribo 'verde' en el primer campo, quiero que el código aparezca automáticamente en el segundo y viceversa. Solo quiero hacerlo por unos pocos colores.

I am very new to PHP, HTML and Javascript and could need some good advice about how I should handle the problem.

Gracias

preguntado el 31 de julio de 12 a las 14:07

1 Respuestas

I would tend to just map values to an object literal, so:

var colors = {
    Green:'#657EC9',
    Red:'#00ffff'
}

Now you could get your value with colors[fieldInputVal] where fieldInputVal might be 'Green' or 'Red' although of course you'd have to test if there actually was a property there. Object literals are the main reason I rarely find a use for switch statements in JS.

As for the event JS, I'm going to be lazy and go with JQuery rather than explain attachEvent vs. addEventListener which would be necessary if you're supporting IE8 or below. If you want to normalize for that yourself and skip JQuery, look up 'addEvent contest' on quirksmode.org

$('.input_one').change( function(){
    //note: only fires after the field loses focus - you tab out or focus another field
    var inputVal = $(this).val();
    if(colors[inputVal] !== undefined){
        $('.input_two').val(colors[inputVal]);
    }
} );

note: I did not test this code for syntax goofs.

If you want to be more flexible and accept 'green' or 'Green', I would just capitalize the first character before you use it for the lookup. To do the lookup on every character add, you'd have to look up the keyup or keydown events (I prefer keyup to avoid breaking the browsers back when somebody holds a key down).

Respondido 31 Jul 12, 14:07

"If you want to be more flexible and accept 'green' or 'Green'" You could capitalize every letter when comparing and have your map keys capitalized as well , then you will match everything from Green over GReeN to greeN (in case of typos) - roel

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.