开发者

div to show select menu value with jquery

i have a question regarding Jquery

    <select id="thechoices">
<option value="0">Select Box</option>
<option value="box1">Box 1</option>
<option value="box2">Box 2</option>
<option value="box3">Box 3</option>
</select>

<!-- the DIV -->
<div id="value"> disabled till you 开发者_开发知识库make a choice</div>

while the select menu have the choice Select box i need the div to be shown as a small black screen with the disabled message once the user change the select menu and choose another option the value div shown the selected option for example Box 1 or Box 2


$(document).ready(function() {
    // event triggered when options changed
    $('#thechoices').change(function() {
        // check if first option or other is selected
        if ($(this).val() == 0) {
            $('#value').addClass('disabled');
            $('#value').html($('#value').data('default'));
        } else {
            $('#value').removeClass('disabled');
            $('#value').html($(this).val());
        }
    });
});

Check out the fiddle: http://jsfiddle.net/gwKfP/1/


Here is a working Example: http://jsfiddle.net/sHqFX/

<select id="thechoices">
<option value="0">Select Box</option>
<option value="box1">Box 1</option>
<option value="box2">Box 2</option>
<option value="box3">Box 3</option>
</select>

<!-- the DIV -->
<div id="value"></div>

Put this between head tags

<script type="text/javascript">
$(document).ready(function(){
    $("#thechoices").change(function(){

       if($(this).val() == 0)
       {
           $("#value").html("disabled till you make a choice");
            $("#value").css("background-color","black");
                 $("#value").css("color","white");
       }
        else{
            $("#value").html($("#thechoices option:selected").text());
            $("#value").css("background-color","white");
            $("#value").css("color","black");
        }
    });
});
</script>


Here's a quick solution, just add this code:

CSS:

<style>
  .disabled{
    background-color: gray;
  }
</style>

JavaScript

function onSelectedOption(){
   var selectedText = $("#thechoices option:selected").text();
   if($("#thechoices").val() == "0")
     $('#value').addClass("disabled").text(selectedText );
   else
     $('#value').removeClass("disabled").text("");
}

$(document).ready(function(){
  onSelectedOption(); //With this we 'disable' when page loads
  $('#thechoices').change(onSelectedOption);
});

Hope this helps


Use the jQuery 'change' event. http://api.jquery.com/change/

$('#thechoices').change(function(){
    $('#value').css('display','block');
});


$('#thechoices').change(
  function() {
    $('#value').text(
      $('#thechoices :selected').text()
    )
  }
);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