Tutorial :Adding text from JS var on change event using jquery



Question:

Im trying to accomplish something "like" this. I want to add the text stored in some JS variables into the doc based on the value selected in a combo. i.e. how do I reference JS variables based on the selected value of a combo?

<select id="clickMe">      <option value="a">a</a>      <option value="b">b</a>      <option value="c">c</a>  </select>    <span id="attachHere"></span>       <script>    var a = "something about a";  var b = "something about b";  var c = "something about c";    $(document).ready(function() {      $("#clickMe").change(function() {          $("#attachHere").text($("#clickMe").val());      });  });      </script>  


Solution:1

Why not go with something like that instead?

<script>  <!--    var values = {      'a' : "something about a",      'b' : "something about b",      'c' : "something about c",  };    $(document).ready(function() {      $("#clickMe").change(function() {          $("#attachHere").text(values[$("#clickMe").val()]);      });  });    //-->  </script>  

You'll control your list of values and easily be able to add and remove values.


Solution:2

It'd be better if you used arrays objects.

Assuming you don't want to use arrays, I think you can use eval:

$(document).ready(function() {      $("#clickMe").change(function() {          var tmp;          eval('tmp = ' + $("#clickMe").val());          $("#attachHere").text(tmp);      });  });  


Solution:3

Try putting the values in a hash keyed by the choice and then extracting it based on the chosen value.

var choices = {};  choices['a'] = 'something about a';  choices['b'] = 'something about b';  choices['c'] = 'something about c';    $(document).ready(function() {      $("#clickMe").change(function() {          $("#attachHere").text(choices[$(this).val()]);      });  });  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »