0

This is a following on question from Enable/disable checkbox determind by users input

Instead of a checkbox, my boss wants to have a drop down list. So now when the user enters his contact number. If the contact number starts with 01 then 'Send updates by SMS' is removed from the drop down list.

I have written some code to reflect this and it removes the SMS from the list if the user enters 01, but then if he changes it to an 07 number the SMS doesn't return back to the list. I have tried adding select.add to the else but this failed to work.

function deselectcheckbox(wildvalue) {
 if (document.getElementById("tel_num").value.startsWith("01")) {
  var select=document.getElementById('send_updates');
   for (i=0;i<select.length;  i++) {
   if (select.options[i].value=='SMS') {
    select.remove(i);
   }
  }
 }
 else
 {
  SOMETHING IN HERE TO CHECK TO SEE IF SMS IS MISSING AND TO ADD IT IF IT IS
 }
}

html:

<table>
<tr>
 <td>Contact Number</td>
 <td>
 <input type="text" name="tel_num" id="tel_num" value="" onkeyup="deselectcheckbox(this.value)"></td>
</tr>
<tr>
 <td>
  <select name="send_updates" id="send_updates" required>
   <option value="" selected>Please Select....</option>
   <option value="SMS">Send updates by SMS</option>
   <option value="Email">Send updates by Email</option>
  </select> 
 </td>
</tr>
</table>

I know I need to add something to the else statement but not sure what.

Thanks

Rick Kap
  • 159
  • 1
  • 9
  • This seems like it might lead you in the right path -- https://stackoverflow.com/questions/8674618/adding-options-to-select-with-javascript – Kevin Mee May 22 '18 at 19:11

1 Answers1

1

Use this script:

var opt;
function deselectcheckbox(wildvalue) {
var select=document.getElementById('send_updates');
 if (document.getElementById("tel_num").value.startsWith("01")) {
   for (i=0;i<select.length;  i++) {
   if (select.options[i].value=='SMS') {
    opt=select.options[i];
    select.remove(i);
   }
  }
 }
 else
 {
    select.append(opt);
 }
}
Liquidchrome
  • 894
  • 5
  • 10