+ Start a Discussion

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?

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

	public Sample() {
		s1 = 'true';
		s2 = 'false';
<apex:page controller="SampleCC">
		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');
			} else {
				alert('var2 is true, var1 is false');
	<script type="text/javascript">    
	<body onload="onload()">
		<div id="one">
		<div id="two">

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.