Javascript form validation with errors in alert block

I know there’s dozens of postings about Javascript form validation, but couldn’t find any to help me in my situation.

I have this form (re image below). i don’t have access to the HTML or CSS and can only add JS to the page.
The ‘original’ form only had the input fields: Email, Password & Confirm Password.
I’ve used JS to add the input fields: First Name & Last Name.
enter image description here

What im trying to do – When a person clicks the button it just validates the fields aren’t null and passwords match & if the fields have errors then it will show the red alert block (visible in my image above) & have a list item added for each field missing.
for example – if first name is missing it will add <li>First Name is a required field</li> to the block. If both first name & last name are missing then it will add <li>First Name is a required field</li><li>Last Name is a required field</li> etc.

If the validation all passes – then it writes the firstname & lastname to localstorage & performs a click action on the actual (hidden) submit button.
And obviously if validation fails – it shows alert block (with error list items) & doesn’t write to local storage or perform click action.

Here’s all the JS code i currently have.
Obviously the 2 new input fields are being added. Its writing to localstorage. Just struggling with the validation.

<script>
    $(document).ready(function () {
        function insertBefore(referenceNode, newNode) {
            referenceNode.parentNode.insertBefore(newNode, referenceNode);
        }

        //Change the heading text
        var title = document.getElementById("ContentContainer_MainContent_MainContent_RegisterLocalFormHeading").parentNode.querySelector(".xrm-attribute-value");
        title.innerText = "Register for a CEDA account";

        //Add the firstname & lastname fields above email field.
        var email = document.getElementById("ContentContainer_MainContent_MainContent_ShowEmail");
        var lastname = document.createElement('div');
        lastname.id = "LastName";
        lastname.classList.add("form-group");
        lastname.innerHTML = "<label class='col-sm-4 control-label required' for='LastNameTextBox'><span id='ContentContainer_MainContent_MainContent_LastNameLabel'><span class='xrm-editable-text xrm-attribute'><span class='xrm-attribute-value'>Last Name</span></span></span></label><div class='col-sm-8'><input name='ctl00$ctl00$ContentContainer$MainContent$MainContent$LastNameTextBox' type='text' autocomplete='off' id='LastNameTextBox' class='form-control' aria-required='true'></div></div>";
        insertBefore(email, lastname)
        var firstname = document.createElement('div');
        firstname.id = "FirstName";
        firstname.classList.add("form-group");
        firstname.innerHTML = "<label class='col-sm-4 control-label required' for='FirstNameTextBox'><span id='ContentContainer_MainContent_MainContent_FirstNameLabel'><span class='xrm-editable-text xrm-attribute'><span class='xrm-attribute-value'>First Name</span></span></span></label><div class='col-sm-8'><input name='ctl00$ctl00$ContentContainer$MainContent$MainContent$FirstNameTextBox' type='text' autocomplete='off' id='FirstNameTextBox' class='form-control' aria-required='true'></div></div>";
        insertBefore(lastname, firstname);

        //Add our fake Register button & hide the actual button
        var regButton = document.createElement('input');
        regButton.id = "customSubmitButton";
        regButton.classList.add("btn", "btn-success");
        regButton.setAttribute("name", "ctl00$ctl00$ContentContainer$MainContent$MainContent$customSubmitButton");
        regButton.setAttribute("value", "Register");
        insertBefore(document.getElementById("SubmitButton"), regButton);
        var submitButton = document.getElementById("SubmitButton");
        submitButton.style.visibility = "hidden";

        //Create our AlertError Box
        var errorBox = document.createElement('div');
        errorBox.id = "validationSummary";
        errorBox.classList.add("listStyleTypeNone", "alert", "alert-block", "alert-danger");
        errorBox.innerHTML = "<ul role='presentation'></ul>";
        var heading = document.getElementsByClassName("login-heading-section")[0];
        heading.parentNode.insertBefore(errorBox, heading.nextSibling);
        errorBox.style.display = "none";

        regButton.onclick = saveData;
        function saveData() {
            validateForm();
            errorBox.style.display = "block";


            localStorage.setItem("CEDAFName", document.getElementById("FirstNameTextBox").value);
            localStorage.setItem("CEDALName", document.getElementById("LastNameTextBox").value);
            //$("#SubmitButton").click();
        }

        function validateForm() {
            var errfirstname, errlastname, errEmail, errPass1, errPass2;
            if ($("#FirstNameTextBox").valid() == false) {
                errfirstname = "<li>First Name is a required field</li>";
            }
            if ($("#LastNameTextBox").valid() == false) {
                errlastname = "<li>Last Name is a required field</li>"
            }

        }

    });
