Selectize.js – how to know that an item selected came from “Add Item” instead of the preloaded options

I have this code.

$customer = $(".customer").selectize({
            valueField: 'builder',
            labelField: 'builder',
            searchField: 'builder',
            openOnFocus: true,
            createOnBlur: true,
            maxItems: 1,
            create: function (input) {
                newOption = true;
                return {
                    builder: input,
                    value: input,
                    text: input,
                };
            },
            render: {
                option: function (item) {
                    return (
                        "<div class='selectize-item'>" +item.builder+ "</div>"
                    );
                },
            },
            load: function (query, callback) {
                if (!query.length) {
                    return callback();
                }
                $.ajax({
                    url: "/api/xxx/xxx",
                    type: "GET",
                    dataType: "json",
                    data: {...},
                    error: function () {
                        callback();
                    },
                    success: function (res) {
                        callback(res);
                    },
                });
            },
        });

I’ve used selectize to a dropdown that allows users to add their own option. I believe this can be done through the create method.

My question here is how can I know that the user has added a new option instead of selecting the options that were pre-loaded. I am planning that if the user has added a new option I will make my variable newOption into true, while if the user has selected to the options that were pre-loaded, newOption will be false.

When I say “pre-loaded”, this is an option that has been loaded through Ajax. You can see it on my load method that the dropdown options are loaded through Ajax.

Any help is greatly appreciated!

Error receiving json data from XMLHttpRequest

I am trying to send the data in XMLHttpRequest through json, in the log I receive succesful and the data info correctly but in the php I cannot collect the data,this works with an exit() and the $data on the php file, if you take out $data it the responseText is empty, if you take out exit(), it transforms into some weird characters with ? and more nonsense, and if you use $_POST it shows array() and some weird characters again after the empty array. The js part is sent when you click on the chart.js and then it is accessed from report.php when clicking on an icon, I don’t know if when accessing like this the info from the js is not arriving, as I just get a blank page. This is the js and the php:

onComplete: function() {
                        console.log(myChart.toBase64Image());
                        var imgData = myChart.toBase64Image();
                        var imgRes = imgData.replace('data:image/png;base64,', '');
                        var xhttp=new XMLHttpRequest();
                        xhttp.onreadystatechange = function() {
                            if (xhttp.readyState == XMLHttpRequest.DONE) {
                                console.log(xhttp.responseText);
                                if (xhttp.status === 200) {
                                    console.log('successful');
                                 } else {
                                    console.log('failed');
                                 }
                            }
                        }
                        xhttp.open("POST", base_url_admin+"record/reporte", true);
                        xhttp.setRequestHeader("Content-type", "application/json");
                        let data = JSON.stringify({"resultChartImg": imgRes});
                        xhttp.send(data);
                    }

php:

header("Content-Type: application/json");
// build a PHP variable from JSON sent using POST method
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);exit();

javascript map function returned undefined

const numbers = [1, 2, 3, 4];
const filteredNumbers = numbers.map((num, index) => {
  if (index < 3) {
    return num;
  }
});

// filteredNumbers is [1, 2, 3, undefined]

According to my understanding callback function should return all numbers of array if their index is less than 3 so it should return 1,2,3 and stop after that and number 4 can not be returned as if condition says index should be less than 3.
I am wondering why it returned undefined for index 3 number.

How to get values using JavaScript from Html.BeginForm() ASP.NET MVC

I want to get display the values the user has typed after the “Add” button is pressed. But I don’t know why my code displays undefined instead of the values.

I am passing multiple instances of my model objects to the controller as a list.

This is my View:

@model List<MVCModel.Models.Student>

 <b>Result</b>    @ViewBag.s <br />
  
@using (Html.BeginForm("Form", "Home", FormMethod.Post))
{
<table>
    <tbody id="GenaratorList">
        <tr>
          @{
            int counter = 0;
            <td>Enter Name: </td>
            <td>@Html.TextBoxFor(m => m[counter].Name)</td>
            <td>Enter Age: </td>
            <td>@Html.TextBoxFor(m => m[counter].Age)</td>
            <td><input type="button" value="Add" onclick="addGenarator()" /></td>
        </tr>
        counter++;
        }
     <tbody>
</table>
<input type="submit" value="Submit Form"/>
}

<script>
    count = 0;
    function addGenarator() {
        var Name = $('#Name').val();
        var Age = $('#Age').val();
        var Student = "studentModels[" + count + "]";
        $('#GenaratorList').append('<tr><td><input id="' + Student + '.Name" Name="' + Student + '.Name" type="text" class="form-control" readonly value="' + Name + '"></td><td><input id="' + Student + '.Age" Age="' + Student + '.Age" type="text" class="form-control" readonly value="' + Age + '"></td></tr>');
        $('#Name,#Age').val('');
        count++;
    }
</script>

How to show different error messages with useForm’s errors

There is an Input component that is required and numeric. I want to show an error message 'required field' if there is no input and 'should be a numeric value' if the input isn’t a number.

