Strings within strings within strings - a triple layer of quotes

Here is a snippet of the code that I'm working with:

<select class="form-select" id="topicId" name="topicId" onchange="javascript:
                var data = $(':input[name]', '#dynamic-form').serialize();
                $.ajax(
                  'ajax.php/form/help-topic/' + this.value,
                  {
                    data: data,
                    dataType: 'json',
                    success: function(json) {                            
                        var eng1 = document.querySelectorAll('input[type="text"]');
                        eng1[eng1.length-1].style.display = 'none';
                    }
                  });">

The issue arises with input[type="text"] - the quotation marks surrounding text are causing complications, especially since the entire code block is already enclosed in quotes. How can I resolve this problem effectively? Do you have any suggestions?

Answer №1

To simplify the process, you can move the code from the onchange attribute to a function and then call that function from the attribute.

function triggerAjax() {
  var data = $(':input[name]', '#dynamic-form').serialize();
  $.ajax(
    'ajax.php/form/help-topic/' + this.value, {
      data: data,
      dataType: 'json',
      success: function(json) {
        var eng1 = document.querySelectorAll('input[type="text"]');
        eng1[eng1.length - 1].style.display = 'none';
      }
    });
}
<select class="form-select" id="topicId" name="topicId" onchange="triggerAjax()">

Alternatively, you can attach the event listener in JavaScript without using onchange.

$("#topicId").change(function() {
  var data = $(':input[name]', '#dynamic-form').serialize();
  $.ajax(
    'ajax.php/form/help-topic/' + this.value, {
      data: data,
      dataType: 'json',
      success: function(json) {
        var eng1 = document.querySelectorAll('input[type="text"]');
        eng1[eng1.length - 1].style.display = 'none';
      }
    });
});
<select class="form-select" id="topicId" name="topicId">

If you absolutely need to include all the code in the onchange attribute, you can use single quotes instead of double quotes. Remember to escape them because single quotes are already used around the selector.

<select class="form-select" id="topicId" name="topicId" onchange="javascript:
                var data = $(':input[name]', '#dynamic-form').serialize();
                $.ajax(
                  'ajax.php/form/help-topic/' + this.value,
                  {
                    data: data,
                    dataType: 'json',
                    success: function(json) {                            
                        var eng1 = document.querySelectorAll('input[type=\'text\']');
                        eng1[eng1.length-1].style.display = 'none';
                    }
                  });">

Lastly, you can simply use $('input:text:last').hide().

Answer №2

I'm confused as to why not simply write everything inside the <script> tag? Regardless, you have the option to switch all single quotation marks to backticks and then replace the global double quotation marks within the onchange="..." with single quotation marks.

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

The jQuery show/hide functionality is malfunctioning

