Disable “Entries Per Page” Dropdown — Bootstrap Table

I want to disable the “Entries per page” dropdown and the search bar.

I saw the below codes (BLOCK 1) in the documentation, but I don’t think I understand how to implement those in my current script (BLOCK 2). I tried what I could, it didn’t work.

/* BLOCK 1 */

$(document).ready(function () {
        $('#dtBasicExample').DataTable({
         "ordering": false // false to disable sorting (or any other option)
        });
        $('.dataTables_length').addClass('bs-select');
      });

/* BLOCK 2 */

window.addEventListener('DOMContentLoaded', event => {
    // Simple-DataTables
    // https://github.com/fiduswriter/Simple-DataTables/wiki

    const datatablesSimple = document.getElementById('datatablesSimple');
    if (datatablesSimple) {
        new simpleDatatables.DataTable(datatablesSimple, {
        perPage: 1,
    }); 
    }
});

Is it a good idea to use useLayoutEffect hook for responsive web design in React app?

I making a website and as usual, the website has to be responsive. I have just migrated to react js to make frontend designs before that I made the designs with HTML, CSS and vanilla js. So before migrating to react, I made sites responsive with CSS media queries as usual, but now after migrating to react I came across the hook useLayoutEffect and its use that it runs synchronously on load. So if I track the window size inside the hook, then render out the completely different layout for different break-points and not use CSS media queries. Will it be a good idea? Can this hook be used for this purpose?

Please advise me what would be better.

Aurelia hiding/ and showing div element when button click is not working

I am trying to hide and show div element based on the button that is clicked. I used if.bind and show.bind but neither of them is working.

<div class="right" if.bind="toggleView()=== true" data-bind = "visible: activeTab() === 'right div'">
<p>This is a right div</p>
<div data-bind="click: hideLeftDiv">
     <label for="TestButton">
                        <svg class="ico"><use xlink:href="Content/icons/icons.svg#div" /></svg>
                        <span>Test Button</span>
                    </label>
</div>
</div>
<div class = "left data-bind = "visible: activeTab() === 'left div'">
<p>This is a left div</p>
</div>
import * as dialog from 'plugins/dialog';
import * as system from 'durandal/system';
import * as ko from 'knockout';


enum divs {
    RIGHT_DIV = "Right div",
    LEFT_DIV = "Letf div"
}

class test{
  private activeTab: KnockoutObservable<divs> = ko.observable(divs.RIGHT_DIV);
  private toggleView: KnockoutObservable<boolean> = ko.observable(false);
  
  async activate(){
  }
  
  async hideLeftDiv() {
        return this.toggleView(false);
    }
    
}

I am expecting it to hide the left div element when I click the Test button div. but it is not working as expected.

Getting video audio from another domain for visualisation

On my web page I’m looking to get an audio level visualisation from a video source created on another domain, both of which I control. I am considering using the this library, which contains the following example code:

var myMeterElement = document.getElementById('my-peak-meter');
var myAudio = document.getElementById('my-audio');
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var sourceNode = audioCtx.createMediaElementSource(myAudio);
sourceNode.connect(audioCtx.destination);
var meterNode = webAudioPeakMeter.createMeterNode(sourceNode, audioCtx);
webAudioPeakMeter.createMeter(myMeterElement, meterNode, {});
myAudio.addEventListener('play', function() {
  audioCtx.resume();
});

Because the source is from another domain, I cannot access the element directly with getElement. I understand the postMessage() function allows the sending cross-origin data, however am not sure how to apply it to a scenario like this, or whether this will even work. Any suggestions?

Chrome extension to replace text on webpage works only after manually refreshing webpage sometimes

I am developing a chrome extension to replace specific texts on webpage. For some websites, it works only after refreshing webpages manually with F5. For example, when I open http://www.iciba.com/ and input Google and press Enter, all Google texts in results are not replaced. But after I press F5 to refresh page manually, all texts are replaced.

manifest.json:

{
    "name": "My Extension",
    "version": "0.1.0",
    "description": "An extension that replaces texts on webpages",
    "manifest_version": 2,
    "permissions": [
        "tabs",
        "<all_urls>"
    ],
    "content_scripts": [{
        "matches": [
            "http://*/*",
            "https://*/*"
        ],
        "js": [
            "replacetxt.js"
        ],
        "run_at": "document_end",
        "all_frames": true
    }]
}

replacetxt.js:

function isExcluded(elm) {
  if (elm.tagName == "STYLE") {
    return true;
  }
  if (elm.tagName == "SCRIPT") {
    return true;
  }
  if (elm.tagName == "NOSCRIPT") {
    return true;
  }
  if (elm.tagName == "IFRAME") {
    return true;
  }
  if (elm.tagName == "OBJECT") {
    return true;
  }
  return false
}

function traverse(elm) {
  if (elm.nodeType == Node.ELEMENT_NODE || elm.nodeType == Node.DOCUMENT_NODE) {

    // exclude elements with invisible text nodes
    if (isExcluded(elm)) {
      return
    }

    for (var i=0; i < elm.childNodes.length; i++) {
      // recursively call to traverse
      traverse(elm.childNodes[i]);
    }

  }

  if (elm.nodeType == Node.TEXT_NODE) {

    // exclude text node consisting of only spaces
    if (elm.nodeValue.trim() == "") {
      return
    }

    // elm.nodeValue here is visible text we need.
    console.log(elm.nodeValue);
    elm.nodeValue = elm.nodeValue.replace("Google", "***");
  }
}

traverse(document);

Javascript handling specific text format

Hello i need help with handling specific text format.

It should look like this

Input:
!tip 10 coin

Output:
!tip+number+string

I need to split this text to 3 section, first its immutable string its always !tip and then number and string. I need to get any number. And string any string. Anyone could help me with this. I tried lot of things but nothing helped me.
Thanks

custom file input button, creating an invisible input file type inside div inside button for file input

I would like to make a file input button like the one in Amazon write a review pictured below

amazon upload button

How is it possible that the entire button opens up the file dialog on click if the input file type is hidden?

amazon upload photo button code

My code here hides the input file type button but does not open the file dialog. It is using React with tailwind classes

    <button
      type="button"
      className="p-6"
    >
      <div aria-label="Add a photo">
        <HiOutlinePlus className="text-4xl" />
        <input type="file" accept="image/*" className="hidden" />
      </div>
    </button>

Using sequelize to get data from two separate databaes and combining them

I’m trying to get data from two different databases, I can not modify the data, I can only query them to fetch data.

I’d like match them by the primaryKey (uuid in this case) and join them together. I think I’m close, I’m just not there yet.

Here’s how I’m defining my two databases and models:

// database instances
exports.townyDB = new Sequelize(env.DB_TOWNY, env.DB_USER, env.DB_PASS, {
    host: env.DB_HOST,
    port: env.DB_PORT,
    dialect: 'mariadb',
    schemas: true
});

exports.townyDB = new Sequelize(env.DB_TOWNY, env.DB_USER, env.DB_PASS, {
    host: env.DB_HOST,
    port: env.DB_PORT,
    dialect: 'mariadb',
    schemas: true
});

// models


const townyResident = townyDB.define("towny_resident", {
    name: {
        type: DataTypes.STRING
    },
    player_uuid: {
        type: DataTypes.STRING,
        primaryKey: true,
        field: 'uuid'
    },
}, {
    tableName: 'TOWNY_RESIDENTS',
    schema: "s10_towny",
    timestamps: false,
    createdAt: false,
    updatedAt: false
});

const CMIUser = cmiDB.define("cmi_user", {
    player_uuid: {
        type: DataTypes.STRING
    },
    username: {
        type: DataTypes.STRING
    },
}, {
    tableName: 'CMI_users',
    schema: "s3_cmi",
    timestamps: false,
    createdAt: false,
    updatedAt: false
});

export default CMIUser;


// Calling both

        CMIUser.hasOne(townyResident, { foreignKey: 'uuid' });
        townyResident.belongsTo(CMIUser, { foreignKey: 'player_uuid' })
        const test = await CMIUser.findOne({
            raw: true, attributes: ['player_uuid', 'username', 'nickname'], order: cmiDB.literal('TotalPlayTime ASC'), where: { player_uuid: userUUID },
            include: [{ model: townyResident, player_uuid: userUUID }]
        });

Which seems like I’m close, the test returns:

{
  player_uuid: '313f0b76-20de-473a-82fb-45684ea4431d',
  username: 'mzya',
  'towny_resident.name': null,
  'towny_resident.player_uuid': null,
  'towny_resident.uuid': null
}

I don’t think towny_resident. should be in the result, and it shouldn’t be null. What am I doing wrong?

React router dom will not re render page but URL is changing on click [duplicate]

My components are not rendering on “Link” clicks but the url route does change, and if I manually refresh the browser the correct page renders. I have a private route created for the ‘/’ path that uses a redirect if the user is not authenticated and send them back to the login. I have had a similar app working before almost set up identically but with using context instead of redux. I have read that react-router-dom and redux don’t exactly pair well together but I don’t fully understand why, I tried linking it up to the npm package “History” but saw multiple ways it can be done and couldn’t successfully make it work. I can provide any additional code/information needed. Big thanks in advance to anyone that can assist. Also here is a link to the full repo:
https://github.com/AustinRobinsonDev/license

If I log in with the correct credentials the navbar links change from “guestLinks” to “auth” but it stays on the login form page, the links are the only thing that will update

Versions:

  • react-router-dom 5.2.0
  • react-dom 18.0.0
  • redux 4.1.2

here is my main app.js:

const App = () => {
  return (
    <Provider store={store}>
      <Router>
        <>
        <Navbar />
          <Switch>
            <Route exact path='/about' component={About} />
            <Route exact path='/register' component={Register} />
            <Route exact path='/login' component={Login} />
            <PrivateRoute exact path='/' component={Home} />
          </Switch>
        </>
      </Router>
    </Provider>
  );
}

export default App;

Navbar with the router Links:

const Navbar = ({auth, logout, clearLicense}) => {
    const onLogout = () => {
        logout();
        clearLicense();
    }
    const authLinks = (
        <>
            <li>Hello {auth.user && auth.user.name}</li>
            <li>
                <a onClick={onLogout} href="#!">
                    <span className="hide-sm">Logout</span>
                </a>  
            </li>
        </>
    )
    const guestLinks = (
        <>
            <li>
                <Link to='/register'>Register</Link>
            </li>
            <li>
                <Link to="/login">Login</Link>
            </li>
        </>
    )
    return (
        <div className='navbar bg-primary'>
            <h1>License Manager{' '}Icon</h1>
            <ul>
                {auth.isAuthenticated ? authLinks : guestLinks}
            </ul>
        </div>
    )
}

const mapStateToProps = state => ({
    auth: state.auth
});

export default connect(mapStateToProps, { logout, clearLicense })(Navbar);

and an example of a component that will not re render:

const Login = ({history, auth, setAlert, login}) => {

  useEffect(() => {
    if (auth.isAuthenticated) {
      history.push('/');
    }
    if (auth.error === 'Invalid Credentials') {
      console.log('error invalid credentials')
      setAlert(auth.error, 'danger');
      clearErrors();
    }
    // eslint-disable-next-line
  }, [auth.error, auth.isAuthenticated, history]);
  const [user, setUser] = useState({
    email: '',
    password: ''
  });

  const { email, password } = user;

  const onChange = e => setUser({ ...user, [e.target.name]: e.target.value });

  const onSubmit = e => {
    console.log('onSubmit clicked')
    e.preventDefault();
    if (email === '' || password === '') {
      setAlert('Please fill in all fields', 'danger');
    } else {
      login({
        email,
        password
      })
    }
  };

  return (
    <div className='form-container'>
      <h1>
        Account <span className='text-primary'>Login</span>
      </h1>
      <form onSubmit={onSubmit}>
        <div className='form-group'>
          <label htmlFor='email'>Email Address</label>
          <input
            id='email'
            type='email'
            name='email'
            value={email}
            onChange={onChange}
            required
          />
        </div>
        <div className='form-group'>
          <label htmlFor='password'>Password</label>
          <input
            id='password'
            type='password'
            name='password'
            value={password}
            onChange={onChange}
            required
          />
        </div>
        <input
          type='submit'
          value='Login'
          className='btn btn-primary btn-block'
        />
      </form>
    </div>
  );
};

const mapStateToProps = state => ({
  auth: state.auth
});

export default connect(mapStateToProps, {setAlert, login})(Login);

React Datepicker with react-hook-form Controller outputting undefined on form submit. Starting value passed from props

I am using react-datepicker inside react-hook-form’s Controller.
I passed the starting date from props to my form component, then I use useState to store that prop value in the component state. The type of the variable seems to be a date object, but I can’t figure out why using it as the selected value on Datepicker is causing the value to return undefined when I submit a form.
I am not doing any clicking on Datepicker. This undefined issue occurs on submitting the form with its initial value.
If I change the value on it and submit the form, it returns the date object as expected.
I want it to return a value if the user does not make any change. It should submit with that initial value provided, not undefined.

I have two date entries. The End Date component works if I do not provide a start value for it.
I have cut out other parts of the form that are irrelevant to this issue.

I am using react-hook-form v 7.29.0,
react-datepicker v 4.7.0,
and react v 18.0.
This most recent version of datepicker apparently doesn’t use moment anymore but just built-in date methods, so I’m not sure what is wrong with my starting date object provided. Can someone please provide some guidance/understanding to what is causing it to return undefined?

Thanks,
Code below:

import React, { useState } from 'react';
import { useForm, Controller } from 'react-hook-form';
import DatePicker from 'react-datepicker';

export default function EmployeeCard(props) {
  const { register, handleSubmit, control } = useForm();
  const employeeStartDateModified =new Date(props.employee.startDate);

  const modifiedProps = {
    ...props.employee,
    startDate: employeeStartDateModified,
  };

  const [employeeData, setInputValues] = useState(modifiedProps);

  let { firstName, middleName, lastName, salary, active, startDate, id, ptoBalance } =
    employeeData;

  const handleOnChange = event => {
    const { name, value } = event.target;
    setInputValues({ ...employeeData, [name]: value });
  };

  // did new state for startDate to see if the object would fix the undefined issue
  const [newStartDate, setNewStartDate] = useState(new Date(startDate));

  const onSubmit = registerData => {
    console.log(registerData); //other components of form show values, except startDate shows undefined. As soon as I change it from its initial value it console logs the date object. Same for endDate, which has no starting value. Entering a value in it and submitting returns the date object. Start date only returns undefined when provided the initial value in selected={}.
  };

  return (
    <form
      onSubmit={handleSubmit(onSubmit)}
      className='centered-container-form'
      key={id}
    >
      <div className='form-group'>
        <label htmlFor='startDate'>Start Date</label>
        <Controller
          control={control}
          name='startDate'
          render={({ field: { value = newStartDate, onChange } }) => (
            <DatePicker
              onChange={date => {
                setNewStartDate(date);
                onChange(newStartDate);
              }}
              selected={value}
              dateFormat='MM/dd/yyyy'
              required
            />
          )}
        />
      </div>
      <div className='form-group'>
        <label htmlFor='endDate'>End Date</label>
        <Controller
          control={control}
          name='endDate'
          render={({ field }) => (
            <DatePicker
              onChange={date => field.onChange(date)}
              selected={field.value}
              dateFormat='MM/dd/yyyy'
            />
          )}
        />
      </div>
      <button type='submit' className='btn btn-outline-primary'>
        Update
      </button>
    </form>
  );
}

