List field contents not displaying with .val function

Viewed 48

I'm running this script in a custom script box of some workflow software. I want the user to have specific fields hide or show based on the list value. This script is on pages after the user picked the list field value. So this loads on a page where the list field is populated. The script works - it shows and hides the correct fields, BUT it makes the value selected not visible. The field is there, but the value is blank.

I've also tried removing the document.ready function at the beginning. I've tried removing val(function() and putting it all into the if statement.

$(document).ready(function() {
  $("#ctl00_mainContent_qtWfInstance_ctl00_ctl01_lstValues").val(function() {
    if ($(this).val() == "One") {
      $("#CustomFieldWrapper_1277_0_0").show();
      $("#CustomFieldWrapper_1303_0_0").hide();
    }
    if ($(this).val() == "Two") {
      $("#CustomFieldWrapper_1303_0_0").show();
      $("#CustomFieldWrapper_1277_0_0").hide();
    }
  });
});

I'm wondering why the list field's selected value doesn't display? The drop down is there, and the list field can be updated (it is editable on the next step). It is showing and hiding correctly based on the value that was selected in the last step.

3 Answers

Use .val(index, value) default parameters.

EDIT: And as @BrandonHill suggested, return the input value at the end of your function.

$(document).ready(function() {
    $("#ctl00_mainContent_qtWfInstance_ctl00_ctl01_lstValues").val(function(index, value) {
        if (value == "One") {
            $("#CustomFieldWrapper_1277_0_0").show();
            $("#CustomFieldWrapper_1303_0_0").hide();
        }
        if (value == "Two") {
            $("#CustomFieldWrapper_1303_0_0").show();
            $("#CustomFieldWrapper_1277_0_0").hide();
        }
      return value; // Add this line
    });
});

The reason is that, using .val() defines its selector the value returned inside, and if you don't have any return it will return undefined which won't be equal to One nor Two anytime.

For this to work, #ctl00_mainContent_qtWfInstance_ctl00_ctl01_lstValues must be an input.

For more information you can read jQuery official documentation.

This is jQuery, not javascript. The .val(function) method will set the input value to the returned value of the function, which in this case is null/undefined. If you accept the second argument in your function you can just return that.

Thank you so much!!!! It now shows the value in the box and if I change the value and save the workflow, it re-loads the page with the new value and showing the correct fields!

All I did was add the return value; line. I did not add the (index, value) I left that as ().

Related