[英]How to Hide the Certain Text Value of Selected Option using jQuery
I have a select box that contains certain elements (see below):我有一个包含某些元素的选择框(见下文):
<select id="test" name="test">
<option value="12345">12345 - Test</option>
<option value="67890">67890 - Test 2</option>
<option value="53453">53453 - Test 3</option>
</select>
Here is what I'm trying to accomplish When the user selects a certain element, I want certain elements of the text to hide.这是我要完成的任务 当用户选择某个元素时,我希望隐藏文本的某些元素。 For example, if I select 12345, I want the - Test to hide.
例如,如果我选择 12345,我希望 - 测试隐藏。
How can I do it in jQuery?我怎样才能在 jQuery 中做到这一点?
Thank you, Kevin谢谢你,凯文
A brute force-y way to do it would be to keep track of the internal text and values of the currently-selected option, then replace the text with the desired text when the option changes.一种蛮力的方法是跟踪当前所选选项的内部文本和值,然后在选项更改时将文本替换为所需的文本。 This part's easy in your case, since the desired output text is the same as the option's value.
这部分在您的情况下很容易,因为所需的输出文本与选项的值相同。
I opted to add a blank option at the beginning, since by default the text will not have changed, but you can get around this by adding a trigger to go off when the page is finished loading.我选择在开始时添加一个空白选项,因为默认情况下文本不会改变,但是您可以通过添加一个触发器来解决这个问题,当页面加载完成时关闭。
var selectedTextOrig = ""; var selectedValue = 0; $("#test").change(function() { // Reset the inner html text for the previously-selected option $("#test option").each(function() { if ($(this).val() == selectedValue) { $(this).text(selectedTextOrig); return false; // break out of $.each() } }); // Store the viewable text and value of the currently selected selectedValue = $("#test option:selected").val(); selectedTextOrig = $("#test option:selected").text(); // Replace the current inner html $("#test option:selected").text(selectedValue); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="test" name="test"> <option disabled="disabled" selected></option> <option value="12345">12345 - Test</option> <option value="67890">67890 - Test 2</option> <option value="53453">53453 - Test 3</option> </select>
I have found a solution:我找到了一个解决方案:
Here is how I achieved it:这是我实现它的方法:
$('select[name="test"]').find('option').remove().end();
$('select[name="test"]').append(new Option(selectId, selectId));
$('select[name="test"]').trigger('change');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.