user1881815 user1881815 - 7 months ago 20
Javascript Question

Basic function and if statement not working in jQuery

Here's my code:

<button id="addSubject" type="button">+</button>
<script>
$('#addSubject').click(function()
{
function optionExists(mySelect, val)
{
return $("#"+mySelect+" option").filter(function() {
return this.value === val;
}).length !== 0;
}

if (optionExists($('#subjectCategories'), $('#fieldNewSubject').val()))
{
$('#subjectCategories').append("<option value=\"" + $('#fieldNewSubject').val() + "\">" + $('#fieldNewSubject').val() + "</option>");
$('#fieldNewSubject').val("");
});
</script>


Here's my quetion: Why won't it work? Nothing happens when I click on the button!
I did put this in the header:

<script src="js/jquery.ui.button.js"></script>
<script src="js/jquery-1.8.2.min.js"></script>

Answer

If I guessed your intention correctly, this should do the same:

$('#addSubject').click(function () {
  var
    val = $('#fieldNewSubject').val(),
    $select = $('#subjectCategories');

  if ($select.find('option[value="' + val + '"]').length === 0) {
    $('<option>', {
      value: val,
      text: val
    }).appendTo($select);
  }
});

http://jsbin.com/usadoq/1/