</script>

AG-Grid: How to exclude selected rows from setQuickFilter?

My AG-Grid table utilizes setQuickFilter to filter rows by user input search criteria. The grid also has rowSelection enabled for other actions. My goal is to exclude selected rows from the search filter so that they always render in the grid regardless of what data the user is searching.

I attempted to conditionally call setQuickFilter only on unselected rows, but setQuickFilter is a method on the grid API and applies to all row data (e.g. gridApi.setQuickFilter(data))

I also attempted to use isExternalFilterPresent and doesExternalFilterPass to add my own filtering logic, but these appear to only run on the initial grid render rather than dynamically updating when selected rows and/or search filters update.

Is this type of filtering possible with current grid capabilities?

How to modify array of object arrays into a single array of objects?

I want to modify existing array which looks like this:

[
 [
  {
   prop1: 'FieldName', 
   prop2: 'FieldValue'
  }
 ],

 [
  {
   prop1: 'OtherFieldName',
   prop2: 'OtherFieldValue'
  }
 ],
]


Into having an array of objects with each object now having an unique id and setting prop1 value as a key for my new object.

[
 {
  id: 1, 
  FieldName: 'FieldValue'
 },
 {
  id: 2, 
  OtherFieldName: 'OtherFieldValue'
 }
]

I know that this probably asks more than the original question, but I think I’m missing something very simple here, just don’t know the most optimal way to go about it.

force while loop to wait for settimeout

$w.onReady(function () {
    let n = 0;

    do {
        setTimeout(() => $w('#z').changeState('State3'), 2000);
        setTimeout(() => $w('#z').changeState('State4'), 4000);
        n++

    } while (n > 3);
});

the changestate code lines only execute once because while doesn’t wait for timeout

I read answers but I couldn’t write it properly, im using wix

How can I insert variables in a markdown text from a NEXT or REACT frontend code?

I am very new with programming (legal professional) and builing a legaltech app. Essentially, I need to be able to have a markdown file where a few variables are changeable from the frontend code which is in NEXT JS.

The markdown file will then be used for a backend code which I have figured out somehow. I want to be in a position where my Frontend variables are dynamically interacting with the markdown file.

I think turndown is a library that can potentially enable this. However, as a beginner, I don’t know how to go about it as there isn’t much content on it. I also explored CodeMirror but I am not sure how that would work with this.

Would really appreciate if someone can help with this or just refer to a project which I can explore to solve this. Been stuck for a few weeks with this.

Why is my javascript file not recognizing servlet like jsp does?

I have a servlet named like @WebServlet(“/UserServlet”), and when I use action=”UserServlet” on JSP, it recognizes it, but the JavaScript file does not.
File Path Info:
Servlet is located at src/main/java/com.name.controller/UserServlet.
JSPs located at webapp/view/
JavaScript file lcoated at webapp/js/

When I do this:

    fetch('/UserServlet', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: registrationDataJSON
    })
        .then(response => response.json())
        .then(data => {
            // handle success or error response
            if (data.status === 'success') {
                // redirect to home page or display success message
            } else {
                // display error message
                alert(data.message);
            }
        })
        .catch(error => {
            // handle network or server error
            console.error(error);
        });
    return true;
};

This redirects to localhost:8080/UserServlet instead of localhost:8080/ProjectName/UserServlet.

But when I mention full path to servlet like this:
fetch('http://localhost:8080/projectname/UserServlet', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: registrationDataJSON }

Then it works, Is there no way I can make it work simply using the Servlet Name and not full path?

how to combine all data in separated session storage?

Is it possible to combine all session storage into one?

I have these three arrays which I pushing into storage because I will access them later.

The reason why I’m doing this is that the array I need is on a separated page. So I can’t combine the array before pushing it into storage.

Here’s what i have tried.

function FnOne() {
    let arrayInFnOne = [
      {
        'id': 1,
        'Choices': 'Cheeta'
      },
       {
        'id': 2,
        'Choices': 'Eagle'
       },
       {
        'id': 3,
        'Choices': 'Elephant'
       },
       {
        'id': 4,
        'Choices': 'Duck'
       },
       {
        'id': 5,
        'Choices': 'Deer'
       }
    ]
   let FNDataOne = sessionStorage.setItem('FNoneData', JSON.stringify(arrayInFnOne));
  }

