2

I have a webpart i need to add multiple times on a webpage, how can I restrict in javascript the the variable to read from each webpart property?

In webpart ascx file, I have hidden fields like:

<asp:HiddenField ID="SiteName" runat="server" />

In my javascript code i read this sitename and do something with it. If i insert the webpart multiple times on a webpage, it will have the javascript inserted many times.

1- how do I handle the multiple javascripts added to the webpage with same webpart referenced on the webpage

2- in javascript functions, i am getting the value where ID contains "SiteName", how will this work with multiple webparts on the same page?

thank you

0

1- how do I handle the multiple javascripts added to the webpage with same webpart referenced on the webpage

Answer - As you want to avoid loading multiple java scripts on page, it means you want to load only once. Move this java script code in js file and refer it in page, rather than referencing it in every page.

Alternately you can tweak your logic of writing javascript using document.write

//Below script goes in your master page

<script type="text/javascript">
var IsJsLoaded = false;
</script>

//below goes in your webpart

<script type="text/javascript">
if(IsJsLoaded == false){
// write our javascript code.
document.write("write you javascript code here")
IsJsLoaded = true; // set variable to true...
}

</script>

2- in javascript functions, i am getting the value where ID contains "SiteName", how will this work with multiple webparts on the same page?

Answer - this should work as expected because hidden variable scope would be webpart, when rendered on page hidden variable id will have webpart id embed so each webpart has its unique hidden variable.

  • But as I said, I am getting the hidden fields where ID contains.. in this case, all fields let's say: SiteName, will contain SiteName, and they are all rendered in the DOM even though the webpart ID is concatenated with them. So how do I choose the right ID? Thanks – Jennifer T Dec 10 '16 at 6:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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