Cao Felix Cao Felix - 7 months ago 14
Javascript Question

Change label when click on drop down list in jquery javascript

How can I implement multiple functions under the jquery javascript? The "Get Projects" button is working fine if I remove the second function (It actually works in my Eclipse project, for some reason it does not work if I remove the second function in here).

There are two things I want to achieve here:
1) Click "Get Projects" to add the projects into drop down list.
2) When selecting a different project from the list, the label will change the text based on what is selected.



$(document).ready(function () {
$('#projectbutton').click(function() {
var selector = document.getElementById('projectselector');
var api = "http://localhost:8080/restapi/test/projects";
$.getJSON(api, {"1":"project 1", "2":"project 2"},function (data) {
$.each(data, function (index, d) {
selector.options[selector.options.length] = new Option(d,d);
});
});
});
});
$(document).ready(function () {
$('#projectselector').change(function() {
var text = $('option:selected',this).text();
$('#selectedprojectname').text(text);
}
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="firstsection">
<h1>List project</h1>
<button id="projectbutton" name="projectbutton">Get Projects</button>
</div>
<div id="secondsection">
<h2>All available projects:</h2>
Projects: <select id="projectselector" name="projectselector"></select>
</div>
<div id="thirdsection">
<h3>Selected project:</h3>
<label id=selectedprojectname name="selectedprojectname">empty</label>
</div>




Answer

I'm not sure what you're trying to do in the getJSON call. The second parameter is just data sent to the API call, so you probably don't need what you're passing.

In any case, something is wrong with the API call. If you remove the API portion it works.

http://jsfiddle.net/CnEUh/3137/

$(document).ready(function () {
  $('#projectbutton').click(function() {
    var selector = document.getElementById('projectselector');
    var api = "http://localhost:8080/restapi/test/projects";
    var data = {"1":"project 1", "2":"project 2"};
      $.each(data, function (index, d) {
        selector.options[selector.options.length] = new Option(d,d);
      });
  });

  $('#projectselector').change(function() {
    var text = $('option:selected',this).text();
    $('#selectedprojectname').text(text);
  });
});

Your jQuery looks fine, but I can't help anymore with the API call unless you post the API code.

Comments