In my PHP code, I have the following loop: foreach ($sid as $key => $value) { $sql = " a sql query "; $vehicle->rowQuery($sql); $numRows = $vehicle->rows; while ( $data = $vehicle->result->fetch_assoc()) { $ ...

Creating a delayed queue using RxJS Observables can provide a powerful and

Imagine we have a line of true or false statements (we're not using a complicated data structure because we only want to store the order). Statements can be added to the line at any time and pace. An observer will remove items from this line and make ...

Unveil the content of a string by applying Base64 decoding in AngularJS

After encrypting a token sent from JAVA code to Angular using Base64 encryption, the next step is decryption: String token = "1345BCHCNB"; Cipher ecipher = Cipher.getInstance("AES"); String mykey = "1234567891234567"; SecretKey key = new SecretKey ...

Select2.js Dropdown List with Case Sensitivity

Currently making use of select2.js version 4.0.3 Situation: Imagine the dropdown list contains the following options: JavaScript javascript Javascript javaScript So, when a user types in java, all options are displayed (case is n ...

The findById function is encountering errors only on invalid id inputs: Unable to cast value to ObjectId

I have implemented a basic GET method to retrieve a 'genre' from a MongoDB database based on an id, using Mongoose. It functions correctly when a valid id is provided, but crashes the application when an invalid id is used. Here is the code snip ...

The presence of a default value within an Angular ControlValueAccessor triggers the dirty state due to

My task is to create dynamic Input components for a template driven form using a directive. The default value of the Input component should be set by the component itself. However, I encountered an issue where setting a default value automatically marks t ...

Using javascript, how can you fill in the missing dates within an array of objects?

I need to populate this object with dates starting from today up to the next 7 days. Here is my current object: let obj = { "sessions": [{ "id": 0, "available_capacity": 3, "date": "15-05- ...

Is it possible to clear a div using jQuery and then restore its contents?

In my setup, I have a video player within a div where clicking the play button (.video-play-container) fades in the video, and clicking the close button (.close-video) fades it out. The issue arose when the faded-out video continued playing in the backgr ...

Tips for adjusting the up and down controls and spins of a date input after modifying its height

After adjusting the height of my inputs (date type) to 40px, I noticed that the up and down controls are no longer aligned with the text inside the field. I am looking for a solution to either adjust the height of the spins or remove them if necessary in ...

What is the process for separating static methods into their own file and properly exporting them using ES6?

After exploring how to split up class files when instance and static methods become too large, a question was raised on Stack Overflow. The focus shifted to finding solutions for static factory functions as well. The original inquiry provided a workaround ...

Implement a transition effect for when elements change size using the `.resizable().css` method

I attempted to incorporate a deceleration effect when resizing an element back to its original size using the resizable method. The slowdown effect should only trigger during the click event (when the "Click-me" button is pressed), not while manipulating ...

The functionality of save() is not compatible with mongoose.Schema

const Information = require('./Models/Information'); ... let sampleData = new Information( dataSample ); sampleData.save( function ( error ){ console.log('testing); if ( error ) { console.log('Error occurred while saving Informa ...

Issue with Ionic 4 button not triggering event when created using Jquery

Utilizing Ionic 4 in my current project, I have integrated it with Jquery. On the HTML page, a button is created using the following code: <ion-button (click)="event1()">EVENT1 </ion-button> In the .ts file for the page, a function is impleme ...

Troubles arising while using ng serve in Angular 2

I'm currently facing an issue during the installation process of an existing Angular application. When trying to run the application using the ng serve command, I encounter the following error message: The "@angular/compiler-cli" package was not prope ...

How can I access the marker's on-screen location in react-native-maps?

Looking to create a unique custom tooltip with a semi-transparent background that can overlay a map. The process involves drawing the MapView first, then upon pressing a marker on top of the MapView, an overlay with a background color of "#00000033" is dra ...

Is it possible to append an "index" to a database field using Express, Loopback, or NodeJS?

Currently, we are utilizing the Express/Loopback Framework for our backend. I am currently working on ensuring that indexes on certain fields in models are properly created in MongoDB. Is there a way to utilize meta-tags within the models so that DataJuggl ...

display and conceal elements according to the slider's current value

Currently, I am working on creating a slider that can show and hide elements as the slider bar moves (ui.value). Firstly, I used jQuery to create 30 checkboxes dynamically: var start = 1; $(new Array(30)).each(function () { $('#showChck') ...

JavaScript: CryptoJS does not have the SHA1 method implemented

This seems like a simple issue to resolve.... Although my CryptoJS object is present, it appears to be lacking a SHA1 method. What steps should I take to rectify this? Despite various examples available, my specific case remains unresolved... On a posit ...

Ensure to update the canvas prior to the function finishing

Is there a way to update the canvas element while inside a JavaScript function without waiting for the function to return? It can be frustrating when you want to keep the function running but also need to update the canvas element in real time. ...

Block users from viewing the image displayed within a JavaScript canvas

On my server, I have a path to an image that is accessed by a JavaScript to load the image onto a canvas. The script then proceeds to hide certain parts of the image using black layers. The issue arises when a user can easily view my JavaScript code, extr ...