Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

javascript - 表单数据:使用选择选项中的值填充输入标签(form data: populating input tag with value from select option)

I have a html form, and I need to make the input value equal whatever is chosen as a select option (due to the way the form is processed, the value must be associated with an input tag - it won't work from within a select tag).(我有一个html表单,我需要使输入值等于选择作为选择选项的任何值(由于处理表单的方式,该值必须与input标记相关联-不能在选择标签)。)

Here are the select options in my form:(这是我表单中的选择选项:) <select type="hidden" name="item_colour" id="select"> <option value="yellow item" selected>yellow</option> <option value="blue item">blue</option> </select> Is it possible to create a hidden input along these lines:(是否有可能沿着这些行创建隐藏的输入:) <input type="hidden" name="item_name" value=item_colour> The above obviously doesn't work, and I'm thinking I need to somehow use the following javascript:(上面的代码显然不起作用,我想我需要以某种方式使用以下javascript:) document.getElementById("item_colour") But I'm stumped how to make it all work.(但是我很困惑如何使其全部正常工作。) Thanks.(谢谢。)   ask by Dr_Hoon translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do something like:(您可以执行以下操作:)

$( "#select option:selected" ).val(); Full example by creating and submitting a form via JS(通过JS创建和提交表单的完整示例) function submit() { var form = document.createElement("form"); form.method = "GET"; var obj = document.createElement("input"); obj.name = "item_colour"; obj.value = $( "#select option:selected" ).val(); form.appendChild(obj); document.body.appendChild(form); form.submit(); } If this doesn't work then maybe the library you are using is changing the dom of the select.(如果这不起作用,则可能您正在使用的库正在更改选择的dom。) It's better if you inspect the element select through the browser and see how it is working.(最好通过浏览器检查选择的元素并查看其工作方式。) I would suggest to also use the console in the browser developer options, it will allow you to write javascript code right on the page which will help you in testing.(我建议也使用浏览器开发人员选项中的控制台,它将允许您在页面上编写javascript代码,这将有助于您进行测试。) Another way of getting the selected attribute is via(获取所选属性的另一种方法是通过) $('.my-custom-select').on('change', function (e, params) { alert(e.target.value); // OR alert(this.value); // OR alert(params.selected); });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...