To display a variable with alert

I want to display a variable with alert I wrote the following code but instead of displaying the variable it shows me object
{{name}} is normal display

<script language="javascript">
var nom = $('name').text();
 alert("Hello there this food" + nom + ". is experd.");
</script>
instead of nom he shows me object```

name is part of a Template’s data ?

Your jQuery selector seems wrong, unless you created custom elements, such an element (<name />) is not supposed to exist. Instead, just select the element that contains {{ name }}.

yes name is part of a Template’s data
i try alert(“Hello there this food” + {{ name }} + “. is experd.”);
it dosnt work

This is normal, you can’t use Blaze tags in JS code. Only in HTML templates.
From where do you want to grab the name ? (onCreated, a helper, an event, …)

1 Like

I’m not quite sure what you’re mean
name is a variable enter by the user

Let’s say you display the name property in a Template this way :

<template name="xxx">
  ...
    <div class="item-name">{{ name }}</div>
  ...
</template>

With some JS, you can grab this value like this (as a general example) :

var name = document.querySelector( '.item-name' ).innerHTML;
alert( name );

my template

<template name="xxx">
<article class="recipe {{#if inMenu}}in-menu{{/if}}">
		<h3>{{name}}</h3>
</template>

i shoud write this ?

var name = document.querySelector( '.recipe {{#if inMenu}}in-menu{{/if}}' ).innerHTML;

You can’t use Blaze tags {{ ... }} in JS code, only in HTML templates.
You are trying to put a HTML condition in a JS selector, remove it, and add the h3.

If you want to automatically alert() the name once the Template “xxx” is rendered, you should try this :

Template.xxx.onRendered(function () {
  var name = this.find( '.recipe h3' ).innerHTML;
  alert( name );
});

thanks for the help
but i want this

<script language="javascript">
 var isAfter = moment(date).isAfter(now);
 if(!isAfter)
 alert("Hello there this food" + name  + ". is experd.");
</script>

```so i cant do this in js code?

Where did you put this <script> ?

i put the script in html page
where i display the name {{ name }}

i tried this instead the script

Template.Recipe.onRendered(function () {
var date = $('dateexp').val();
 var now = moment();
 var isAfter = moment(date).isAfter(now);
var name this.find( '.recipe h3' ).innerHTML;
 (if isAfter){
  
  alert( name );
}
});

```Unexpected token

You tried this, and ?

Your if condition is incorrect.

i correct my if condition and it still show me msg Unexpected token

Your variables declarations are still incorrect.

I can’t, just can’t… this whole topic. :joy::joy::joy::joy::joy::joy::joy::joy::joy::joy:

3 Likes