City and street validation at checkout

I am a newcomer in Magento2 and face with a next task. I have to do custom validation for city and street inputs at Checkout page for both shipping and payment steps.
There are 2 issues I am misunderstanding totally.

  1. As I could investigate templates for city and street are inserted by Knockout. To get cities and streets list I have to insert php method in script tag. This php method provides to me URL for next Ajax request. Because of general Knockout template with ‘.html’ type I can’t insert php code there.
    So how can I call my js file from Knockout html template?
  2. City and street inputs must offer coincidences for first entered letters (as a result of Ajax request) in their lists below. How this lists can be realized?

I have read Magento devdocs and a lot of communities but couldn’t find intelligible explanation. Sorry for possible repeat.

app/design/frontend/Vendor/Theme/Magento_Checkout/web/template/shipping-address/form.html (inputs are inserted inside id="shipping-new-address-form")

<div class="amtheme-shipping-wrap">
    <form class="form form-shipping-address amtheme-form-address"
          id="co-shipping-form"
          data-bind="attr: {'data-hasrequired': $t('* Required Fields')}">
        <div class="step-title" data-bind="text: setAddressTitle" data-role="title"></div>
        <!-- ko foreach: getRegion('before-fields') -->
            <!-- ko template: getTemplate() --><!-- /ko -->
        <!--/ko-->
        <div id="shipping-new-address-form" class="fieldset address">
            <!-- ko foreach: getRegion('additional-fieldsets') -->
                <!-- ko template: getTemplate() --><!-- /ko -->
            <!--/ko-->
            <!-- ko if: (isCustomerLoggedIn) -->
            <div class="field choice" data-bind="visible: !isFormInline">
                <input type="checkbox" class="checkbox" id="shipping-save-in-address-book" data-bind="checked: saveInAddressBook" />
                <label class="label" for="shipping-save-in-address-book">
                    <span data-bind="i18n: 'Save in address book'"></span>
                </label>
            </div>
            <!-- /ko -->
            <div class="amtheme-address-toolbar" data-bind="visible: !isFormInline && !isFormPopUpVisible()">
                <button type="button"
                        class="action action-cancel"
                        click="hideNewAddress"
                        text="$t('Cancel')"
                        data-bind="attr: {title: $t('Cancel')}">
                </button>
                <button type="button"
                        class="action action-save"
                        click="saveNewAddress"
                        text="$t('Ship here')"
                        data-bind="attr: {title: $t('Ship here')}">
                </button>
            </div>
        </div>
    </form>
</div>

I was about to write inside form.html something like this:

<script>
    require([
        'jquery',
        'Magento_Theme/js/govaddress-validation'
    ], function($) {
        $(function () {
            $('input[name="city"]').keyup(function () {
                console.log('keyup event worked');
                govAddressValidation.getCityList('<?php echo $this->getUrl("opgovaddress"); ?>');
            });
        })
    })
</script>

My JS file is not matter as it is unreachable for now

app/design/frontend/Vendor/Theme/Magento_Theme/web/js/govaddress-validation.js

define([
    'jquery'
], function ($) {
    'use strict';
    return {
        url: '',
        getCityList: function (url) {
            var inputValue = $('input[name="city"]').val();
            this.inputValue = inputValue;
            this.url = url;
            this.ajaxCall();
            console.log('getCityList');
        },

        ...
    }
})

app/design/frontend/Vendor/Theme/Magento_Theme/requirejs-config.js

var config = {
    map: {
        '*': {
            backTop: 'Magento_Theme/js/components/back-to-top',
            amMenu: 'Magento_Theme/js/components/am-menu',
            amQty: 'Magento_Theme/js/components/am-qty',
            amSelect: 'Magento_Theme/js/components/am-select',
            amFileUpload: 'Magento_Theme/js/components/am-file-upload',
            amStickyHeader: 'Magento_Theme/js/components/am-sticky-header',
            govAddressValidation: 'Magento_Theme/js/govaddress-validation'
        }
    },

    config: {
        mixins: {
            'mage/validation': {
                'Magento_Theme/js/lib/mage/validation-mixin': false
            },
            'mage/menu': {
                'Magento_Theme/js/lib/mage/menu-mixin': true
            }
        }
    }
};