Here is the code:

  const schema = yup.object().shape({
    myField: yup.number().required('required field')
  });
  
  ...

  const DEFAULT_DATA = {
    myField: 1,
  };

 ...

 
 const {
    handleSubmit,
    register,
    reset,
    formState: { errors },
    control
  } = useForm({
    defaultValues: output
      ? { ...output }
      : DEFAULT_DATA,
    resolver: yupResolver(schema)
  });

 ...

<Input
  errorMessage={
    errors.myField?.type
      ? 'should be a numeric value'
      : errors.proximityFirst?.message
        ? 'required field'
        : ''
  }
  {...register('myField')}
/>;

Something is wrong as it shows 'required field' even when the input is a string, for numeric values it works fine, just for non-numeric values the error message is wrong.

Any ideas?

How to change the dataAxis fontsize?

The dataAxis is the label of each bar chart, however, I don’t know how to change the fontsize of the axis label in the bar chart.

Here is the code from echart:

https://echarts.apache.org/examples/zh/editor.html?c=bar-gradient

I think the current font size is around 12, I am trying to change the size to 14 or 18.

Tailwind classes not working in Svelte app

I’ve continuously been trying for days to get Tailwind classes working with my Svelte project. I followed the exact steps from here and still nothing works.

Here’s the structure of my svelte project:

enter image description here

The postcss.config.cjs code:

const tailwindcss = require("tailwindcss");
const autoprefixer = require("autoprefixer");
module.exports = {
  plugins: [require("tailwindcss"), require("autoprefixer")],
};

The tailwind.config.js code:

const production = !process.env.ROLLUP_WATCH;

module.exports = {
  future: {
    purgeLayersByDefault: true,
    removeDeprecatedGapUtilities: true,
  },
  plugins: [],
  purge: {
    content: ["./src/App.svelte"],
    enabled: production, // disable purge in dev
  },
};

in tailwind.css file:

@tailwind base;
@tailwind components;
@tailwind utilities;

in package.json file:

{
  "name": "svelte-app",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "watch:tailwind": "postcss public/tailwind.css -o public/index.css -w",
    "build:tailwind": "cross-env NODE_ENV=production postcss public/tailwind.css -o public/index.css",
    "build": "npm run build:tailwind && rollup -c",
    "start": "sirv public",
    "serve": "serve public -p 80",
    "dev": "concurrently "rollup -c -w" "npm run watch:tailwind""
  },

  "devDependencies": {
    "@rollup/plugin-commonjs": "^17.0.0",
    "@rollup/plugin-node-resolve": "^11.0.0",
    "@types/autoprefixer": "^10.2.0",
    "concurrently": "^7.2.2",
    "cross-env": "^7.0.3",
    "postcss-cli": "^7.1.2",
    "rollup": "^2.3.4",
    "rollup-plugin-css-only": "^3.1.0",
    "rollup-plugin-livereload": "^2.0.0",
    "rollup-plugin-svelte": "^7.0.0",
    "rollup-plugin-terser": "^7.0.0",
    "svelte": "^3.0.0"
  },
  "dependencies": {
    "autoprefixer": "^10.4.7",
    "postcss": "^8.4.14",
    "sirv-cli": "^2.0.0",
    "tailwindcss": "^3.1.3"
  }
}

What is it that I’m doing wrong? I’ve looked for so many answers on the web but still nothing works in my laptop…
Tho, the Tailwind CDN works but that’s not what I wanted!

Running script after linking packages via yarn3 leads to missing modules error

I have two repositories:

  1. Automation framework based on webdriverio (with yarn3 as package manager and nodelinker pnpm) (named = taf)

package.json

    "dependencies": {
        "@name/controls": "^1.0.7",
        "@wdio/cli": "~7.19.6",
        "@wdio/cucumber-framework": "~7.19.5",
        "@wdio/local-runner": "~7.19.5",
        "@wdio/shared-store-service": "~7.19.5",
        "@wdio/spec-reporter": "~7.19.5",
        "chromedriver": "~102.0.0",
        "cucumber-html-reporter": "~5.5.0",
        "date-fns": "~2.28.0",
        "fs-extra": "~10.1.0",
        "ignore-case": "~0.1.0",
        "properties-reader": "~2.2.0",
        "wdio-chromedriver-service": "~7.3.2",
        "wdio-cucumber-parallel-execution": "~3.6.15",
        "wdio-cucumberjs-json-reporter": "~4.4.1",
        "wdio-image-comparison-service": "~3.1.1",
        "winston": "~3.7.2",
        "xmlhttprequest": "~1.8.0"
    },
    "devDependencies": {
        "chalk": "4.1.2",
        "eslint": "^8.14.0",
        "husky": "^8.0.0",
        "jest": "~28.0.2",
        "node-emoji": "^1.11.0",
        "pinst": "^3.0.0",
        "webdriverio": "^7.20.1",
        "yargs": "^17.5.1"
    },
    "packageManager": "[email protected]",
    "resolutions": {
        "@name/controls": "portal:/controls"
    }
}
  1. Controls library (with npm as package manager) (named = controls)

