Error: anticipated expression, received keyword 'if'

I'm facing an issue that I could really use some assistance with. I am trying to hide the "changeOrderUp" button when it's in the first row, and similarly, I want to hide the "changeOrderDown" button when it's in the last row. However, FireBug is throwing an error: "SyntaxError: expected expression, got keyword 'if'". I am struggling to figure out the cause of this error. Any help would be greatly appreciated!

Below is my javascript code snippet:

for(var ordem = (data.var_pergunta).length; ordem >= 1 ; ordem--){
    $('<tr><td class="ordem-pergunta-'+ordem+'">'+ordem+'</td> \
    <td class="ds-pergunta-'+ordem+'">'+data.var_pergunta[ordem - 1].ds_pergunta+'</td>  \
    <td class="cd-pergunta-'+ordem+' hide">'+data.var_pergunta[ordem - 1].cd_pergunta+'</td> \
    <td><button id="'+ordem+'" class="btn-change-order-up btn btn-primary '+if(ordem == 1){ document.write('hide');}+'" type="button"><i class="fa fa-angle-up"></i></button> \
    <button id="'+ordem+'" class="btn-change-order-down btn btn-info '+if(ordem == (data.var_pergunta).length)){ document.write('hide');}+'" type="button"><i class="fa fa-angle-down"></i></button>  \
    </td></tr>').insertAfter('.tr-ordem-pergunta');
                        }

Answer №1

When working with Javascript, it's important to note that inline if conditionals are not allowed. Instead, you should utilize the ternary operator, which functions similarly to an if block.

Avoid using document.write as it does not return a string for concatenation but overwrites the document and displays only the specified string on the page.

In place of

if(ordem == 1){ document.write('hide');}

You can use something like

(ordem === 1 ? 'hide' : '')

This approach:

  1. Compares ordem strictly to 1 (=== is stricter than ==)
  2. Returns 'hide' if the comparison is true
  3. Returns an empty string otherwise

To simplify your code further, consider adding a + at the end of each line instead of escaping the newline. Using an escape character makes the code less readable.

For consolidation, you could refactor the snippet as follows:

for (var ordem = data.var_pergunta.length; ordem >= 1; --ordem){
  $('<tr><td class="ordem-pergunta-' + ordem + '">' + ordem + '</td>' +
    '<td class="ds-pergunta-'+ordem+'">' +
      data.var_pergunta[ordem - 1].ds_pergunta +
    '</td>' +
    '<td class="cd-pergunta-'+ordem+' hide">' +
      data.var_pergunta[ordem - 1].cd_pergunta +
    '</td>' +
    '<td><button id="'+ordem+'" class="btn-change-order-up btn btn-primary ' +
      (ordem === 1 ? 'hide' : '') +
    '" type="button"><i class="fa fa-angle-up"></i></button>' +
    '<button id="'+ordem+'" class="btn-change-order-down btn btn-info ' +
      (ordem === data.var_pergunta.length ? 'hide' : '') +
    '" type="button"><i class="fa fa-angle-down"></i></button>' +
    '</td></tr>').insertAfter('.tr-ordem-pergunta');
}

If your string is lengthy, consider utilizing a templating library such as Handlebars.js. By converting your string into a template, it could look like this:

<tr>
  <td class="ordem-pergunta-{{ordem}}">{{ordem}}</td>
  <td class="ds-pergunta-{{ordem}}">{{prev_ordem.ds_pergunta}}</td>
  <td class="cd-pergunta-{{ordem}} hide">{{prev_ordem.cd_pergunta}}</td>
  <td>
    <button id="{{ordem}}" class="btn-change-order-up btn btn-primary {{#if first_ordem}}hide{{/if}}" type="button">
      <i class="fa fa-angle-up"></i>
    </button>
    <button id="{{ordem}}" class="btn-change-order-down btn btn-info {{#if last_ordem}}hide{{/if}}" type="button">
      <i class="fa fa-angle-down"></i>
    </button>
  </td>
</tr>

To render this template:

template({
  ordem: ordem,
  prev_ordem: data.var_pergunta[ordem - 1]
  first_ordem: ordem === 1,
  last_ordem: order === data.var_pergunta.length
});

Answer №2

Give this a shot. Save the condition value in a variable and display it.

for(var order = (data.question_var).length; order >= 1 ; order--){
if(order == 1){ var value = document.write('hide'); }
if(order == (data.question_var).length)){ var next = document.write('hide');}
$('<tr><td class="order-question-'+order+'">'+order+'</td> \
<td class="description-question-'+order+'">'+data.question_var[order - 1].question_description+'</td> \
<td class="code-question-'+order+' hide">'+data.question_var[order - 1].question_code+'</td> \
<td><button id="'+order+'" class="btn-change-order-up btn btn-primary '+value+'" type="button"><i class="fa fa-angle-up"></i></button> \
    <button id="'+order+'" class="btn-change-order-down btn btn-info '+next+'" type="button"><i class="fa fa-angle-down"></i></button> \
    </td></tr>').insertAfter('.tr-order-question');
                        }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Upon page reload in Nuxt.js middleware, Firebase authentication is returning as null