What does [ERROR_MODULE_NOT_FOUND] mean?

After running “nodemon server,” I got this error:


[nodemon] 2.0.15
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server index.js`
internal/process/esm_loader.js:74
    internalBinding('errors').triggerUncaughtException(
                              ^

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/Users/brandonkim/Desktop/restaurant-reviews/backend/server.js' imported from /Users/brandonkim/Desktop/restaurant-reviews/backend/index.js
    at finalizeResolution (internal/modules/esm/resolve.js:271:11)
    at moduleResolve (internal/modules/esm/resolve.js:694:10)
    at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:805:11)
    at Loader.resolve (internal/modules/esm/loader.js:88:40)
    at Loader.getModuleJob (internal/modules/esm/loader.js:241:28)
    at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:72:40)
    at link (internal/modules/esm/module_job.js:71:36) {
  code: 'ERR_MODULE_NOT_FOUND'
}
[nodemon] app crashed - waiting for file changes before starting...

What does this mean? How do I fix it? I am just simply trying to run the server for the backend of a website.

My package.json is:


{
  "name": "backend",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "bson": "^4.2.2",
    "cors": "^2.8.5",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "mongodb": "^3.6.4"
  }
}

Cannot get a value from API

I have an issue with an API call from polygon.io.
I am using their free API which gives me information on stock tickers.

I am using an API that provides me a response when called.
From the response, I need to get response > data > results > “c” value, in this case, 1014.97

So far the best I could do is:
console.log(response.data.results)

which gives:

  Array [
  Object {
    "T": "TSLA",
    "c": 1014.97,
    "h": 1090.5753,
    "l": 1000.21,
    "n": 1043576,
    "o": 1084.79,
    "t": 1638565200000,
    "v": 30773995,
    "vw": 1028.7486,
  },

Please tell me how I can get the “c” value?

Here is the full response data:

console.log(response)

This, in VS-Code>Terminal shows:

Object {
  "config": Object {
    "adapter": [Function xhrAdapter],
    "baseURL": "https://api.polygon.io/",
    "data": undefined,
    "headers": Object {
      "Accept": "application/json",
    },
    "maxBodyLength": -1,
    "maxContentLength": -1,
    "method": "get",
    "params": Object {
      "apiKey": "Gp5IgTvT4fPbfhINPpOk7iBIUDjOTRc9",
    },
    "timeout": 5000,
    "transformRequest": Array [
      [Function transformRequest],
    ],
    "transformResponse": Array [
      [Function transformResponse],
    ],
    "transitional": Object {
      "clarifyTimeoutError": false,
      "forcedJSONParsing": true,
      "silentJSONParsing": true,
    },
    "url": "v2/aggs/ticker/MSFT/prev",
    "validateStatus": [Function validateStatus],
    "xsrfCookieName": "XSRF-TOKEN",
    "xsrfHeaderName": "X-XSRF-TOKEN",
  },
  "data": Object {
    "adjusted": true,
    "count": 1,
    "queryCount": 1,
    "request_id": "6a2a6c28efc5fcf9e4b1f295f845bf91",
    "results": Array [
      Object {
         "T": "TSLA",
         "c": 1014.97,
         "h": 1090.5753,
         "l": 1000.21,
         "n": 1043576,
         "o": 1084.79,
         "t": 1638565200000,
         "v": 30773995,
        "vw": 1028.7486,
      },
    ],
    "resultsCount": 1,
    "status": "OK",
    "ticker": "MSFT",
  },
  "duration": 406,
  "headers": Object {
    "content-type": "application/json",
    "date": "Sat, 04 Dec 2021 21:37:55 GMT",
    "server": "nginx/1.19.2",
    "strict-transport-security": "max-age=15724800; includeSubDomains",
    "vary": "Accept-Encoding",
    "x-request-id": "6a2a6c28efc5fcf9e4b1f295f845bf91",
  },
  "ok": true,
  "originalError": null,
  "problem": null,
  "status": 200,
}

Uncaught ReferenceError: $ is not defined ruby-on-rails

I tried to read jquery but it did not work.
I want to hide the download and cancel button once users click the download button, and show back button.

This is error when I run.

Uncaught ReferenceError: $ is not defined

This is show.html.erb

 <button class="btn btn-primary" type="submit" id="download_button"><%= t(".download") %></button>
          <%= link_to t("cancel"), certs_path, class: "btn btn-default", id: "cancel_button" %>
          <%= link_to t("back"), certs_path, class: "btn btn-default", id: "back_button", style: "display:none;" %>

....

<!-- After downloading the certificate,
   prevent the button from being pressed to prevent certs re-creation. -->
<script>
    $("#download_button").on("click", () => {
        $("#download_button").hide()
        $("#cancel_button").hide();
        $("#back_button").show();
    });
</script>

This is config/webpack/environment/js


const { environment } = require('@rails/webpacker')

const webpack = require('webpack')
environment.plugins.prepend('Provide',
  new webpack.ProvidePlugin({
    $: 'admin-lte/plugins/jquery/jquery',
    jQuery: 'admin-lte/plugins/jquery/jquery',
  })
)

module.exports = environment

This is app/assets/javascipts/application.js

//= require jquery
//= require_tree .

I also tried rails s, and bundle update but it did not work.

bootstrap.js:488 Uncaught TypeError: Cannot read properties of undefined (reading ‘cycle’)

I’m Creating a dynamic carousel Asp.net MVC
it’s not displaying the elements, but when I added “active” to the carousel-item class manually using inspect, it works perfectly. also, I’m getting this error

bootstrap.js:488 Uncaught TypeError: Cannot read properties of undefined (reading ‘cycle’) at HTMLDivElement. (bootstrap.js:488) at Function.each (jquery-3.4.1.js:367) at jQuery.fn.init.each (jquery-3.4.1.js:202) at jQuery.fn.init.Plugin (bootstrap.js:479) at HTMLDivElement. (bootstrap.js:542) at Function.each (jquery-3.4.1.js:367) at jQuery.fn.init.each (jquery-3.4.1.js:202) at bootstrap.js:540 at dispatch (jquery-3.4.1.js:5237) at elemData.handle (jquery-3.4.1.js:5044)

var list = Model;
var items = list.Take(3);
var iterations = 0;

while (items.Count() > 0)
{
var active = iterations == 0 ? “active” : “”;

foreach (var item in items)
{

Date

Price

@item.Description

}

iterations++;
items = list.Skip(3 * iterations).Take(3);

}

Cannot read properties of null

I am trying to add the code on this page: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_filter_elements

but it give me an error on the js:

Uncaught TypeError: Cannot read properties of null (reading ‘getElementsByClassName’)
at main.js?ver=5.8.2:35

I am trying to add it on: https://nuovosito.lealternative.net/test-browser-4/

It seems works fine expect that it can’t find and active class to the current button.

Is it possible assign the checked state to the value of the current checkbox in razor form without onclick method?

I have an ASP.Net Core MVC Web Application project.
I want to send the checkbox’s checked state as the value to the model’s related parameter on form submit.
I have seen so many examples that using jquery to get/set the value of the checkbox via onchange methods.

What I wonder is that is it possible to assign the current checkbox’s checked state to the value in a similar way to the code below.(it doesn’t work)

<input type="checkbox" id="IsActive" name="DTO.IsActive" checked="@Model.IsActiveTournament" value="(this.checked)" 

One of the simplest working examples I found is the following but it returns false if the checkbox is checked by default and its state is not changed.

<input type="checkbox" id="IsActive" name="DTO.IsActive" checked="@Model.IsActive" onchange="if(this.checked) this.value='true'; else this.value='false';" >

I know that there are many ways to achieve what I want but I want the cleanest solution.

Thanks in advance!

Splitting a multiline string by regex ha unwanted elements in result array

I’m trying to split a multiline string using a regex.

const regexCommitSha = RegExp(/([0-9a-f]{7})s/m)
const result = commits.split(regexCommitSha)
console.log(result)

This is my multiline string (commits):

1234567 fix: simple bug fix
apps/backend/src/lib/file.ts
1234567 fix: second bug fix
apps/backend/src/lib/file.ts
apps/frontend/src/lib/file.ts
1234567 feat: new feature
apps/frontend/src/lib/file.ts
1234567 feat: second feature
apps/frontend/src/lib/file.ts

And this is my result:

[
  '',
  '1234567',
  'fix: simple bug fixnapps/backend/src/lib/file.tsn',
  '1234567',
  'fix: second bug fixn' +
    'apps/backend/src/lib/file.tsn' +
    'apps/frontend/src/lib/file.tsn',
  '1234567',
  'feat: new featurenapps/frontend/src/lib/file.tsn',
  '1234567',
  'feat: second featurenapps/frontend/src/lib/file.ts'
]

Why do I have the empty string as first element and why do I have '1234567'-elements in my result array? As this is my splitter, I thought this is not existing in the result.

I would expect

[
  'fix: simple bug fixnapps/backend/src/lib/file.tsn',
  'fix: second bug fixn' +
    'apps/backend/src/lib/file.tsn' +
    'apps/frontend/src/lib/file.tsn',
  'feat: new featurenapps/frontend/src/lib/file.tsn',
  'feat: second featurenapps/frontend/src/lib/file.ts'
]

What am I doing wrong?

I need help so i can display the users balance once they connect

    //---------------------------connect wallet------------------------------\

    window.userWalletAddress = null
    const loginButton = document.getElementById('connectWallet')
    const userWallet = document.getElementById('userWallet')

    function toggleButton() {
      if (!window.ethereum) {
        loginButton.innerText = 'MetaMask is not installed'
        return false
      }

      loginButton.addEventListener('click', loginWithMetaMask)
    }

    async function loginWithMetaMask() {
      const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' })
        .catch((e) => {
          console.error(e.message)
          return
        })
      if (!accounts) { return }

      window.userWalletAddress = accounts[0]
      userWallet.innerText = window.userWalletAddress
      loginButton.innerText = 'Sign out of MetaMask'

      loginButton.removeEventListener('click', loginWithMetaMask)
      setTimeout(() => {
        loginButton.addEventListener('click', signOutOfMetaMask)
      }, 200)
    }

    function signOutOfMetaMask() {
      window.userWalletAddress = null
      userWallet.innerText = ''
      loginButton.innerText = 'Sign in with MetaMask'

      loginButton.removeEventListener('click', signOutOfMetaMask)
      setTimeout(() => {
        loginButton.addEventListener('click', loginWithMetaMask)
      }, 200)
    }

    window.addEventListener('DOMContentLoaded', () => {
      toggleButton()
    });

    // ---------------------------------------------------------\



    const testnet = ' https://data-seed-prebsc-1-s1.binance.org:8545/';
    const walletAddress = document.getElementById('userWallet').innerText;

const web3 = new Web3(new Web3.providers.HttpProvider(testnet));
var balance = web3.eth.getBalance(walletAddress); //Will give value in.
balance = web3.toDecimal(balance);

ok so i’m trying to get the users current smart chain balance to show in the console for now but when i try to grab the data of the wallet address

(which shows in an element with an ID of userWallet after they connect)

but when i try to grab the elements inner text it shows as undefined in the terminal
but if i put an actual address without trying to grab but rather as a string it works correctly.

I honestly think i should get better at javascript before diving into this web3 stuff but i’m stubborn and want this to work lol.

also if anyone wants to help with a little project of mine let me know and ill see how i can contact you (i don’t know if its against the rules to post my telegram here yet)

how i can pass props in redux? and save it global

import axios from "axios";
import React, {useEffect, useState} from "react";

in loginUser i get sucessfuly the username ,and redirect …but befor redirect it

const url = `https://api.agify.io`


