Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Sep 2011
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Combining Text and numeric variables

    I would like to fill a text field using both text and variables..

    i.e. it would say x+2, so i would write.. (if 2 were a given variable)
    form.form1.value = "x+" 2 ???

    (I know that isn't correct, I'm just wondering how I would go about this..)

  • #2
    Regular Coder
    Join Date
    Aug 2010
    Posts
    945
    Thanks
    19
    Thanked 205 Times in 203 Posts
    This is probably not a good answer
    as i really dont understand the question ....

    Code:
    <form name="frm">
    <input name="a" >
    <script>var a=2*1;frm.a.value="2+" + a  </script>
    <input name= "b" >
    <script>frm.b.value=eval("2+" + a ) </script>
    </form>
    input a has 2 + 2
    input b has 4

  • #3
    Senior Coder Arbitrator's Avatar
    Join Date
    Mar 2006
    Location
    Splendora, Texas, United States of America
    Posts
    3,274
    Thanks
    28
    Thanked 271 Times in 265 Posts
    Quote Originally Posted by lilwillywonka View Post
    I would like to fill a text field using both text and variables..

    i.e. it would say x+2, so i would write.. (if 2 were a given variable)
    form.form1.value = "x+" 2 ???

    (I know that isn't correct, I'm just wondering how I would go about this..)
    If you want the text field to read "x + #" where # is a numeric variable, you would use something like this:

    Code:
    var input_el = document.getElementById("text_field");
    var my_numeric_variable = 2;
    input_el.value = "x + " + my_numeric_variable.toString();
    That would operate on HTML like this:

    Code:
    <input id="text_field" type="text">
    (Note that .toString() isn't technically required since JavaScript automatically converts variable types (here from a number to a string), but I prefer to do these conversions explicitly instead of relying on "magic" to auto-convert between types.)
    For every complex problem, there is an answer that is clear, simple, and wrong.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •