Issue with switch statements in PHP/JavaScript causing unexpected 'undefined' behavior

Exploring a switch statement:

var currency = "";

switch (row.currency) {
case 1 :
    currency = "£";
    break;
case 2 :
    currency = " $";
    break;
case 3 :
    currency = "€";
    break;

default:
    currency = "£";
    break;
}

I then attempt to access the variable currency here:

<td>' + currency + '<input class="editinput number" type="text" value="' + row.adhoc_setup_rem_cost + '" name="changes[' + row.id + '][adhoc_setup_rem_cost]" /></td>

However, upon viewing it, instead of seeing a currency symbol before the input box, I only see the word 'undefined'...

Answer №1

There seems to be some confusion regarding the row.currency variable in this context. However, upon testing it, I found that the code provided worked perfectly for me.

$(document).ready(function() {
 var currency = "";
 var row={currency:1};
 switch (row.currency) {
 case 1 :
         currency = "&pound;";
         break;
 case 2 :
         currency = " &#36;";
         break;
 case 3 :
         currency = "&euro;";
         break;

 default:
         currency = "&pound;";
          break;
 }

 $('<td>'+currency+'<input type="text"> </td>').insertAfter("p");
});

It is possible that the issue lies with your row.currency variable. Please double-check it or provide your code for further assistance.

Answer №2

Responding to the query about rps, and also addressing the OP's question, I would suggest steering clear of utilizing a switch statement and opting for an array instead. Given that row.currency will consistently hold values of 1, 2, or 3, you can easily map these to corresponding currency symbols within an array assigned to currency:

var currency = ['&pound;','&pound;','&#36;','&euro;'];//default value is 0
//string concatenation:
'<td>' + currency[+(row.currency) || 0] + '<inp...';

The logic here relies on the assumption that coercing row.currency into a number will always result in a value less than or equal to 3. If it exceeds this range, you risk appending undefined to the string. To mitigate this, consider the following adjustment:

'<td>' + currency[+(row.currency)] || currency[0] + '<inp...';

This ensures that the expression defaults to '&pound;'. However, overall, I find your code structure rather peculiar. It appears that you are constructing HTML within JavaScript, likely intended for client-side execution. In scenarios involving PHP (as implied by your title), generating HTML server-side is typically more advantageous compared to your current approach.

If hypothetically querying a database with PDO:

$currency = array(1 => '&pound;', 2 => '&#36;', 3 => '&euro;');
while($row = $stmt->fetch(PDO::FETCH_OBJ))
{
    $row->currency = isset($currency[$row->currency]) ? $row->currency : 1;//default 1
    echo '<tr><td>'. $currency[$row->currency].'</td>';
}

In light of this, without clearer details regarding the context and purpose of your posted code, determining the optimal strategy remains uncertain.

Answer №3

Eliminate the currency from your HTML structure and include this in your script after providing an identifier for the TD element:

var text = document.createTextNode(currency);  
document.getElementById('tdIdentifier').appendChild(text);

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

Displaying Dynamic Content in React Table Rows Based on Conditions

I'm populating a table with multiple rows using props. If a returned prop is an empty string "" , I want to exclude that row from rendering. <Table.Body> <Table.Row> <Table.Cell>Producer</Table.Cell> ...

How can I retrieve text that is enclosed within 2 specific tags and then format the output according to my preference?

