jquery - How to add/remove options in a single select element with javascript -


i working on jquery project. have form 2 single select elements ie. programtype , programofinterest. programofinterest child of programtype. have placed ajax call inside programtype's change function sends id of selected programtype server, use id query database related programofinterest objects , send javascript. problem have populated programofinterest field data backend. want know whether there way remove/add options single select element using jquery?

hint: while working multiple select used uncheck options this

var tag_options = document.getelementbyid("category_categoryname").options; for(var = 0; < tag_options.length; i++){ tag_options[i].selected = false; } 

i hoping can similar add/remove options in single select. ideas?

$("#category_categoryname").empty(); clear existing options

$("#category_categoryname").find('option[value="1"]').remove(); clear option "value" attribute of 1.

$("#category_categoryname").append($("<option/>", { "value": "2", text: "option 2" }); add new option select.

this using jquery syntax. mentioned jquery project, although example code not contain jquery, assume you're happy solution use it.

here's demo:

$(function() {    $("#btngo").click(function() {      updateselect1();      updateselect2();    });      function updateselect1() {        $("#category_categoryname").empty();        $("#category_categoryname").append($("<option/>", {        "value": "4",        "text": "option 4"      }));    }      function updateselect2() {        $("#category_categoryname2").find('option[value="1"]').remove();        $("#category_categoryname2").append($("<option/>", {        "value": "4",        "text": "option 4"      }));    }  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <form>    <select id="category_categoryname">      <option value="1">option 1</option>      <option value="2">option 2</option>      <option value="3">option 3</option>    </select>    <br/><br/>    <select id="category_categoryname2">      <option value="1">option 1</option>      <option value="2">option 2</option>    </select>    <br/><br/>    <button id="btngo" type="button">run demo</button>  </form>


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -