<%= form_for(@mymodel, remote: true, html: { id: 'match_form' }) do |f| %>
<%= f.text_field :match_id, style: "width:82px" %>
<%= f.submit 'Save', class: 'btn btn-primary', id: 'match_submit', style: "width:38px;padding:0px" %>
<%= button_tag 'Cancel', class: 'btn btn-secondary', id: 'match_cancel', style: "width:52px;padding:0px" %>
<% end%>
<script type='text/javascript'>
$(function() {
$(document).on("click", "#match_submit", function(event){
$.ajax('my_controller_method', {
type: 'GET',
dataType: 'script',
data: {
mid: $("#").val(), // How can I get the new value entered in 'match_id' textfield here?
},
error: function(jqXHR, textStatus, errorThrown) {
return console.log("AJAX Error: " + textStatus);
}
});
});
</script>我有上面显示的表单和JavaScript块。
如何在JavaScript代码的'match_id‘文本字段中获得输入的新值?
发布于 2020-02-12 18:21:42
您需要理解ERB是一个驻留在服务器上的模板,然后被编译成HTML (这意味着所有的ERB代码都完全消失了),然后生成的HTML被发送到浏览器,然后执行JS代码。
JS只能看到和处理生成的HTML。它不知道是否存在ERB或PHP或任何用于生成它所处理的HTML的模板语言。
您的ERB模板的结果将是<input id="debit_match_id">,因此在JS/jQuery中选择它的正确方法是$("#debit_match_id")。
发布于 2020-02-12 18:05:20
<%= f.text_field :match_id, style: "width:82px", id: "debit_match_id" %>
# add id in text field to get the value通过使用$('#debit_match_id').val();,可以获取match_id文本字段的当前值:
data: { mid: $('#debit_match_id').val(); } // get the new value entered in 'match_id'发布于 2020-02-12 18:17:42
感谢@JeremyThille的回答:
$("#debit_match_id").val();
这给出了在文本字段中输入的新值(debit_match_id是文本字段的HTML。JavaScript使用HTML,而不是拼音模板id)
https://stackoverflow.com/questions/60185572
复制相似问题