Check if a text exists in a string in vuejs

<a-form-item label="Link" :colon="false">
     <a-input placeholder="Link" @blur="(e) => valueInput(e)" />
</a-form-item>

// script

methods: {
   valueInput(e) {
      console.log(e.target.value) 
       //result 1 : https://web-sand.io/browse/productOw/next-tip
       //result 2 : https://web-sand.io/browse/productOw/next-tip?name='next'
       //result 3 : https://web-sand.io/browse/next-tip
   }
},

I’m working with code in vuejs. Now I want to check that string. Now I want to check if the string exists productOw ? and if productOw exists, check if ?name exists? So is there a way to get productOw from the string to check. Because the input link has a different length and short format, I used incorrect string trimming. Please give me your opinion.thanks.

JS: using try/catch with more than one await?

I want to make a fetch request to an API and potentially catch the error using a try/catch. After I await the fetch, I await the response text(). This should never have an error . Is there a better way of writing this without both await‘s being inside the try/catch?

try {
    const response = await fetch(url, { method: 'POST', headers, body });
    const responseText = await response.text();
    
    if (responseText) {
        const a = responseText.split("<svg")[1].split("</svg>")[0]
        const svg = "<svg" + a + "</svg>";
        const blob = new Blob([svg], {type: 'image/svg+xml'});


        return blob;
    }  
} catch (e) {
    throw new Error('Returned error:' + e);
}

Appending List of Object to FormData JS

After Adding values to my profile packages and inspecting it from my JS that it has data contained in it, but on my server side when i push, ProfilePackages results to count = 0; even when Object List has Data.

This is my JS Code

