Note that there are some explanatory texts on larger screens.

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

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload