1

I'm trying to make a dropdown in HTML, but I want to have it's default value to be determined by the value of a PHP variable. I wanted to do it with JavaScript, but I end up with the famous "Uncaught ReferenceError: $ is not defined" error :/.

PHP:

while(list($ArtikelID, $Type) = mysql_fetch_array($result))
{
  $arid = $ArtikelID;
  $te = $Type;
}

HTML + JS:

<form name="send" method="post" action="editartticlesdef.php">
    articlenumber: </br>
    <input readonly="readonly" name="ArticleID" value=<?php echo $arid ?>></br>
    Type: </br>
    <select name="Type">
        <option value="Article">Article</option>
        <option value="Code">Code</option>
        <option value="News">News</option>
        <option value="Project">Project</option>
    </select></br>
    <script>
        document.getElementById("Type").selectedIndex = <?php echo '$te'; ?>;
    </script>
</form>

I tried to place the script on other places on the page but had no success :/. I suspect the variable falls outside the scope, but I don't know how to get it back in :/.

2
  • 1
    Replace <?php echo '$te'; ?> with '<?php echo $te; ?>' Commented Oct 14, 2015 at 12:32
  • Is PHP or JavaScript throwing the error? What is the resulting JavaScript created by this code? Commented Oct 14, 2015 at 12:32

3 Answers 3

4

It should be -

<select name="Type" id="Type">

And

document.getElementById("Type").selectedIndex = '<?php echo $te; ?>';
Sign up to request clarification or add additional context in comments.

1 Comment

Well that worked, but it turns out I'm also an idiot. While this solves the error I got it also shows me that I'm trying to select the value of the dropdown by id and not the value of the variable $te. facepalm
1

Provided $te is an integer between 0 and 3, then you need to:

  1. Give your select an id attribute:

    <select name="Type" id="Type"> <option value="Article">Article</option> <option value="Code">Code</option> <option value="News">News</option> <option value="Project">Project</option> </select>

  2. remove the quotes areound the php variable itsself and place them in the html:

    <script> document.getElementById("Type").selectedIndex = "<?php echo $te; ?>"; </script>

Comments

0

Sorry for not answering the question, but you should not use mysql_, it's deprecated and unsafe (See PHP Manual). Use MySQLi or PDO.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.