JavaScript to hide sharepoint fields reruns when form is submitted and required fields are missing

sharepoint.stackexchange https://sharepoint.stackexchange.com/questions/250017

  •  24-01-2021
  •  | 
  •  

Domanda

Thank you for taking the time to read my question.

I have a simple script in a SharePoint NewForm.aspx which initially hides a field on the form and then displays it if Yes is chosen in response to a question field. Here's the code:

<script src="https://code.jquery.com/jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
 $(document).ready(function() {
    //Hide fields initially 
    $('nobr:contains("abc")').closest('tr').hide();
    //Show field if Yes is chosen from the drop down list
    $("select[title$='My question here?']").change(function()   {
    if($(this).val() == "Yes" ) {
        $('nobr:contains("abc")').closest('tr').show();
    } else {
        $('nobr:contains("abc")').closest('tr').hide();
    }
});
});
</script>

The problem with it is that some of the fields in the form are required fields, and if the user submits the form without completing the required fields, then:

  1. The field that needs to be completed is highlighted, which I want
  2. The script above is rerun and the form field is hidden again, which I don't want

How do I prevent the hide script being rerun?

Hoping someone can help.

È stato utile?

Soluzione

I'm not a 100% sure on this, but here is what I normally do... Rather than keeping the script from reruning, the script should be able to run again without breaking the behaviour. You are telling the form to perform an action when a field changes, which is good for user input, but the script needs to know what to do if the value is already set (which should be the case scenario for the edit form too).

In this case, I would prompt the script to validate if the value of the field is "Yes" before the user's input.

<script type="text/javascript">

$(document).ready(function() {
    //Validate field initially
    if($("select[title$='My question here?']").val() == "Yes" ) {
        $('nobr:contains("abc")').closest('tr').show();
    } else {
        $('nobr:contains("abc")').closest('tr').hide();
    }

    //Show field if Yes is chosen from the drop down list
    $("select[title$='My question here?']").change(function()   {
    if($(this).val() == "Yes" ) {
        $('nobr:contains("abc")').closest('tr').show();
    } else {
        $('nobr:contains("abc")').closest('tr').hide();
    }
});
});
</script>

Again, not 100% sure, I hope it helps!

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a sharepoint.stackexchange
scroll top