function FnTwo(){
  let arrayInFnTwo = [
        {
          'id': 6,
          'Choices': 'Eggplant'
        },
         {
          'id': 7,
          'Choices': 'Tomato'
         },
         {
          'id': 8,
          'Choices': 'Potato'
         },
         {
          'id': 9,
          'Choices': 'String beans'
         },
         {
          'id': 10,
          'Choices': 'Squash'
         }
      ]
     let FNDataTwo = sessionStorage.setItem('FNtwoData', JSON.stringify(arrayInFnTwo));
}

function FnThree(){
let arrayInFnThree = [
        {
          'id': 11,
          'Choices': 'Paper'
        },
         {
          'id': 12,
          'Choices': 'Pencil'
         },
         {
          'id': 13,
          'Choices': 'Monitor'
         },
         {
          'id': 14,
          'Choices': 'Pentel Pen'
         },
         {
          'id': 15,
          'Choices': 'Wire'
         }
      ]
     let FNDataThree = sessionStorage.setItem('FNthreeData', JSON.stringify(arrayInFnThree));
}

document.querySelector('button').addEventListener('click', () => {
    let finalData = sessionStorage.setItem('FinalDataAns', concat(FNDataOne,FNDataTwo,FNDataThree))
  console.log(finalData);
})
<button>
Save
</button>

when selecting any radiobutton it does not show me its value as checkboxes do

I have a problem that is starting to be annoying, I have researched in forums, I even asked chatgpt and I have not managed to get it to work. I am making a section of the menu of a restaurant and in the section of salads for each one I need to have 5 radio buttons each one with a sauce without price since that will be the one that the customer can choose for free. I already made the section with checkbox to choose others for an additional cost can be one or more but in these with radiobuttons is to choose only one. The problem is that when I try to capture the value and show me the name of the sauce it does not show me anything, it leaves only the empty space. I have tried many ways but I cannot solve the situation. Do you have any idea of something that could work? Thanks

Part of Code Javascript

