HTML Select Menu - change Javascript variable on change

advertisements

I have a Javascript that stores a variable for a default phone number, but I would like users to be able to override this based on the options in a select menu. If they make a selection from the menu I would like the Javascript variable to be updated with the new value from the selected option.

Here's the script:

$("#callContact1").click(function() {
  $.ajax({
      url: "https://www.server.com/callback.php?recipientNumber=0412345678&type=makecall",
      data: {},
      type: "GET"
    })
    .then(function(data) {
      $('#ajaxResponse').html(data).show();
    })
    .fail(function(xhr) {
      var httpStatus = (xhr.status);
      var ajaxError = 'There was an requesting the call back. HTTP Status: ' + httpStatus;
      console.log('ajaxError: ' + ajaxError);
      //make alert visible
      $('#ajaxResponse').html(ajaxError).show();
    })
})

I would like to edit the value of the 'recipientNumber=0412345678' in the url of the AJAX request function whenever this select menu is changed:

<select class="form-control" name="callBackNumber" id="callBackNumber">
<option value=""></option>
<option value="0418468103" selected>Mobile (0412345678)</option>
<option value="0294846565">Work (0299887766)</option>
<option value="0233445566">Home (0233445566)</option>
</select>

I'm not sure if this is possible or if there is a better way to construct this to achieve the same result?


Create a global variable with your defaultPhoneNumber.

var defaultPhoneNumber = $("#callBackNumber").val();

Update that variable on change of dropdownlist.

$("#callBackNumber").change(function(){
  defaultPhoneNumber  = $(this).val();
});

And use updated value in URL

 $.ajax({
      url: "https://www.server.com/callback.php?recipientNumber="+ defaultPhoneNumber  +"&type=makecall",
      data: {},
      type: "GET"
});