S.Rakin
S.Rakin

Reputation: 832

How to select type attribute of input tag based on a javascript variable as condition ?

I have a input tag to get text input from client side

<input type="text" class="form-control" placeholder="Enter Message" id="messageText"  autofocus/>

Now I want to select the type attribute based on a javascript variable password_flag

If password_flag==1 then type="password" else type="text"

So, when password_flag will be set user will be able to give password input

As I have been using uwsgi as server, I can't use FreeMarker to invoke conditions.

Upvotes: 1

Views: 387

Answers (3)

Srinath
Srinath

Reputation: 295

You can even achieve it by using event inline

var password_flag = 1;
//var password_flag = 0;
<input type="text" class="form-control" placeholder="Enter Message" id="messageText"   onclick="password_flag?this.type='password':this.type='text'" autofocus />

Upvotes: 1

zb22
zb22

Reputation: 3231

You can do this with vanilla javascript as well:

var password_flag = 1;
  
var input = document.getElementById('messageText');
  
if(password_flag === 1){
	input.setAttribute('type','password');
} else{
 	input.setAttribute('type','text');
}
<input type="text" class="form-control" placeholder="Enter Message" id="messageText"  autofocus/>

Upvotes: 1

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

You can achieve this easily by the if-else condition:

$(document).ready(function(){
  var password_flag = 1; 
  if(password_flag === 1){
    $('#messageText').attr('type', 'password');
  } else {
    $('#messageText').attr('type', 'text');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" placeholder="Enter Message" id="messageText"  autofocus/>

Upvotes: 1

Related Questions