function agregarProducto(nombre, precio, form, variedades = []) {
  let precioCheckboxes = 0; // Precio de los checkboxes, inicializado en cero
  let precioRadiobuttons = 0; // Precio de los radiobuttons, inicializado en cero
  let nombreCheckbox = "";
  let nombreRadiobutton = "";
  let hayOpcionesSeleccionadas = false; // Variable para verificar si hay opciones seleccionadas
  
  // Si hay checkboxes, obtener los valores seleccionados y sumar sus precios
  if (form) {
    var checkboxes = form.querySelectorAll('input[type="checkbox"]:checked');
    for (var i = 0; i < checkboxes.length; i++) {
      let checkboxPrecio = parseFloat(checkboxes[i].getAttribute('data-precio'));
      let checkboxNombre = checkboxes[i].getAttribute('name');
      if (isNaN(checkboxPrecio)) { // Si no hay precio en el checkbox, agregar el nombre en lugar del precio
        variedades.push(checkboxNombre);
      } else { // Si hay precio en el checkbox, sumar al precio de los checkboxes
        precioCheckboxes += checkboxPrecio;
        variedades.push(`${checkboxNombre} ($${checkboxPrecio.toFixed(2)})`);
      }
      nombreCheckbox = checkboxNombre; // Actualizar el nombre del checkbox seleccionado
      hayOpcionesSeleccionadas = true; // Marcar que hay opciones seleccionadas
    }
  }
  
// THIS PART HAS ERROR NOT SHOW THE VALUE OF RADIOBUTTON
if (form) {
  var opcionSeleccionada = form.querySelector('input[type="radio"]:checked');
  var opciones = opcionSeleccionada ? opcionSeleccionada.value : "";

  if (opcionSeleccionada) { // Solo actualizar el nombreRadiobutton si hay opciones seleccionadas
    let opcionPrecio = parseFloat(opcionSeleccionada.getAttribute('data-precio'));
    nombreRadiobutton = opcionSeleccionada.getAttribute('value');



    if (isNaN(opcionPrecio)) { // Si no hay precio en la opción, agregar el nombre en lugar del precio
      variedades.push(nombreRadiobutton);
    } else { // Si hay precio en la opción, sumar al precio de las opciones
      precioRadiobuttons += opcionPrecio;
      variedades.push(`${nombreRadiobutton} ($${opcionPrecio.toFixed(2)})`);
    }
    hayOpcionesSeleccionadas = true; // Marcar que hay opciones seleccionadas
 

  }
}

Here i select the plate and add the car
everything is correct but in the brackets it doesn’t show me the name of the sauce you chose

I have tried using different types of logic, I checked variables, I thought it was an error in the javascript file but not because everything else works correctly and the console does not show any errors.

How to limit or set a max number of allowed checkbox selections? – Shopify website

Link to website: https://island-paradise-tours.myshopify.com/products/full-day-excursion-6-hours (password = paradiseTours)

I am working for the first time in Shopify and in hopes to find out how to limit the total number of checkboxes a user can select when they are going through the steps of selecting “What activities would you like to add?”

You will see this on the page after you select a date/time for the service. I need it to cap at 4 checkboxes max to just throw an alert. I can spice the design up later, but just need to catch an error.

Like I said, I’m using Shopify and I am using a plugin or app called Propel Appointment Booking. It allows you to add custom questions (i.e. Checkbox), but I can’t set a max limit.

Overall, the goal is to make sure the user doesn’t select more than 4 of the 11 checkboxes. And at the moment, I have no way of adding a specific ID or Class to the input field to call it. Little lost.

Code I am using:

window.onload = function () {
    const input = document.querySelector('input[type=checkbox]');
    function check() {
        if (input.checked) {
            alert("checked");
        } else {
            alert("You didn't check it.");
        }
    }
    input.onchange = check;
    check();
}

enter image description here

why http request with nodejs gives no response?

I’m creating a simple MERN stack project – the user makes notes with a note model that includes an ObjectId user ref while testing an endpoint it gives me a request sending with no response I need to know why.
here is my code below.

//Note model
  const mongoose = require('mongoose');
  const AutoIncrement = require('mongoose-sequence')(mongoose);

//create employee schema

    const noteSchema = new mongoose.Schema(
      {
        user: {
          type: mongoose.Schema.Types.ObjectId,
          required: true,
          ref: 'User',
        },
        title: {
          type: String,
          required: [true, 'title note is required!'],
        },
        text: {
          type: String,
          required: [true, 'note description is required!'],
        },
        completed: {
          type: Boolean,
          default: false,
        },
      },
      {
        timestamps: true,
      }
    );
    
    noteSchema.plugin(AutoIncrement, {
      inc_field: 'ticket',
      id: 'ticketNums',
      start_seq: 500,
    });
    
    module.exports = mongoose.model('Note', noteSchema);

createNote controller code:

please note that req.id was taken from jwt access token.

const createNote = asyncHandler(async (req, res) => {
  const { title, text } = req.body;
  if (!title || !text)
    return res.status(400).json({
      message: 'title and text are required for creating a new note.!',
    });

  const note = await Note.create({
    user: req.id,
    title,
    text,
  });
  return res.status(201);
});

I’ve tried so many things. Why is my websocket still closed?

I’ve been trying to figure this out for two entire months. I’ve had this code over here (SendCommand) in C# backend

        {
            var id = Guid.NewGuid().ToString();
            var cmd = new RenderRequest()
            {
                command = command,
                args = arguments,
                id = id,
            };
            var res = new TaskCompletionSource<RenderResponse<Stream>>();
            var responseMutex = new Mutex();
            
            // Setup listener
            mux.WaitOne();
            resultListeners[id] = stream =>
            {
                Console.WriteLine("[info] SendCommand() over");
                lock (responseMutex)
                {
                    res.SetResult(stream);
                }

                return 0; 
            };
            mux.ReleaseMutex();
            // Send message
            var bits = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(cmd));
            while (ws is not {State: WebSocketState.Open})
            {
                Writer.Info(LogGroup.GeneralRender, "Ws not available, retry in a second");
#if DEBUG 
                await Task.Delay(TimeSpan.FromSeconds(60), cancellationToken  ?? CancellationToken.None);
#else
                await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken  ?? CancellationToken.None);
#endif
                if (cancellationToken is {IsCancellationRequested: true})
                    throw new TaskCanceledException();
            }
            await ws.SendAsync(bits, WebSocketMessageType.Text, true, cancellationToken ?? CancellationToken.None);

            await using var register = cancellationToken?.Register(() =>
            {
                mux.WaitOne();
                resultListeners.Remove(id);
                mux.ReleaseMutex();
                // TODO: Would be nice if we could send a message to WS telling it to cancel the task
                // TrySetCanceled instead of SetCanceled due to WEB-35
                lock (responseMutex)
                {
                    if (res.TrySetCanceled(cancellationToken.Value) && command != "Cancel")
                    {
                        SendCommand("Cancel", new List<dynamic>()
                        {
                            id,
                        }, CancellationToken.None);
                    }
                }
            });
            var resp = await res.Task;
            return resp;
        }

