Answers:
尝试这个-
$('select').on('change', function() {
alert( this.value );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="1">One</option>
<option value="2">Two</option>
</select>
您还可以引用onchange事件-
function getval(sel)
{
alert(sel.value);
}
<select onchange="getval(this);">
<option value="1">One</option>
<option value="2">Two</option>
</select>
.change()
快捷方式。
我的印象是,通过执行$(this).val();可以获取选择输入的值。
如果您毫不客气地订阅(这是推荐的方法),这将起作用:
$('#id_of_field').change(function() {
// $(this).val() will work here
});
如果onselect
将标记与脚本混合使用,则需要传递对当前元素的引用:
onselect="foo(this);"
然后:
function foo(element) {
// $(element).val() will give you what you are looking for
}
您可以尝试一下(使用jQuery)-
$('select').on('change', function()
{
alert( this.value );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
或者您可以使用像这样的简单Javascript-
function getNewVal(item)
{
alert(item.value);
}
<select onchange="getNewVal(this);">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
$('#select_id').on('change', function()
{
alert(this.value); //or alert($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="select_id">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
箭头函数的作用域与函数不同,
this.value
将为箭头函数给出undefined。修复使用
$('select').on('change',(event) => {
alert( event.target.value );
});
这对我有用。尝试其他一切都没有运气:
<html>
<head>
<title>Example: Change event on a select</title>
<script type="text/javascript">
function changeEventHandler(event) {
alert('You like ' + event.target.value + ' ice cream.');
}
</script>
</head>
<body>
<label>Choose an ice cream flavor: </label>
<select size="1" onchange="changeEventHandler(event);">
<option>chocolate</option>
<option>strawberry</option>
<option>vanilla</option>
</select>
</body>
</html>
取自Mozilla
寻找jQuery 网站
HTML:
<form>
<input class="target" type="text" value="Field 1">
<select class="target">
<option value="option1" selected="selected">Option 1</option>
<option value="option2">Option 2</option>
</select>
</form>
<div id="other">
Trigger the handler
</div>
JAVASCRIPT:
$( ".target" ).change(function() {
alert( "Handler for .change() called." );
});
jQuery的示例:
要将有效性测试添加到所有文本输入元素:
$( "input[type='text']" ).change(function() {
// Check input( $( this ).val() ) for validity here
});
对于所有选择,调用此函数。
$('select').on('change', function()
{
alert( this.value );
});
仅选择一项:
$('#select_id')
jQuery使用on Change事件获取选择html元素的值
$(document).ready(function () {
$('body').on('change','#select_box', function() {
$('#show_only').val(this.value);
});
});
<!DOCTYPE html>
<html>
<title>jQuery Select OnChnage Method</title>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<select id="select_box">
<option value="">Select One</option>
<option value="One">One</option>
<option value="Two">Two</option>
<option value="Three">Three</option>
<option value="Four">Four</option>
<option value="Five">Five</option>
</select>
<br><br>
<input type="text" id="show_only" disabled="">
</body>
</html>
jQuery(document).ready(function(){
jQuery("#id").change(function() {
var value = jQuery(this).children(":selected").attr("value");
alert(value);
});
})
让我分享一个用BS4,thymeleaf和Spring boot开发的示例。
我正在使用两个SELECT,其中第二个(“子主题”)根据第一个(“主题”)的选择由AJAX调用填充。
首先,是百里香片段:
<div class="form-group">
<label th:for="topicId" th:text="#{label.topic}">Topic</label>
<select class="custom-select"
th:id="topicId" th:name="topicId"
th:field="*{topicId}"
th:errorclass="is-invalid" required>
<option value="" selected
th:text="#{option.select}">Select
</option>
<optgroup th:each="topicGroup : ${topicGroups}"
th:label="${topicGroup}">
<option th:each="topicItem : ${topics}"
th:if="${topicGroup == topicItem.grp} "
th:value="${{topicItem.baseIdentity.id}}"
th:text="${topicItem.name}"
th:selected="${{topicItem.baseIdentity.id==topicId}}">
</option>
</optgroup>
<option th:each="topicIter : ${topics}"
th:if="${topicIter.grp == ''} "
th:value="${{topicIter.baseIdentity.id}}"
th:text="${topicIter.name}"
th:selected="${{topicIter.baseIdentity?.id==topicId}}">
</option>
</select>
<small id="topicHelp" class="form-text text-muted"
th:text="#{label.topic.tt}">select</small>
</div><!-- .form-group -->
<div class="form-group">
<label for="subtopicsId" th:text="#{label.subtopicsId}">subtopics</label>
<select class="custom-select"
id="subtopicsId" name="subtopicsId"
th:field="*{subtopicsId}"
th:errorclass="is-invalid" multiple="multiple">
<option value="" disabled
th:text="#{option.multiple.optional}">Select
</option>
<option th:each="subtopicsIter : ${subtopicsList}"
th:value="${{subtopicsIter.baseIdentity.id}}"
th:text="${subtopicsIter.name}">
</option>
</select>
<small id="subtopicsHelp" class="form-text text-muted"
th:unless="${#fields.hasErrors('subtopicsId')}"
th:text="#{label.subtopics.tt}">select</small>
<small id="subtopicsIdError" class="invalid-feedback"
th:if="${#fields.hasErrors('subtopicsId')}"
th:errors="*{subtopicsId}">Errors</small>
</div><!-- .form-group -->
我正在遍历存储在模型上下文中的主题列表,显示所有带有其主题的组,然后显示所有没有组的主题。BaseIdentity是@Embedded复合密钥BTW。
现在,这是处理更改的jQuery:
$('#topicId').change(function () {
selectedOption = $(this).val();
if (selectedOption === "") {
$('#subtopicsId').prop('disabled', 'disabled').val('');
$("#subtopicsId option").slice(1).remove(); // keep first
} else {
$('#subtopicsId').prop('disabled', false)
var orig = $(location).attr('origin');
var url = orig + "/getsubtopics/" + selectedOption;
$.ajax({
url: url,
success: function (response) {
var len = response.length;
$("#subtopicsId option[value!='']").remove(); // keep first
for (var i = 0; i < len; i++) {
var id = response[i]['baseIdentity']['id'];
var name = response[i]['name'];
$("#subtopicsId").append("<option value='" + id + "'>" + name + "</option>");
}
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
}).change(); // and call it once defined
对change()的初始调用可确保它将在重新加载页面时执行,或者确保后端已通过某种初始化预先选择了某个值。
顺便说一句:我使用“手动”表单验证(请参阅“有效” /“无效”),因为我(和用户)不喜欢BS4将不需要的空白字段标记为绿色。但是,这是此问题的另一范围,如果您有兴趣,也可以发布。
我想添加,谁需要完整的自定义标头功能
function addSearchControls(json) {
$("#tblCalls thead").append($("#tblCalls thead tr:first").clone());
$("#tblCalls thead tr:eq(1) th").each(function (index) {
// For text inputs
if (index != 1 && index != 2) {
$(this).replaceWith('<th><input type="text" placeholder=" ' + $(this).html() + ' ara"></input></th>');
var searchControl = $("#tblCalls thead tr:eq(1) th:eq(" + index + ") input");
searchControl.on("keyup", function () {
table.column(index).search(searchControl.val()).draw();
})
}
// For DatePicker inputs
else if (index == 1) {
$(this).replaceWith('<th><input type="text" id="datepicker" placeholder="' + $(this).html() + ' ara" class="tblCalls-search-date datepicker" /></th>');
$('.tblCalls-search-date').on('keyup click change', function () {
var i = $(this).attr('id'); // getting column index
var v = $(this).val(); // getting search input value
table.columns(index).search(v).draw();
});
$(".datepicker").datepicker({
dateFormat: "dd-mm-yy",
altFieldTimeOnly: false,
altFormat: "yy-mm-dd",
altTimeFormat: "h:m",
altField: "#tarih-db",
monthNames: ["Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"],
dayNamesMin: ["Pa", "Pt", "Sl", "Ça", "Pe", "Cu", "Ct"],
firstDay: 1,
dateFormat: "yy-mm-dd",
showOn: "button",
showAnim: 'slideDown',
showButtonPanel: true,
autoSize: true,
buttonImage: "http://jqueryui.com/resources/demos/datepicker/images/calendar.gif",
buttonImageOnly: false,
buttonText: "Tarih Seçiniz",
closeText: "Temizle"
});
$(document).on("click", ".ui-datepicker-close", function () {
$('.datepicker').val("");
table.columns(5).search("").draw();
});
}
// For DropDown inputs
else if (index == 2) {
$(this).replaceWith('<th><select id="filter_comparator" class="styled-select yellow rounded"><option value="select">Seç</option><option value="eq">=</option><option value="gt">>=</option><option value="lt"><=</option><option value="ne">!=</option></select><input type="text" id="filter_value"></th>');
var selectedOperator;
$('#filter_comparator').on('change', function () {
var i = $(this).attr('id'); // getting column index
var v = $(this).val(); // getting search input value
selectedOperator = v;
if(v=="select")
table.columns(index).search('select|0').draw();
$('#filter_value').val("");
});
$('#filter_value').on('keyup click change', function () {
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == '13') {
var i = $(this).attr('id'); // getting column index
var v = $(this).val(); // getting search input value
table.columns(index).search(selectedOperator + '|' + v).draw();
}
});
}
})
}