简体   繁体   中英

JS showing undefined in text input

I have this HTML/PHP Code that populates a select box

<select name="customerbilling_productname" id="mySelectBox" onchange="changeValue(this.value);" style="width:120px;">
    <option value="">Please Choose</option>
    <option value="Type Custom">Type Custom</option>
    <?php
    $json_array = array();
    $stmt = $pdo_conn->prepare("SELECT * from prices ");
    $stmt->execute(array());
    $records = $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach($records as $result2) {
        $product = $result2["product"];
        $json_array[$product] = $result2['retail'];
        echo '<option value="'.$result2["product"].'">'.$result2["product"].'</option>';
    }
    json_encode($json_array, JSON_FORCE_OBJECT); 
    ?>
    </select>

And this JS Code:

<script>
var json = <?php echo $json_array; ?>;
function changeValue(myValue) {
    document.getElementById("customerbilling_unitprice").value = json[myValue];
}
</script>

So when i select an option from the drop down, it should populate the customer billing_unitprice text input to have the value from the retail column in the database

when i select an option from the drop down, it is showing undefined in the text input and not the value in the database

You are encoding the json like this:

json_encode($json_array, JSON_FORCE_OBJECT); 

but you aren't assigning it to anything.

So, do this:

$json_str = json_encode($json_array, JSON_FORCE_OBJECT); 

Then update your javascript like this:

var json = JSON.parse('<?php echo $json_str; ?>');

The reason why I am doing JSON.parse() is because PHP's json_encode returns a json string. You then need to parse this into an object/array in javascript.

try to change this:

var json = <?php echo $json_array; ?>;

to this:

var json = '<?php echo $json_array; ?>';

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