Just started with nuxtjs and using the Nuxt firebase library for firebase integration. After a successful login, I'm redirecting the user to the "/member/desk" route. However, if I refresh the page on that particular route, it redirects me back to "/a ...

Angular prevents the page from reloading when using `$window.location`

I'm facing an issue while trying to refresh my admin page using Angular. I've come across $window.location.reload() and $route.reload(). I attempted to use $window.location.reload() by injecting $window into the function parameters. scope.uploadL ...

Retrieve the thousand separator for numbers using Angular in various languages

When using the English locale, numbers appear as follows: 111,111,222.00, with a comma as the thousand separator and a point as the decimal separator. In languages like German, the same number would be represented as 111.111.222,00, reversing the positions ...

What is the process for enabling HLS.js to retrieve data from the server side?

I have successfully implemented a video player using hls.js, and I have some ts files stored in https:/// along with an m3u8 file. To read the content of the m3u8 file, I used PHP to fetch it and sent the data to JavaScript (res["manifest"] = the content ...

Dealing with a 404 error when using the JQuery AJAX PUT method in ASP.NET MVC

My issue arises when attempting to update my data in ASP.NET MVC using jQuery AJAX with the PUT method. I am encountering a 404 error, indicating that my controller cannot be found. However, everything works fine when I use the GET or POST methods. What ...

Error message: It seems the spatial reference for this ESRI object is missing

Currently, I am utilizing Esri GIS to load the center location from an address. However, I am encountering an issue as I am using a geocoder from Google to obtain longitude and latitude, which is resulting in the following error message: TypeError: this.s ...

Tips for sending data through AJAX before the browser is about to close

My issue is with a javascript function that I've called on the html unload event. It seems to be working fine in Google Chrome, but for some reason it's not functioning properly in Firefox and IE. <script> function fun() { ...

JavaScript keydown event for rotating images

I am experiencing an issue with JavaScript animation. I have incorporated code from this particular link into my keydown function. However, the code is not functioning as expected. While the code from the provided link works fine on its own, within the key ...

Sending information to a jQuery UI Dialog

I'm currently working on an ASP.Net MVC website where I display booking information from a database query in a table. Each row includes an ActionLink to cancel the booking based on its unique BookingId. Here's an example of how it looks: My book ...

Ways to track all requests completed in Nuxt 3

I am looking to create a unique loading page that conceals itself once all requests and static data have been loaded, including static images and libraries. How can I determine when all requests and static data have finished loading? I have attempted the ...

"Error message: PHP throwing an undefined index error when using

I am struggling with a specific issue regarding sending POST data to a PHP file for database insertion. Despite looking at various solutions, I keep encountering a PHP notice stating undefined index arg1 and arg2. Below is the ajax code snippet: function ...

I attempted to activate the hover effect on a DOM element using JavaScript, but was unsuccessful. It appears that achieving this is not possible. However, I am curious as to how Chrome is able to

I attempted to activate the hover state of a DOM element using JavaScript, but had no success. It appears that this task is not achievable in the way I initially approached it. I have heard that creating a class with a hover function and then adding or ...

Is there a way to make a button on a single div only affect that specific div

I have a PHP query that echoes a div for each row in the table. I want the div to slide up and then, when the user clicks the "read more" button, the div slides down. However, since it is echoed in a loop, all the divs have the same IDs and classes. I wo ...

Enhance the functionality of bindings in Rails 4 by implementing turbolinks

Although there are similar questions about this issue, mine seems to be caused by having the javascript tag in the head rather than the body. Moving my js outside of the page change block is not an option for me. I stick to Rails convention by organizing ...

AngularJS: ng-show causing flickering issue upon page refresh

Recently, I encountered an issue with my code snippet: <body> <ng-view></ng-view> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script> <script src="http://ajax.googleapis.com/ajax/ ...

AngularJS mdDialog not supporting Tinymce functionality

I'm attempting to integrate the TinyMCE editor into an AngularJS mdDialog. Working Plunker: http://embed.plnkr.co/s3NsemdcDAtG7AoQRvLh/ Plunker with issues: http://embed.plnkr.co/fL8kGLl3b4TNdxW1AtKG/ All features are working fine except for the d ...

The list marquee in HTML, JS, and CSS is not being properly rendered on

I recently made changes to a code that showcases a marquee scrolling a basic HTML list. Check it out here: I am facing 3 issues that I am struggling to resolve: JS: I want the marquee to continuously show text re-entering from the right just after it ...

What is the best way to deploy a Vue Webpack application using Sails.js?

I am currently managing a Sails.js server alongside a Vue Webpack application, running as separate entities. Here's how my folder structure is laid out: /application-root/server/ /application-root/client/ Within the /server/ directory lies my Sails ...

Tips on preventing users from navigating backwards in a React Redux application

Seeking guidance on how to restrict user access after successful login in react redux. Can anyone assist me? I want to prevent users from navigating back to certain routes once they are logged in I am currently working on securing the routes to block unau ...

What could be causing the issues with SSL certificates when using Node.js/Express-TypeScript?

I'm currently in the process of transitioning a project's backend from JavaScript (Node.js/Express) to TypeScript. However, I've encountered an unusual issue where FS's readFileSync is unable to access the key.pem or cert.pem files in t ...