var formData = new FormData();
    formData.append("Title", $("#profileTitle").val());
    formData.append("Duration", $("#txtDuration").val());
    formData.append("StartingPrice", $("#startPrice").val());
    formData.append("Description", $("#txtDescription").val());
    formData.append("CategoryId", $("#SubCatDropDown").val());
    $("#tablePackage tbody tr").each(function () {

        var packageDetails = {};
        packageDetails.Description = $(this).find("#desc").val();
        packageDetails.Amount = $(this).find("#amount").val();
        packageDetails.Duration = $(this).find("#hours").val();

        formData.append("ProfilePackages", JSON.stringify(packageDetails));
    });
   
    $.each($("#skills option:selected"), function (i, selected) {
        formData.append('ProfileSelectedSkills', selected.value);
        console.log(selected.value);
    });
    $.each($('.fileUpload')[0].files, function (key, input) {
        formData.append('Files', input);
        console.log(input);
    });

    $.ajax({
        async: true,
        type: 'POST',
        dataType: 'JSON',
        contentType: 'application/json; charset=utf-8',
        data: formData,
        processData: false,
        contentType: false,
        url: '/F/Profile/FAddProfile?handler=SaveProfile',
        beforeSend: function (xhr) {
            xhr.setRequestHeader("MY-XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },
        success: function (data) {
            alert(data);
            window.location = '/F/Profile/FProfile'; // redirect
        },
        error: function () {
            alert("Something went wrong");
        }
    });

And this is my Controler Model

 public int Id { get; set; }
    public string Description { get; set; }
    public int CategoryId { get; set; }
    public decimal StartingPrice { get; set; }
    public int Duration { get; set; }
    public string Title { get; set; }
    
    public virtual List<ProfileSkill> ProfileSkills { get; set; } = new List<ProfileSkill>();
    public virtual List<ProfileFiles> ProfileFiles { get; set; } = new List<ProfileFiles>();
    public virtual List<ProfilePackage> ProfilePackages { get; set; } = new List<ProfilePackage>();

When i push, ProfilePackges result to count = 0

how to set th:field thymeleaf from javascript variable

Salut, je travaille avec J2EE Spring boot jpa et thymeleaf
j’ai un formulaire (thymeleaf) lorsque je clique à un bouton d’ajout une table sera crée dynamiquement avec javascript,une ligne contient plusieurs select dropdown comment j’affecte les valeur sélectionnées dans la dropdown à un field de thymeleaf

le formulaire html :

        <form th:object="${order}" method="post" th:action="@{'/order'}">
 
          <table  id="myTable2" >
          <tr id="initialRow1" class="select_row">
          <td>  <button type="button" onClick ="addRow(this)">Add</button>
                  <label> Adultes</label>
                    <select id="select8" class="select1">
     
      <option>1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option
      ><option>5</option>
      <option>6</option>
    </select>
    <label>Enfatns</label>
    <select  id="idS" class="select2" onchange="myFunction()">
    <option value="0">0</option>
    <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option></select></td>
     
  
     
  
               </tr>
             </table>       
            <div class="mb-3">
                <label for="numberOfAdults">Nombre Adultes</label>
                <select  th:field="*{numberOfAdults}" class="form-select form-select-sm"
                        aria-label=".form-select-sm example">
                    <option th:each="idx: ${#numbers.sequence(0, travel.numberOfAdults)}"
                            th:value="${idx}"
                            th:text="${idx}"></option>
                </select>
            </div>
            <div class="mb-3">
                <label for="numberOfChildren">numberOfChildren</label>
                <select id="numberOfChildren" th:field="*{numberOfChildren}" class="form- 
           select form-select-sm"
                        aria-label=".form-select-sm example">
                    <option th:each="idx: ${#numbers.sequence(0, travel.numberOfChildren)}"
                            th:value="${idx}"
                            th:text="${idx}"></option>
                </select>
            </div>
            <div>
                <input type="hidden" th:field="*{travel.id}">
            </div>
            <script th:inline="javascript">
            /*<![CDATA[*/
            function sumOppositeWalls(nbrA){
              
                var table = document.getElementById('myTable2');
                var rowCount = table.rows.length;
                //alert(rowCount);
                var minusCount=0;
                for(var i=1;i<rowCount;i++){
                    nbrA=document.getElementById('id1_'+i).value;
                    alert(nbrA);
                   
                    
          }
                var wall2=document.getElementById('select8').value;
                alert(wall2);
            }/*]]>*/
            </script>
            <br>
            <button type="submit" class="btn btn-primary">Aller au sommaire
           </button>
        </form>

le javaScript

      <script th:inline="javascript">

         window. addRow = function addRow(btn) {  

        var parentRow = btn.parentNode.parentNode;
        var table = parentRow.parentNode;
        var rowCount = table.rows.length;

        var row = table.insertRow(rowCount);

        var cell1 = row.insertCell(0);
        var element1 = document.createElement("label");
        element1.type = "text";
        element1.innerHTML="Adultes :";
        cell1.appendChild(element1);


        var cell2 = row.insertCell(1);
        var element2 = document.createElement("select");
        element2.id="numberOfAdults" ;
        element2.setAttribute("th:field","*{numberOfAdults}");
          //element2.type = "select";
        var option1 = document.createElement("option");
        option1.innerHTML = "1";
        option1.value = "1";
        element2.add(option1, null);
        var option2 = document.createElement("option");
        option2.innerHTML = "2";
            option2.value = "2";
       element2.add(option2, null);
       var option2 = document.createElement("option");
      option2.innerHTML = "3";
      option2.value = "3";
      element2.add(option2, null);
      var option2 = document.createElement("option");
      option2.innerHTML = "4";
      option2.value = "4";
      element2.add(option2, null);
      var option2 = document.createElement("option");
       option2.innerHTML = "5";
       option2.value = "5";
      element2.add(option2, null);

      element2.add(option2, null);
        cell2.appendChild(element2);


         }
            </script>

enter image description here