Search code examples
javascriptjquery-mobileselect-menu

JQuery Mobile: Disable and re-enable and refresh select menu option


I want to disable or enable certain options in a select menu based on another value. In the example, the user will enter a weight (on page stepOne) and if that value is greater than 3, then the option "quad" (on page stepTwo) must be disabled. If the value is less than or equal to 3, then the option "quad" must be enabled.

The html includes a weight input, and then a submit button which triggers the stepOneSubmission. What happens with the code below is that if the weight is above 3, the page will not change - I think it is getting stuck at the refresh - maybe because the select menu has not yet been created therefore cannot be refreshed???. If user enters a weight below 3 then the page change to stepTwo works. If user then navigates back to stepOne and enters a weight above 3, the stepOne Submission works this time, and "quad" is disabled.

function stepOneSubmission() {
var weight = $('#weight').val();
$('#weightTwo').val(weight);
var strengthSelect=$("#strength");
if (weight>3)
{
$("#strength option[value=4]").prop('disabled',true);
strengthSelect.selectmenu("refresh");
$.mobile.pageContainer.pagecontainer("change", "#stepTwo");
}
$.mobile.pageContainer.pagecontainer("change", "#stepTwo");
};
function stepTwoSubmission() {
$.mobile.pageContainer.pagecontainer("change", "#theReport");
};

Solution

  • I did not succeed with the above approach. Instead I split off the select option changes from the form submission. I made a new function setStrengthValues to rebuild the select options according to weight and which runs on key up of the weight field.

    function setStrengthValues(){
    
    var weight = $('#weight').val();
    $('#weightTwo').val(weight);
    var strengthSelect=$("#strength");
    var selectValues = [{"single": "Single", "double": "Double", "quad": "Quad"}];
    if (weight >= 3) {
     $("#strength").find('option').remove();
     $(selectValues[0]).each(function (key, value) {
         $.each(selectValues[0], function (key, value) {
             strengthSelect
             .append($("<option></option>")
             .attr("value", key)
             .text(value));
         });
     });
    strengthSelect.find('option:contains(' + selectValues[0].quad + ')').remove();  
    strengthSelect.val('Single');
    strengthSelect.selectmenu("refresh");       
    } 
    else {
        $("#strength").find('option').remove();
        $(selectValues[0]).each(function (key, value) {
            $.each(selectValues[0], function (key, value) {
            strengthSelect
             .append($("<option></option>")
             .attr("value", key)
             .text(value));
         });
     });
    strengthSelect.val('Single');
    strengthSelect.selectmenu("refresh");
    }       
    };
    function stepOneSubmission() {
    $.mobile.pageContainer.pagecontainer("change", "#stepTwo");
    };