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 5 of 5
  1. #1
    New to the CF scene
    Join Date
    Nov 2013
    Posts
    9
    Thanks
    2
    Thanked 0 Times in 0 Posts

    How to integrate html into a javascript variable

    I am working in this simple function in javascript and my editor keeps telling me that there is an error in the var imag line. I do not see the error.
    I will appreciate any help about this.

    This is my code:

    Code:
    <script type="text/javascript">
    
    function getcod(varimag) {
    var imag = "<img src=""images/" + varimag + "">";
    response.write(imag);
    }
    </script>
    MY HTML code:

    Code:
    <select class="texto2" id="imagen"  name="imagen" onchange="getcod(this);">
      <option value="01.jpg">Image 1</option>
       <option value="02.jpg">Image 2</option>
        <option value="03.jpg">Image 3</option>
      
    </select>
    Thanks in advance.

  • #2
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,912
    Thanks
    56
    Thanked 545 Times in 542 Posts
    way too many quotes. Try it like this:
    Code:
    var imag = "<img src='images/" + varimag + "'>";
    I also suspect that your onchange will work better just passing the select value:
    Code:
    onchange="getcod(this.value);"

  • Users who have thanked xelawho for this post:

    rrobles (04-07-2014)

  • #3
    Regular Coder Linux_Sage's Avatar
    Join Date
    Mar 2014
    Location
    Sterling,VA
    Posts
    105
    Thanks
    0
    Thanked 10 Times in 10 Posts
    You're probably going to need to escape those double quotes

    Code:
    var imag = "<img src=\""images/" + varimag + "\">";
    If you're going to include double quotes within double quotes and display them, they need to be escaped.

    Edit:
    I got ninja'd

  • Users who have thanked Linux_Sage for this post:

    rrobles (04-07-2014)

  • #4
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    11,037
    Thanks
    0
    Thanked 250 Times in 246 Posts
    I prefer using single quotes for the literal string to be consistent in using double quotes for the HTML attributes and avoid escaping them.

    Code:
    var imag = '<img src="images/' + varimag + '">';
    Btw, I'm curious why the OP is using ASP/ASP.NET's response.write method in Javascript. Or probably he created his own version of response.write method in Javascript?

  • #5
    New to the CF scene
    Join Date
    Nov 2013
    Posts
    9
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Thank you xelawho. Now it works.


  •  

    Tags for this Thread

    Posting Permissions

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