export const loginUser = (values, history, setFieldError, setSubmitting) => {
    const username = values.email.split("@")[0]
    return () => {
        axios.get(url,{
            params:{
                name:username
            }
        }).then((response) => {
            console.log("username", username)

//here i should save username for use it globall

            console.log("response", response)
            history.push("/user")
        }).catch(error => console.error(error))
        setSubmitting(false);
    }
}

i should use the user name that come from loginUser for showing it in my code on Userinfo,after getting that props save it globally,for using everywhere,
after that should work axios call

export const Userinfo = () => {
    const [state, setState] = useState({info: []});
    useEffect(() => {
        axios
            .get("https://api2.binance.com/api/v3/ticker/24hr")
            .then((response) => {
                setState({
                    info: response.data
                });
                console.log(response.data);
            });
    }, [])
    const {info} = state;
    return (
        <div>
            <h2>post!</h2>
            {info.map((user) => (
                <div key={user.data}>
                    <h6>{user.count}</h6>
                </div>
            ))}
        </div>
    );
}


this code i write in redux component

here is my code
https://codesandbox.io/s/agitated-cherry-rfrj6?file=/src/auth/actions/userActions.js

Ellipsize middle of string in Javascriptt

I am currently trying to create a function that will ellipsize the middle of a text string. The idea is for it to show the first five characters and the last five characters. The middle of the string will just show as

