修改这个js函数,让它使用从数据库中获取的值,而不是在数组中指定的值来生成Select选项


Modify this js function so that it uses the value fetched from the db instead of the values specified in the array to generate the Select options

我如何修改这个函数,使它可以使用从数据库中获取的值,而不是在用于生成选择选项的数组中指定的值?

该函数允许我区分选择元素的默认值(或'默认状态',预先设置为最常用的选项)与当用户通过单击表单元素主动选择该值时(表明他们做出了主动决定将其设置为该值)。该函数在初始形式下正确工作,我在这里发布了一个工作示例:http://jsfiddle.net/chayacooper/JHAPp/4/

<script>
$('select').focus(function () {
    var option = $(this).find("option[value*=default]");
    option.attr('value', option.attr('value').replace(/_default/g, ''));
});
</script>
<select name="jeans">
    <option value="$0">$0</option>
    <option value="$50_default" selected="selected">$50</option>
    <option value="$100">$100</option>
    <option value="$150">$150</option>
</select>

我在调整功能以在帐户页面上工作时遇到了麻烦,用户可以在那里查看和编辑他们的信息。在函数的初始使用中,我可以手动更改选项值(即:将value="$50"替换为value="$50_default"),但是帐户页面在下面的printselectopoptions函数中使用$options数组生成元素的选项,以便预先选择与db信息匹配的选项。下面的函数预先选择了与db中的信息匹配的值(无论用户是否特别选择了该值,或者它是否仍然处于'默认状态'),但是,由于它需要删除'_default'字符串,以便识别由$options数组生成的正确选项,它正在提交没有'_default'字符串的值,无论它是否被更改。

我如何修改js函数与此串联工作,以便如果用户没有专注于元素,它会提交默认值,如果值是从数据库中获取的'默认状态'(与'_default'字符串)?

<?php
    try {  
        $stmt = $conn->prepare("SELECT * FROM price WHERE user_id = :user_id");  
        $stmt->bindValue(':user_id', $user_id); 
        $stmt->execute();
    }  catch(PDOException $e) {echo $e->getMessage();}
    $row = $stmt->fetch();
    $search_default = array('_default');
    $replace_default = array('');
    $row_default = str_replace($search_default, $replace_default, $row);
    // This function selects the option matching the value in the db
    function printSelectOptions($dataArray, $currentSelection) {
        foreach ($dataArray as $key => $value) {
            echo '<option ' . (($key == $currentSelection) ? 'selected="selected"' : '') . ' value="' . $key . '">' . $value . '</option>';
        }
    }
?>
<select name="jeans">
<?php
    // Generates a <select> element with the options specified in this array
    $options = array("Null"=>"", "$0"=>"$0", "$50"=>"$50", "$100"=>"$100", "$150"=>"$150");
    $selected = $row_default['jeans'];
    // Pre-selects the option matching the db information
    echo printSelectOptions($options, $selected); 
?> 
</select> 

我认为你应该考虑更改PHP代码,并保留JavaScript。

这个怎么样:

在调用echo printSelectOptions(...)之前,找到$options中键等于$row_default['jeans']的条目(它永远不会以"_default"结束)并将该条目的键更改为$row['jeans']。你可能只是把它设置成原来的样子,但你可能会改变它,让它现在以"_default"结尾。

您还可以将$selected = $row_default['jeans'];更改为$selected = $row['jeans'];

现在,如果来自数据库的值以"_default"结尾,那么选中的选项(并且只有选中的选项)将以"_default"结尾。由于JavaScript保持不变,如果用户关注select元素,它将删除"_default"。

代码应该是这样的:

// This is a helper function that replaces a key while maintaining the entry's
// position in the array. It does not modify the given array, but returns a
// new array.
function replaceKey($array, $oldKey, $newKey) {
    $newArray = array();
    foreach ($array as $key => $value) {
        $newArray[($key === $oldKey) ? $newKey : $key] = $value;
    }
    return $newArray;
}
$options = array("Null"=>"", "$0"=>"$0", "$50"=>"$50", "$100"=>"$100", "$150"=>"$150");
// We will change the key for the entry in $options so it includes "_default" if
// the value from the database includes "_default". We need to do this only if
// $row['jeans'] ends with "_default". That will be the case if these two are
// different.
if ($row_default['jeans'] !== $row['jeans']) {
    $options = replaceKey($options, $row_default['jeans'], $row['jeans']);
}
// Now we can use the value from the db for setting the selected value, rather
// than the value that had "_default" removed. 
$selected = $row['jeans'];
// Pre-selects the option matching the db information.
echo printSelectOptions($options, $selected);
更新:

选择获得焦点时执行的JavaScript看起来是正确的。我在一个小提琴中测试了它,它似乎工作得很好。如果您查看jsfiddle,我对其进行了一些修改,以便它反映出选项以"_default"结尾的事实。我还将.attr()的使用更改为.prop(),但原来的工作也一样。(如果你使用jQuery>=1.6,你应该使用.prop()来改变元素属性,而不是.attr()。)

如果PHP生成的选择是jsfiddle中显示的样子,那么一定有其他原因导致JavaScript不能正常工作。可能是JavaScript错误导致事件处理程序无法连接。

$row在你的代码是一个数组,你使用$row['jeans']访问字段,并返回所有行,你需要把$stmt->fetch()在循环。

while ($row = $stmt->fetch()) {
    $row_default = str_replace($search_default, $replace_default, $row['jeans']);
    echo '<option value="' . $row_default . '">' . $row_default . '</option>';
}

这里是获取文档