简体   繁体   中英

Passing the if check between php and javascript from a select option tag

I have a problem with a if statement to determine whether the option box has the value "Choose Here", if it's not proceed to the following function inside the if statement. The $EnrollmentMonth is working fine capturing the value from elsewhere.

<script>
    function promptEnrollmentMonth () {
        if (document.getElementById("add_product").value !== "Choose here") {
            var month = prompt("Is this the correct month for this course/product?", "<?php echo $EnrollmentMonth; ?>");
            if (month != null) {
                window.location.href = "studentupdate.php?id=<?php echo $StudentID?>" + "&enrollmentmonth=" + month;
                <?php
                    $EnrollmentMonth = $_GET['enrollmentmonth'];
                    $sql3 = "INSERT into enrollment (StudentID, ProductID, EnrollmentMonth) VALUES ($StudentID, $select1, $EnrollmentMonth)";
                    mysql_query($sql3);
                ?>
                // Insert result if the prompt box does not return null.
            }
        } else {
            document.write("Stuck here!");
        }
    }
</script>

<button type="submit" onclick="promptEnrollmentMonth();">Update</button>

<?php
    $sql2          = 'SELECT * FROM product ORDER BY ProductID ASC';
    $sql2          = "SELECT * FROM product WHERE ProductID NOT IN (SELECT ProductID from enrollment WHERE StudentID = '$StudentID') ORDER BY ProductID ASC";
    $result_select = mysql_query($sql2);
    $rows          = array();
    while ($row = mysql_fetch_array($result_select)) {
        $rows[] = $row;
    }
    echo "<div class=\"spanstyle\">Add course/product:<select name='add_product'>";
    echo "<option value='Choose here' selected>Choose here</option>";
    foreach ($rows as $row) {
        echo "<option value='" . $row['ProductID'] . "'>" . $row['ProductName'] . "</option>";
    }
    echo "</select></div>";
?>

You are calling document.getElementById() but your select doesn't have an id. Thats why using getElementById will not work unless you give your select the id="add_product" alternatively you could use document.getElementsByName('add_product')[0] to get your very first item with the name add_product. but i would prefer the ID.

your final PHP/HTML should look sth like this

echo '<div class="spanstyle">Add course/product:<select name="add_product" id="add_product">';
echo '<option value="Choose here" selected>Choose here</option>';

please note, that i used single-quote style for the strings, so if you use my answer you have to change it to your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM