Change the text in the selected box of a select menu onChange event
I have a select menu with option items as
<select>
<option>--1</option>
<option>--2</option>
<option>--3</option&g开发者_JS百科t;
<option>--4</option>
</select>
When i select a item from the select menu, it displays '--2' in the box. I want only '2' to be displayed in the selected item box. How can i do that?
If i get a solution in jQuery, that would be more preferable.
Note: I don't want the values displayed in the drop down menu to be changed at any moment but the value that is displayed in the select box must not have the '--'(dashes).
It seems like what you are trying to do is have a display value and a value that Javascript can read. In that case I propose you change your select
element as opposed to writing custom javascript to change the appearance. This sounds like it may solve your problem.
I would write the select
as per following:
<select>
<option value="--1">1</option>
<option value="--2">2</option>
<option value="--3">3</option>
<option value="--4">4</option>
</select>
then read the value instead of the text of the option element (see this: http://www.w3schools.com/TAGS/tag_option.asp)
the solution you propose would be difficult to pull off using javascript or jquery unless you override the entire select with a custom element.
alert("--1".replace("--", ""));
so:
$("select").change(function() {
$("#someInput").val($(this).val().replace("--", ""));
});
Try it here.
If want just to replace all entrys, you can call
$(function() {
$('select').find('option').each(function(index,elem) {
$(elem).text(function(i, text) {
return text.replace(/^--/, '');
});
});
});
if you want to replace an entrys only when selected do
$(function() {
$('select').bind('change', function() {
var self = this;
$(this).find('option:selected').text(function(i, text) {
if( self.last )
$(self.last).text(function(i, oldtext) {
return '--' + oldtext;
});
self.last = this;
return text.replace(/^--/, '');
});
});
});
Demo: http://www.jsfiddle.net/4yUqL/39/
精彩评论