So for example if I have dkjkjfdljfldkjfssdfsf

It should show as

dkjkj…sdfsf

I so far have this function:

function ellipsizeIt(text, length) {
if (text.length > length) { return ${text.substring(0, length)}...${text.substring(0, length)}; }
return text;
}

But its just repeating the string first five characters when I do:

ellipsizeIt(text, 5);

It will show as

dkjkj…dkjkj

Any way to do it so that it doesnt just repeat the first five characters in the end of the string and show the actual last 5 characters?

Problems in understanding javascript nested for loops

I try to understand nested for loops in javascript but it’s very confusing.

I have this code and I can’t understand how it works:

let n = 5;
for (let i = 0; i < n; i++) {
    for (let j = 0; j < i; j++) {
    console.log(j);
}}

In console I have : 0
1
0
1
2
0
1
2
3

And I’m trying to figure out which loop represent each number.

Trouble canva to image C#

Have been going through a process of being able to add in an image what I paint on a canvas.

I am working on the asp.net form and I rely on JavaScript to be able to paint the movements of the cursor on the canva.

<table id="Table8" class="table table-striped table-bordered table-hover" style="width: 100%" runat="server">
    <tr>
        <td>
            <label>Espacio habilitado para firma del cliente.</label></td>
    </tr>
    <tr>
        <td>
            <canvas id="Canvas1" runat="server" style="border: outset;"></canvas>
            <br />
            <asp:button id="Button1" runat="server" text="Limpiar Firma" onclick="limpiar_Click" />
            Fecha de Firma:
            <asp:label id="Label1" runat="server"></asp:label>
            <script src="/Scripts/scriptEntrega.js" type="text/javascript"></script>
            <script>
                function verimage() {
                    const canva = document.querySelector("pizarra");
                    const dataURI = cav.toDataURL('image/jpg');
                    Image2.src = dataURI;
                }
            </script>
        </td>
        <td>
            <asp:image id="Image3" runat="server" />
        </td>
    </tr>
</table>

So far everything works perfect, I can do the perfect painting process, but now I need to store the image, for which I am trying to convert the canvas into an image and later the image to convert it into an array.

In the same form I have a button, which when pressed calls from the C # codebehind a JavaScript function, with which I try to pass the canvas to the image, but nothing appears to me and on the contrary it deletes everything I paint.

<td style="text-align: center">
    <asp:Button ID="ButtonSubmit" class="btn btn-primary" runat="server" Text="Guardar" OnClick="ButtonSubmit_Click" />
</td>

event

 protected void ButtonSubmit_Click(object sender, EventArgs e)
        {
            string script = "window.onload = function() { verimage(); };";
            ClientScript.RegisterStartupScript(this.GetType(), "verimage", script, true);
        }

I do not know why the above happens, but if you could enlighten me, I would appreciate it.