Is it possible to extract text between specific tags and format the output as desired? Are there any tools or scripts available for this task? For instance: [b]1.[/b] [artist]Norman Bass[/artist] – How U Like Bass? (Warp Brothers Club Mix) [i](3:26 ...

Exploring JavaScript's usage of the var keyword within loops versus outside loops

Recently, my coworker and I engaged in a discussion about the best and worst practices when it comes to using the var keyword within loops. Here is my approach: for (var i = 0; i < anArray.length; i++) { for (var j = 0; j < anotherArray.length; ...

Unable to view through transparent merged geometry in three.js

Could someone assist me in understanding why, when merging the geometries of these boxes, I am encountering visibility issues from certain angles? Blue boxes represent normal individual boxes, while Orange boxes are the result of merged geometries. I am u ...

Dealing with an XMLHttpRequest using app.post in node.js with express (JavaScript)

In my current project, I am working on implementing a filter functionality using checkboxes. The concept involves creating HTML for the checkbox that triggers a script to send DOM data to the server. Here is an example of the HTML code: <div class=&quo ...

What is the best way to generate an array of objects by extracting specific properties from another array object?

Here is the information provided: const cocktail = [ { "idDrink":"13070", "strDrink":"Fahrenheit 5000", "strGlass":"Shot glass", "strInstructions":&qu ...

Creating visual content on a website

I'm currently working on a project where I need to showcase the results of a numerical model I am operating. My goal is to gather user input in the form of latitude/longitude coordinates, utilize php (or a similar tool) to trigger a python script that ...

Is there a way to transform a callback into promises using async/await, and convert a prototype function into a standard

I need help converting a code callback function to promises. When attempting to convert the prototype to a normal function, I encounter an error that I can't fix on my own. I am eager to utilize the ES7 async-await feature to avoid callbacks. functio ...

Tips for displaying a hyperlink in an Angular 6 component template

In my Angular 6 application, I am facing an issue with a component that is used to display messages on the page. Some of the messages include hyperlinks in HTML markup, but they are not being rendered properly when displayed (they appear as plain text with ...

Organizing AngularJS ng-repeat into sets of n items

I am facing a challenge with a data set structured like this: $scope.items = [ { model:"A", price: 100, quantity: 30}, { model:"B", price: 90, quantity: 20 }, { model:"C", price: 80, quantity: 200 }, { model:"D", price: 70, quantity: 20 ...

Events bound to JSX elements created in an array map are not being triggered by React

My current task involves working on a compact react + typescript (1.6) application designed for editing slideshows. The functionality of the app is straightforward. A sidebar on the left displays all existing slides, and upon clicking, a canvas appears on ...

Right-align each item when selecting none

Is there a way to change the style of just one of the elements select or option, without affecting the style of both? I attempted to align the select element to the right, while leaving the option elements aligned to the left. However, this did not work a ...

Arranging a collection of objects (Displaying information in a random sequence)

Here is a summary of the data returned in a shortened version: var array = [{ "response": { "itineraries":[ { "price": { "totalPricePerPassenger":"104" ...

Using forEach Loop with Promise.all in Node.js

I am seeking a solution for a task where I need to read a directory, copy its contents, and create a new file within that same directory. function createFiles(countryCode) { fs.readdir('./app/data', (err, directories) => { if (err) { ...

Erase the white backdrop from the dragImage

Is there a way to remove the white outline that appears when dragging a draggable element from a dark background? I want to make it completely transparent. Here is a visual representation: https://i.sstatic.net/Eywf9.png Here is the code snippet: docume ...

Refresh page upon clicking the same state link in AngularJS using ui.router

Just received an interesting request from our QA team that seems a bit out there. Let's dive in: imagine you are already on the 'about' state/page within an angular-based app, and when you click on the 'about' state URL again from ...

I keep getting double results from the Multiple Checkbox Filter

Currently, I am facing an issue with a checkbox filter on a product page that I'm developing. The filter is functioning correctly, but I encounter duplicate results when an item matches multiple criteria. For instance, if I select both 'Size 1&ap ...

Sending request results to the client's browser in Node.js - A step-by-step guide

I am struggling with figuring out how to send the results of a 'request' to the client browser. This function is executed on my Node.js server. var request = require("request"); function RedirectReceiver(url, currentState, callback){ ; Send ...

Unable to Update the Status Code

When it comes to setting the status code to 9999, I am utilizing the basic Response.StatusCode. In this case, the page is accessed via an AJAX call and the status code is checked at readyState = 4. On detecting 9999 as the status code, an alert pops up wit ...

Tips for managing click events in my class

I need assistance with dynamically adding and removing a class from a clicked element in AngularJS. Here is an example of my code: <li ng-repeat='test in tests' > <a href='' ng-click='pickTest($index, $event)'&g ...