Change Selected Text When Selected
How do you change the selected text in a select box using jQuery?
Solution 1:
Try this:
$(document).ready(function() {
$('#name-select').change(function() {
var selectedItem = $('#name-select option:selected');
var oldValue = selectedItem.text();
var newValue = 'Name: ' + oldValue;
selectedItem.text(newValue);
});
});
You would need to update your select option to give it an ID though:
<selectid="name-select"><optgrouplabel="Name"><option>John</option><option>Mike</option></optgroup></select>
And here's the jsFiddle demo: http://jsfiddle.net/benmajor/2m76z/
Solution 2:
html:
<selectid="myselect"><optgrouplabel="Name"><option>John</option><option>Mike</option></optgroup></select>
js:
$("#myselect").change(function (event) {
var o = $("#myselect option:selected")
, v=o.text()
, old = $("#myselect option:contains('name')")
, oldv = old.html();
oldv && old.html(oldv.replace('name: ',''));
o.text('name: ' + v);
});
Solution 3:
If you add a value attribute to the option you could use something like this (and you need to add a value attribute otherwise you will loose the value if someone selects a value and then selects another value).
$("select").change(function () {
var label = $("select option:selected").parent().attr("label");
var val = $("select option:selected").attr("value");
$("select option:selected").html(label+":"+val);
});
Post a Comment for "Change Selected Text When Selected"