如何在javascript变量中存储select_标记的值?

如何在javascript变量中存储select_标记的值?,javascript,ruby-on-rails,ruby,Javascript,Ruby On Rails,Ruby,我想将select from表单的值存储到我的javascript中 这项工作: .... 白色 黑色 红色 绿色 黄色的 document.getElementById(“tshirt颜色”).addEventListener(“更改”,函数(){ document.getElementById(“tshirt div”).style.backgroundColor=this.value; },假); 我正在尝试这样做: document.getElementById(“tshirt颜色

我想将select from表单的值存储到我的javascript中

这项工作:


....
白色
黑色
红色
绿色
黄色的
document.getElementById(“tshirt颜色”).addEventListener(“更改”,函数(){
document.getElementById(“tshirt div”).style.backgroundColor=this.value;
},假);
我正在尝试这样做:


document.getElementById(“tshirt颜色”).addEventListener(“更改”,函数(){
var bg_color=此值
document.getElementById(“tshirt div”).style.backgroundColor=;
},假);
我的一些尝试:

var bg_color=document.getElementById(“tshirt color”).value
函数的内部和外部

var bg_color=document.getElementById(“tshirt color”).addEventListener(“change”,function()){
document.getElementById(“tshirt div”).style.backgroundColor=;
,假);
我尝试了许多不同的方法来存储
var
,但每种方法都会产生以下错误:

未定义的局部方法或变量“bg_color”

f.grouped\u collection\u select的值是一个整数,因此我想找到颜色标题(红色、蓝色、绿色等),然后将其返回到
…style.backgroundColor


如何存储表单中的select,将其存储为变量,然后从颜色模型中查找颜色?

您可以始终将值存储在元素中,并在select更改时更新其值

然后做一些类似的事情

<%= hidden_field_tag 'color_id', '0', onchange: "changeColor()", id: 'selected-color-field'%>
<script>
  function changeColor() {
    var selectedColor = document.getElementById("selected-color-field").value
    // Do whatever
  }
</script>

函数changeColor(){
var selectedColor=document.getElementById(“所选颜色字段”).value
//做任何事
}

您无法从ERB标记内部访问JavaScript变量。ERB位于脚本顶部。这意味着当向Rails服务器发出页面请求时,它将编译页面,以便解释ERB。然后向客户端发送一个普通JavaScript文件或HTML文件。JavaScript将在客户端上执行

<%= Color.find(bg_color) %>
如果不想预先提供所有颜色,则必须设置一个AJAX请求,在选择颜色时查询服务器


让我快速解释一下

由于JSON是JavaScript对象表示法的缩写,因此可以简单地将其作为JavaScript的一部分进行读取


或者,您可以手动构建选项,并通过自定义属性提供颜色值。例如,选项可以如下所示:

白色
然后使用附加属性设置颜色

const color=this.options[this.selectedIndex].dataset.colorValue;
document.getElementById(“tshirt div”).style.backgroundColor=颜色;

谢谢,但这给了我一个由于ruby导致的javascript错误:
意外的标记&
…假设这是由于拔毛造成的,但是你怎么想:
const colors={“1”:“白色”、“2”:“黑色”、“3”:“蓝色”、“4”:“红色”}
@uno似乎ERB替换了HTML不安全字符。添加
.HTML\u safe
添加和以将字符串标记为HTML安全。我将更新答案。谢谢!只需使用
var
而不是
const
,因为我的javascript循环到多个画布上。sHow是否完全有效?如果分组的\u集合选择正在被更改为隐藏字段,这不也需要某种
onchange
吗?我只是对
grouped\u collection\u select
值如何准确地传递到隐藏字段感到困惑here@uno您可以使用jquery来实现这一点。只需附加一个简单的
$('#selected color field').val(event.target.value)
以选择更改。
tmp = Color.pluck(:id, :value) # retrieve the id and value of the colors
#=> [[1, "#fff"], [2, "#000"]]
tmp = tmp.to_h # convert the nested array into a hash
#=> { 1 => "#fff", 2 => "#000" }
tmp = tmp.to_json # convert the hash to a JSON string
#=> '{"1":"#fff", "2":"#000"}'
tmp = tmp.html_safe # mark the string as HTML safe so ERB won't replace characters such as " with &quot;
#=> '{"1":"#fff", "2":"#000"}'