I have the below html code:
<select class="1-100"></select>
I am using Jquery to populate the value of above select option:
$(function(){
var $select = $(".1-100");
for (i=1;i<=100;i++){
$select.append($('<option></option>').val(i).html(i))
}
});
This gives me a drop down with values from 1 to 100. I want to trigger a function when I select a number from this drop down. The function should return the number I selected in the dropdown(displayed on window). How I accomplish this?
HTML :-
<select class="1-100"></select>
<textarea id="mytext"></textarea>
Jquery :-
$('select.1-100').on('change',function(){
alert($(this).val());
$('#mytext').val($(this).val());
});
$(function(){ var $select = $(".1-100"); for (i=1;i<=100;i++){ $select.append($('<option></option>').val(i).html(i)) } $('select.1-100').on('change',function(){ alert($(this).val()); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select class="1-100"></select>
html
<label></label>
<select class="1-100"></select>
in js
$(function(){
var $select = $(".1-100");
for (i=1;i<=100;i++){
$select.append('<option value="'+ i +'">'+ i +'</option>');
}
$('select').on('change',function(){
$('label').text($(this).val());
});
});
You can try to attach the on change
handler:
$(function() { var $select = $(".1-100"); for (i = 1; i <= 100; i++) { $select.append($('<option>').val(i).html(i)); } $select.on('change', function() { alert(this.value); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select class="1-100"></select>
This can be accomplished using the change
event on the <select>
element.
The value of the <select>
can be fetched using .val()
.
Here's a working snippet:
$(function(){ var $select = $(".1-100"); for (i=1;i<=100;i++){ $select.append($('<option></option>').val(i).html(i)) } $(document).on('change', 'select', function(){ alert($(this).val()); $('span').text($(this).val()); $('textarea').val($(this).val()); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label>Select a value: </label><select class="1-100"></select> <p>Selected value = <span></span></p> <textarea></textarea>
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.