1

I'm using a simple PreSaveAction() on my custom Edit Form. This is SharePoint 2013 on-premise. The goal is to validate a drop down menu against a text field. ie. If the Status drop down is set to "Unfilled" then ensure that the "Unfilled reason" text field has some text.

I added a Script Editor Webpart to the page and added the following code:

<script src="https://shoreline/sites/sitename/SiteAssets/jquery-1.11.3.min.js"></script>

    <script language="javascript" type="text/javascript">

     function PreSaveAction()     
{
    alert("test");
    var val1 = document.getElementById('ctl00_ctl40_g_66098ca8_a834_4817_9ed3_147b323e8424_ff91_ctl00_DropDownChoice'); //get value from dropdown - Status
    alert("val1 Status = " + val1.value);
    var val2 = document.getElementById('ctl00_ctl40_g_66098ca8_a834_4817_9ed3_147b323e8424_ff101_ctl00_ctl00_TextField'); // get text field - Unfilled Reason
    alert("val2 unfilled reason = " + val2.value);
   if (val1.value = "Unfilled" && val2.value=="")
{
    alert("Please double check your information.");
    return false;
} else {
     return true;
}
}
</script>

The alerts are working and showing the correct values, however the Status field which is defaulted to "Pending" (or could be anything previously selected in the drop down) automatically clears to blank - but then saves using the default "Pending" even when it changed to "Unfilled".

Any idea why this is happening or how to prevent it?

2 Answers 2

1

In your “if” you have val1.value = “Unfilled” which is an assignment. I think you want “==“ for a comparison...

1

Would receommend to use SPUtility javascript library. Hard coded element ids wouldn't work when a new field is added to the list/library because they get changed. SPUtility is a free javascript library to handle this efficiently.

Please try this sample code (Modify as require). It should alert if the status is Unfilled. If not, please check for any error in the console.

<script src="https://shoreline/sites/sitename/SiteAssets/jquery-1.11.3.min.js"></script>
<script src="https://shoreline/sites/sitename/SiteAssets/sputility.min.js"></script>

<script language="javascript" type="text/javascript">

    function PreSaveAction(){
        alert("test");

        var val1 = SPUtility.GetSPField('Single Choice Field');
        alert("val1 Status = " + val1.GetValue());

        var val2 = SPUtility.GetSPField('Text field');
        alert("val2 unfilled reason = " + val2.GetValue());

        if (val1.GetValue() == "Unfilled" && val2.GetValue()==""){
            alert("Please double check your information.");
            return false;
        } 
        else 
            return true;

    }
</script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.