To relate two strings, it's easiest to use an object to create a dictionary/ map, as shown below;
$('#input1').bind('keyup',function() {
var map = {
"1":"One",
"2":"Fish",
"3":"Bar"
};
$('#input2').val(map[$(this).val()]);
});
You can see this in action here: http://www.jsfiddle.net/dCy6f/
For more advanced behaviour:
$('#input1').bind('keyup',function() {
var str = '';
var input = $(this).val();
var intVal = parseInt(input, 10); // Dont forget the radix
var map = {
"1":"One",
"2":"Fish",
"3":"Bar"
};
if (intVal > 50 && intVal < 100) {
str = 'Something';
} else if (map.hasOwnProperty(input)) {
str = map[input];
}
$('#input2').val(str);
});
You can test this inplementation here: http://www.jsfiddle.net/H6skz/
If you want the second value only to update when the user has finished typing into the first input field, change "keyup" to "change".
To abstract this into a function, your could do:
function relate(me, withMe) {
$(me).bind('keyup',function() {
var str = '';
var input = $(this).val();
var intVal = parseInt(input, 10); // Dont forget the radix
var map = {
"1":"One",
"2":"Fish",
"3":"Bar"
};
if (intVal > 50 && intVal < 100) {
str = 'Something';
} else if (map.hasOwnProperty(input)) {
str = map[input];
}
$(withMe).val(str);
});
}
and then use it as follows:
relate('#input1', '#input2');
For a more intuitive interface, write a jQuery plugin:
(function ($) {
jQuery.fn.relate = function (withMe) {
this.bind('keyup',function() {
var str = '';
var input = $(this).val();
var intVal = parseInt(input, 10); // Dont forget the radix
var map = {
"1":"One",
"2":"Fish",
"3":"Bar"
};
if (intVal > 50 && intVal < 100) {
str = 'Something';
} else if (map.hasOwnProperty(input)) {
str = map[input];
}
$(withMe).val(str);
});
};
}(jQuery));
and then use as follows:
$('#input1').relate('#input2');