在<select>选项更改时更改只读输入值

时间:2019-01-09 20:48:58

标签: javascript html html5

我想根据从标签中选择的位置,在“选择>选项”中显示值。 这是html: 这是javascript: $(document).ready(function(){ $(“#stateCoord选项”).filter(function(){     返回$(this).val()== $(“#stateCoordInfo”)。val(); })。attr('selected',true); $(“#stateCoord”)。live(“ change”,function(){     $(“#stateCoordInfo”)。val($(this).find(“ option:selected”)。attr(“ value”)); }); }); 我仍然对javascript有所了解,因此详细的说明不会受到影响。提前致谢。

4 个答案:

答案 0 :(得分:0)

我不确定是否是您需要的,但是我认为应该是:JSfiddle

这是JS代码:

$(document).ready(function() {

  $("#stateCoord").change(function() {
      var value = $("#stateCoord option:selected").text();
      $("#stateCoordInfo").val(value);
  });
});

答案 1 :(得分:0)

$(document).ready(function() {

     $("body").on("change","#stateCoord",function() {

     $("#stateCoordInfo").val($(this).find("option:selected").val());

});

   $("#stateCoord").trigger("change");
});

答案 2 :(得分:0)

From what I understand, you want to update the text shown in the readonly text box with the value attribute of the selected option from the dropdown.

To do this, you just need to update the val of your read-only text box to the val of the drop-down whenever change event is fired.

$(document).ready(function() {
  $('#stateCoord').change(function(e) {
    $('#stateCoordInfo').val($(this).val());
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="stateCoord" id="stateCoord" autocomplete="off">
       <option selected="selected">SELECT STATE</option>
       <option value="lg">Lagos</option>
       <option value="abj">Abuja</option>
</select>

<input type="text" name="stateCoordInfo" value="" id="stateCoordInfo"  readonly>

答案 3 :(得分:0)

If I assume correctly, you want this:

1) initialization of the select option at document ready, that strange thing the code with filter() was trying to do.

2) Capture the change event on the select and show the value of the current selected option on the input. This is what the live() (deprecated) part was trying to do.

$(document).ready(function()
{
    $("#stateCoord").val("").change();

    $("#stateCoord").change(function()
    {
        $("#stateCoordInfo").val($(this).val());
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select name="stateCoord" id="stateCoord">
  <option value="" selected>SELECT STATE</option>
  <option value="lg">Lagos</option>
  <option value="abj">Abuja</option>
</select>

<input type="text" name="stateCoordInfo" value="" id="stateCoordInfo">