and Here for ConnectionManager

        {
            while (true)
            {
                try
                {
                    mux.WaitOne();
                    ws ??= new ClientWebSocket();
                    var wsCurrentState = ws.State;
                    mux.ReleaseMutex();
                    
                    if ((wsCurrentState is WebSocketState.Aborted) || (wsCurrentState is WebSocketState.Closed) || (wsCurrentState is WebSocketState.None) || (wsCurrentState is WebSocketState.CloseReceived) || (wsCurrentState is WebSocketState.CloseSent))
                    {
                        Console.WriteLine("[info] ws connection is in state {0}, so we are re-connecting", ws.State);
                        mux.WaitOne();
                        ws = new ClientWebSocket();
                        mux.ReleaseMutex();
                        await ws.ConnectAsync(wsUrl, CancellationToken.None);
                    }
                    await ListenForMessages();
                }
                catch (Exception e)
                {
                    Console.WriteLine("[info] ConnectionManager got error in ws connection {0}", e.Message);
                    await Task.Delay(TimeSpan.FromSeconds(5));
                }
            }
        }

Anyone know why the websocket is always in the state closed?

Tried removing the check, everything, tried so many things, everyone who has the fix is gatekeeping it from me. I would love this to god if I can ever get this to work. It’s crazy how stupid this is getting to be. I thought this would be easy but this has turned out to be the most annoying thing I’ve ever dealt with in my entire life. It’s getting so crazy. If anyone can help, I’d do anything at this point due to how stupid this is really getting on me. Hopefully one of you guys can find the problem here and tell me what I’m doing wrong, or how to open up the websocket. That’s all I need. Thanks!

Selenium Testing $ not defined while loading jQuery

public static void runTimeInfo(String messageType, String message) throws InterruptedException {
    js = (JavascriptExecutor) driver;

    // Check for jQuery on the page, add it if need be
    js.executeScript("if (!window.jQuery) {"
            + "var jquery = document.createElement('script'); jquery.type = 'text/javascript';"
            + "jquery.src = 'https://code.jquery.com/jquery-3.6.4.min.js';"
            + "document.getElementsByTagName('head')[0].appendChild(jquery);" 
            + "}");

    // Wait for jQuery to load
    js.executeScript("var waitForJQuery = setInterval(function() {"
            + "if (window.jQuery) {"
            + "clearInterval(waitForJQuery);"
            + "jQuery.noConflict();"
            + "}" 
            + "}, 100);");

    // Use jQuery to add jquery-growl to the page
    js.executeScript("jQuery.getScript('https://the-internet.herokuapp.com/js/vendor/jquery.growl.js')");

    // Use jQuery to add jquery-growl styles to the page
    js.executeScript("jQuery('head').append('<link rel="stylesheet" "
            + "href="https://the-internet.herokuapp.com/css/jquery.growl.css" " 
            + "type="text/css" />');");

    // jquery-growl w/ no frills
    js.executeScript("jQuery.growl({ title: 'GET', message: '/' });");

    if (messageType.equals("error")) {
        js.executeScript("jQuery.growl.error({ title: 'ERROR', message: '"+message+"' });");
    } else if (messageType.equals("info")) {
        js.executeScript("jQuery.growl.notice({ title: 'Notice', message: 'your notice message goes here' });");
    } else if (messageType.equals("warning")) {
        js.executeScript("jQuery.growl.warning({ title: 'Warning!', message: 'your warning message goes here' });");
    } else {
        System.out.println("no error message");
    }

    // jquery-growl w/ colorized output
    //js.executeScript("jQuery.growl.error({ title: 'ERROR', message: 'your error message goes here' });");
    //js.executeScript("jQuery.growl.notice({ title: 'Notice', message: 'your notice message goes here' });");
    //js.executeScript("jQuery.growl.warning({ title: 'Warning!', message: 'your warning message goes here' });");

    Thread.sleep(5000);
}

