JaMes
JaMes

Reputation: 607

Variable is empty with jQuery

I would like to run a code only if the date of my task is not empty. But currently, the code is running with a empty date. Can you explain me where is my error ?

var date = '<%[email protected]%>'
if( date != null){
  $('.sn_date').html('<i class="fa fa-calendar-o" id="fa_icons"></i><%[email protected]("%d %b")%>')
}

Upvotes: 0

Views: 146

Answers (3)

Rnice4christ
Rnice4christ

Reputation: 78

Have you tried validating with Ruby then dumping out your JS if the date is present?

<% if (@task.date.present?) %>
 $('.sn_date').html('<i class="fa fa-calendar-o" id="fa_icons"></i><%[email protected]("%d %b")%>')
<% end %>

Upvotes: 1

Dima I. Belinski
Dima I. Belinski

Reputation: 381

First case:

<script>
var date = <%[email protected]?%>
if( date){
  $('.sn_date').html('<i class="fa fa-calendar-o" id="fa_icons"></i><%[email protected]("%d %b")%>')
}
</script>

if @task.date is nil or empty, .present? will return false, else true. In any conditions your var date will be boolean.

Second case:

<script>
var date = <%[email protected]%>
if( !!date){
  $('.sn_date').html('<i class="fa fa-calendar-o" id="fa_icons"></i><%[email protected]("%d %b")%>')
}
</script>

in this case your var date will be string, does not matter what will return @task.date, nil or string date. And now in js you should verify if var date not empty string if (!!date) {}.

if date = '' => !!date return false

if date = 'date' => !!date return true

Upvotes: 1

NEFEGAGO
NEFEGAGO

Reputation: 281

you can validate with " " empty, something like that if (date != ""){ your sentence.... }

Upvotes: 0

Related Questions