function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sp13sp13 

Pass apex variable to javascript variable

I need to show/hide a text(using javascript) depending on the value of variables in apex class
doing alert('{!s1}'); returns correct value but when i pass '{!s1}' to a variable(var var1 = '{!s1}';) it doesn't work.
how can i pass the string from apex class to a javascript variable and use it in if..else statement?

CONTROLLER:
public class SampleCC {
	public String s1 {get;set;}
	public String s2 {get;set;}

	public Sample() {
		s1 = 'true';
		s2 = 'false';
	}
}
Page:
<apex:page controller="SampleCC">
	<script>
		function onloads() {
			var var1 = '{!s1}';
			var var2 = '{!s2}';
			     //alert(var1);  <----this variable returns false even if the value of s1 is true
			if(var1='true' && var2='false') {
				alert('var1 is true, var2 is false');
				$("#one").show();
				$("#two").hide();
			} else {
				alert('var2 is true, var1 is false');
				$("#one").hide();
				$("#two").show();
			}
		}
	</script>
	
	<script type="text/javascript">    
        window.onload=onloads; 
    </script>
	
	<body onload="onload()">
		<div id="one">
			text1
		</div>
		<div id="two">
			text2
		</div>
	</body>
</apex:page>




Ankit AroraAnkit Arora
JS gets the values on page load. So later if values are getting changed and you want same value in JS then you just need to reRender the JS on any action.

Let me know if it works.