package.json

  "devDependencies": {
    "@wdio/cli": "^7.19.7",
    "@wdio/cucumber-framework": "^7.19.7",
    "ignore-case": "^0.1.0",
    "jest": "^28.1.0",
    "winston": "^3.7.2"
  }

When I run a command in 1st repository:

> yarn link ~/controls

It successfully links with 2nd repository. I can change code and see changes via node_modules folder in 1st repository.

But when I’m trying to execute any script inside 1st repository, I receive an error:

Error: Cannot find module 'winston'
Require stack:
- controlslibraryutilsLogger.js
- tafwdio.conf.js
- [email protected][email protected]
- [email protected][email protected]
- [email protected][email protected]
- [email protected][email protected]
- [email protected][email protected]
- [email protected][email protected]
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (controlslibraryutilsLogger.js:1:17)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)

Without linking, everything is working perfect. No errors regarding missing modules.

AWS S3 headObject – getting undefined

exports.handler = async (event) => {
    const key = decodeURIComponent(event.Records[0].s3.object.key).replace(/+/g, " ");
    const bucket = event.Records[0].s3.bucket.name;

    new AWS.S3().headObject({ Bucket: bucket, Key: key }, function(err, data)
    {
        if (!err)
        {         
            console.log("Err data: "+data.Body);//data is undefined 
            metadata = data;        
        }else{
            metadata = data;
        }
    });
};

No error is thrown but I keep getting data as undefined!
Any idea

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of “”

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "". Strict MIME type checking is enforced for module scripts per HTML spec.

Failed to load Vuejs components

I use Ruby-on-Rails 7 for the backend part, and VueJS 3 for frontend.

I added vue js dependencies to importmap configuration.
Path: config/importmap.rb:

pin "application", preload: true
pin "vue", to: "https://ga.jspm.io/npm:[email protected]/dist/vue.esm-browser.js"

path : app/javascript/application.js

import * as View from "view"
import PollShow from "./PollShow.vue"

const app = Vue.createApp()

app.component('PollShow', PollShow)
app.mount('#poll_show')

And then added vue js import vuejs and component PollShow.vue in application.js
However vue js import works well but component import is not working.
Do you have any idea why this is not working ?

Page is not getting loaded with fecthed Data using dropdown selection

I am Selecting a dropdown, whose value is passed to a stored procedure as parameter. I am getting the data from database but the data is not getting loaded into same page.

Page A is loaded with data and a dropdown,now once dropdown is selected it should refresh the Page A with newly fetched data but page is rendering the old data. I Am confused.. can anyone help me out ?
i am able to fetch data of the selected dropdown value just that data is not getting loaded into the same page PageA

PageA.cshtml.cs
PageA.cshtml
PageA.cshtml.cs (Javascript)

How to stop refreshing the web page in react [closed]

I am not maintaining a code that is written by someone else.

There is a form in the page. Is page is re-rendered after clicking the Submit button ? In my onSubmit method, there is not a code piece that re-render the web page. I want to stop refreshing the page, I also used preventDefault but it didn’t work
enter image description here

Code:
enter image description here

enter image description here

Please help me

xTypeError: Cannot read properties of undefined (reading ‘author’)

I’m learning to build my blog by following this Githup tutorial (https://github.com/adrianhajdin/project_graphql_blog) but when I was using [slug].js to build my localhost/3000/post/react-tesing, it puts me this error:
TypeError: Cannot read properties of undefined (reading ‘author’)
I’ve checked that several times but had no idea. So how can I fix this ? Thx!

[slug].js
import React from 'react'
import {getPosts, getPostDetails} from '../../services';
import {PostDetail, Categories, PostWidget, Author, Comments, CommentsForm} from '../../components';

const PostDetails = ({post}) => {
  return (
    <div className='container mx-auto px-10 mb-8'>
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-12">
            <div className='col-span-1 lg:col-span-8'>
                <PostDetail post={post} />
                <Author author={post.author} />
                <CommentsForm slug={post.slug} />
                <Comments slug={post.slug}/>
            </div>
            <div className='col-span-1 lg:col-span-4'>
                <div className='relative lg:sticky top-8'>
                    <PostWidget slug={post.slug} categories={post.categories.map((category) => category.slug)}/>
                    <Categories />
                </div>
            </div>
        </div>
    </div>
  );
};

export default PostDetails;

my index.js – services:

export const getPostDetails = async (slug) => {
  const query = gql`
    query GetPostDetails($slug: String!) {
      post(where: {slug: $slug}) {
        title
        excerpt
        featuredimage {
          url
        }
        author{
          name
          bio
          photo {
            url
          }
        }
        createdAt
        slug
        content {
          raw
        }
        categories {
          name
          slug
        }
      }
    }
  `;
  const result = await request (graphqlAPI, query, {slug});

  return result.post;
};