user6558380
user6558380

Reputation:

Javascript check dropdown value against textbox

I need to check textbox value against dropdown list, and if that value does not exist, add to the list.

I have this script:

            <select id="drop" onchange="ChooseContact(this)">
              <option value="Volvo Red">Volvo Red</option>
              <option value="Mers Blue">Mers Blue</option>
              <option value="Ferr red">Ferr red</option>
            </select>

function execute(data) { 
    var txtbox = document.getElementById ("txtServiceReportInspectedBy").value;
        if ( document.createElement('option').value != txtbox ) {
            var categories = document.getElementById("drop");
            var newOption = document.createElement('option');
            newOption.innerText = txtbox ;
            newOption.setAttribute('value', txtbox );
            categories.appendChild(newOption);
        }
    document.getElementById("drop").value = txtbox ;
}

But the new item is still created in the dropdown list, eventhough such item already there. Thanks.

Upvotes: 0

Views: 210

Answers (2)

trincot
trincot

Reputation: 350477

You are not searching for the text among the options. Here is how you could do that:

add.addEventListener('click', execute);

function execute(data) { 
    var txtbox = txtServiceReportInspectedBy.value,
        optionTexts = Array.from(document.querySelectorAll('#drop>option'), 
                                 option => option.value);
    if ( !optionTexts.includes(txtbox) ) {
        var newOption = document.createElement('option');
        newOption.value = newOption.textContent = txtbox ;
        drop.appendChild(newOption);
    }
    drop.value = txtbox;
}
<input id="txtServiceReportInspectedBy"><button id="add">Add</button><br>
<select id="drop">
  <option value="Volvo Red">Volvo Red</option>
  <option value="Mers Blue">Mers Blue</option>
  <option value="Ferr red">Ferr red</option>
</select>

Upvotes: 1

Jovani Martinez
Jovani Martinez

Reputation: 79

On your "if" sentence you are creating a new element "option" so always is going to be different your "value", so always is going to create a new element inside your "select" tag You need to iterate for the elements of your "select" tag to find if its value exist or not

Upvotes: 0

Related Questions