Get text from value in a selection
I try to create a function, I pass a selector plus the value and I would like to get text
function getTextBySelectorAndValue(selector, value) {
return $(selector + " option[value='" + value + "']").text();
}
Error i get it's Syntax error, unrecognized expression: [object Object] option[value='1']
Seem like selector is not really working
I call this method like
getTextBySelectorAndValue($("#lodgerAppointmentLocation"), $("#lodgerAppointmentLocation").val());
You are passing a jQuery object to a function that expects a string selector.
I suggest either passing the existing function a selector string...
function getTextBySelectorAndValue(selector, value) {
return $(selector + " option[value='" + value + "']").text();
}
$('#lodgerAppointmentLocation').on('change', function() {
$('div#output').text(getTextBySelectorAndValue("#lodgerAppointmentLocation", $("#lodgerAppointmentLocation").val()));
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="lodgerAppointmentLocation">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<div id="output"></div>
你没有看到我的答案,并且在你更新了你的问题的意思,所以我的答案不再合适,所以我必须删除。
链接地址: http://www.djcxy.com/p/83948.html上一篇: jQuery如何区分'data'和'selector'参数?
下一篇: 从选定的值中获取文本