Jewell Ellis Jewell Ellis - 4 months ago 14
HTML Question

My Javascript function keeps running/looping

I have a script that I am trying to run on a SharePoint page. This is for an HTML form Web part. When the page is loaded i would like to automatically set the default value to "blank". I am VERY new to javascript, but I needed this done immediately so I took to google for some assistance. I was able to find this script and made modifications to it. Please help find what I am doing wrong, the page keeps refreshing until it times out.

<table cellpadding="0" cellspacing="0" width="100%" border="0">



<tr>

<td align="left">

<span class="CCSPDDLLabel">For Legacy vs Spectrum :</span>

<select name="LegacyVsNew" onchange="LegacyVsNewChangeCategory(this)">
<option value="New" selected="selected">New</option>
<option value="New">New</option>
<option value="Legacy">Legacy</option>
</select>

</td>

</tr>

</table>



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

var fieldName = document.getElementsByTagName('select')[0];
var fieldNameValue = fieldName.options[fieldName.selectedIndex];
var fieldNameText = fieldName.options[fieldName.selectedIndex].text;



LegacyVsNewChangeCategory();

function LegacyVsNewChangeCategory()
{


if(fieldNameValue.value)
_SFSUBMIT_();


else
location.href="/features/custom-filter-html-form"
}


</script>


Thanks

Answer

When the page is loaded i would like to automatically set the default value to "blank".

You have the first option selected by default.

<option value="New" selected="selected">New</option>

Try this instead:

<option selected="selected">Select...</option>
<option value="New">New</option>        
<option value="Legacy">Legacy</option>

But even taking the step above, you will always have a value selected, and you're running a redirect in the function anyway.

You're calling your function on page load. The function checks to see if something is selected, and either runs _SFSUBMIT_(); if something is selected, otherwise it runs a redirect. Being that your page starts with something selected, it will continously run _SFSUBMIT_();. If it doesn't have a selected value, it will just immediately redirect you.

JSFiddle to demonstrate: https://jsfiddle.net/syg0wv82/

Comments