gpt4 book ai didi

javascript - 如何在表单中组合两个选择字段

转载 作者:行者123 更新时间:2023-12-03 09:28:14 24 4
gpt4 key购买 nike

在提交表单之前,我尝试将表单中两个选择字段的值合并为一个变量。

这是我的代码:

在 new.html.erb 中(对于 RoR):

<%= form_for :character, url: characters_path, method: :post do |f| %>
<p>
<%= f.label :alignment %><br>
<%= f.select :alignment_lr, options_for_select([" ","Chaotic","Neutral","Lawful"], disabled: " ", selected: " ") %>
<%= f.select :alignment_ud, options_for_select([" ","Good","Neutral","Evil"], disabled: " ", selected: " ") %>
</p>
<% end %>

这会生成以下 html:

<p>
<label for="character_alignment">Alignment</label><br>
<select id="character_alignment_lr" name="character[alignment_lr]">
<option disabled="disabled" selected="selected" value=" "> </option>
<option value="Chaotic">Chaotic</option>
<option value="Neutral">Neutral</option>
<option value="Lawful">Lawful</option></select>
<select id="character_alignment_ud" name="character[alignment_ud]">
<option disabled="disabled" selected="selected" value=" "> </option>
<option value="Good">Good</option>
<option value="Neutral">Neutral</option>
<option value="Evil">Evil</option></select>
</p>

如何组合为 :alignment_lr:alignment_ud 选择的值以等于 alignment.value =alignment_lr.value + ' ' +alignment_ud。值

我愿意使用 javascript 或 jquery 来解决这个问题。

最佳答案

我认为最好添加一个隐藏输入来存储这两个值;

<input id="character_alignment" type="hidden" name="character[alignment]" value=""/>

<script type="text/javascript">
$(document).ready(function() {

// for the first select
$("#character_alignment_lr").change(function(){
setCharacterAlignment();
});


// for the second select
$("#character_alignment_lr").change(function(){
setCharacterAlignment();
});

});

function setCharacterAlignment()
{
// get dropdown selected option
var val1 = $('#character_alignment_lr option:selected').val();
var val2 = $('#character_alignment_ud option:selected').val();

// set hidden input value
$("#character_alignment").val(val1 + " " + val2);
}

</script>

关于javascript - 如何在表单中组合两个选择字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31596785/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com