I am trying to achieve the following result:
There is a <select>
control. Below that is a textbox
. I want to assign the value entered in this textbox to the value
attribute of a particular option
in the <select>
control.
For example:- Say, following is the <select>
dropdown:-
<select id="anyid">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="custom">Custom</option>
</select>
Say 4
is entered in the textbox
, then onkeyup
of the textbox, I want the value
attribute of the Custom
option to be 4
. So after this the <select>
options would be:-
<select id="anyid">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">Custom</option>
</select>
Any ideas? I would prefer jQuery over Javascript.
You should have a class/id assigned to your custom
option.
<option class="customOption" value="custom">Custom</option>
Then you can do:
$('#myTextBox').on('keyup', function () {
$('.customOption').val(this.value);
});
$(document).ready(function(){
$("textbox").keyup(function(){
var newValue = $(this).val();
$("option").each(function(){
if($(this).html() == "Custom")
{
$(this).val(newValue);
}
});
});
});
Please try above code.
<select id="anyid">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="custom">Custom</option>
</select>
<input type="text" onkeyup="fillCustomValue(this)"/>
<script>
function fillCustomValue(elem) {
document.getElementById('anyid').options[document.getElementById('anyid').options.length - 1].value = elem.value;
document.getElementById('anyid').options[document.getElementById('anyid').options.length - 1].innerHTML = elem.value;
}
</script>
Try this without jQuery
Try this
$('#va').keyup(function(){
$('#anyid option[value=custom]').attr('value',$(this).val())
});
OR
$('#va').keyup(function(){
$('#customIDofUrOption').attr('value',$(this).val())
});
You can use the $('#id').val() to set value for option.
$(document).ready(function () {
$("#myInput").keyup(function () {
$('#custom').val($("#myInput").val());
alert($('#custom').val());
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.