this code is giving me $ not defined error. can anyone help with the solution?? I am using firefox for the testing. please let me know if you needed any additional information as I am new to selenium I am not sure how to resolve it. I have tried changing jQuery versions, but it is still not working.

Missing ‘}’ or object member name in JSON-LD

I have already tried solutions that were mentioned here

I’ve already countless checked for trailing commas, white spaces, uneven curly bracket. But none of them worked. Can someone help what is wrong with my schema?

Check this link using the validator.schema website here

{
    "@context": "https://schema.org",
    "@type": "RealEstateListing",
    "name": "8 Bedroom Residential",
    "description": "Romantic and impressive Mediterranean estate situated on a one acre, street to street view lot in the hills of coveted North Tustin, Villa Fiorile is a custom gated estate in an unmatched setting with mature trees and lush gardens. Grand, intimate, and rich in character and style, this residence is accented by saturated colors, arched windows and doors, interior arched casings, and exposed wood-beamed ceilings. Upon entering the residence, one is welcomed by a dramatic entry hall that leads into the majestic living room anchored by a fireplace with European mahogany windows offering expansive views from Catalina to Palos Verdes and beyond.  French doors in the adjacent sun room lead out to serene grounds with a sparkling all-tile swimming pool. The spacious property offers a main house with five bedrooms, three of which are large enough to be primary suites, each adorned with luxurious spa-like Carrara marble baths. The two additional bedrooms have their own baths. Rich mahogany patio doors and windows surround the home and encourage indoor and outdoor living. Materials used throughout are rarely seen in today’s homes. From the expansive formal living and dining rooms, cozy family room with fireplace and sitting room, and charming kitchen, the authentic Mediterranean finishes showcase the home’s timeless style. The grounds feature an expansive lawn, patios with old world fountains, garden, majestic oak and palm trees, a two-story guest house and separate casita. Homes of this",
    "address": {
      "@type": "PostalAddress",
      "streetAddress": "1621 FOOTHILL BLVD",
      "addressLocality": "SANTA ANA",
      "addressRegion": "CA",
      "postalCode": "92705",
      "addressCountry": "US"
    },
    "geo": {
      "@type": "GeoCoordinates",
      "latitude": 33.760629,
      "longitude": -117.785239
    },
    "image": "https://api1.realtytrac.com/api/v1/properties/photo?u=AZbWrYHm2bcgjXps4ixc7OKvon-poleUd_Rd7GqF0TYPpYtz3JiXjv6_K0Q-Heoc5MAqCPP_s-MxdpH0EIUTFcLOyjCt60liESSDdXwvI7wlsOHWdCkN2XO2BEW8x0mfG5SskhXp9OiFDyghsxT5XM3S-n8o",
    "offers": {
      "@type": "Offer",
      "priceCurrency": "USD",
      "price": "$4999000",
      "URL": "https://www.realtytrac.com/p/foothill-blvd-santa-ana-ca-92705-52061555/",
      "availability": "http://schema.org/InStock"
    },
    "url": "https://www.realtytrac.com/p/foothill-blvd-santa-ana-ca-92705-52061555/"
  }

Tried validating it with validator.schema.org website and says Missing ‘}’ or object member name.

How would I select a size (say size 11) on stockX using puppeteer?

I am trying to make a bot, and I need to select a size. For now, i’m just going to select 11. How would I do this, since all of the buttons have the same class?

I have tried to select the data-testid, but i’m pretty new at puppeteer and node.js in general, so it’s been a little hard.

const pt = require('puppeteer')

const url = 'https://stockx.com/buy/air-jordan-1-retro-high-og-chicago-reimagined-lost-and-found'

async function initBrowser(){
    const browser = await pt.launch({headless:false, defaultViewport: null, slowMo:10});
    const page = await browser.newPage();
    await page.goto(url,{waitUntil: 'networkidle0'});
    return page;
}

async function selectSize(){
    const page = await initBrowser();
    await page.$eval("div[data-testid='size-11'" , form => form.click() );
}

async function checkout(){
    await selectSize();
    await page.setViewport({width: 1920, height: 1080})
    await page.screenshot({path: 'test.png'})
}

checkout();

What ends up happening is this:

Error: Error: failed to find element matching selector "div[data-testid="#size-11"]"
    at CDPElementHandle.$eval (*filepath*)
    at async selectSize (*filepath*)
    at async checkout (*filepath*)