简体   繁体   中英

Change the value of label with change in drop-down value using JQuery

I am trying to change the value of label with change in drop-down value using jQuery but its not working. Please help me fix this.

<select id="myselect">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
</select>
<br/>
<label id="label"></label>
<br/>
$("label").val("150.000.000");
$(("#myselect").val()).on('change', function() {
    if ($("#myselect").val() == '1') {
        $("#label").val("150.000.000");
    } else  {
        $("#label").val("350.000.000");
    }
});

Your selector attached to the change event is incorrect, you need to provide the id of the element as a string, not the value of the element itself. Also, label elements don't have a value you need to use text() to change them, and you can use this within the change handler to refer to the select element. Try this:

 $("label").text("150.000.000"); $("#myselect").on('change', function() { if ($(this).val() == '1') { $("#label").text("150.000.000"); } else { $("#label").text("350.000.000"); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="myselect"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> <br/> <label id="label"></label> <br/> 

You can even shorten the JS code to this:

$("label").text("150.000.000");
$("#myselect").on('change', function() {
    $("#label").text(function() {
        return $(this).val() == '1' ? "150.000.000" : "350.000.000";
    })
});

You can save all values in an array and can use value to compute index of value to be selected.

Following snippet depicts the same:

 var data = ["150.000.000", "350.000.000", "550.000.000", "750.000.000"]; $("#myselect").on("change", function() { var selectedVal = $("option:selected",this).val(); var newValue = data[parseInt(selectedVal)-1]; $("#label").text(newValue); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <select id="myselect"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> <br/> <label id="label"></label> <br/> 

Try this code:

  $(document).ready(function() {
  $("label").text("150.000.000");
  $("#myselect").on('change', function() {
    if ($("#myselect").text() == '1') {

      $("#label").text("150.000.000");

    } else {

      $("#label").text("350.000.000");
    }
  });
});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM