When I add html code to the variable, it shows as Nan

 var test = "";
    for (var i = 0; i < controlResponse.classifications.length; i++) {
        test+='<div role="option" aria-checked="false" class="select item" style="pointer-events: all;"><span class="text">' + controlResponse.classifications[i].name + ' </span></div>';

    }
   
    for (var i = 0; i < controlResponse.fileList.length; i++) {

        var htmlCode='<div class="row">                                                                                                                                                      '+
         '   <div class= "ten wide computer sixteen wide mobile ten wide tablet column">                                                                                                    '+
         '   <h5 class="ui header">                                                                                                                                                          '+
         '       <i aria-hidden="true" class="file word outline large icon fa-fw"></i>                                                                                                       '+
         '       <div class="content">outlook_testler.docx</div>                                                                                                                             '+
         '   </h5>                                                                                                                                                                           '+
         '       </div > <div class="six wide computer sixteen wide mobile six wide tablet column">                                                                                          '+
         '       <div role="listbox" aria-expanded="false" class="ui selection dropdown" tabindex="0" style="float: right;">                                                                 '+
         '           <div aria-atomic="true" aria-live="polite" role="alert" class="divider default text">Classification</div><i aria-hidden="true" class="dropdown icon"></i>               '+
            '           <div class="menu transition classifications">                                                                                                                      ' +
            +test+
            '           </div>                                                                                                                                                                  ' +
         '   </div>                                                                                                                                                                      '+
         '   </div>                                                                                                                                                                          '+
            '   </div>';
        $("#classificationModalList").append(htmlCode);

         
    }

When I add html code to the variable, it shows as NaN.
I add select item html codes to test variable then I added test variable inside htmlCode variable
then I added test variable inside htmlCode variable

Websocket: there are 2 connections in chrome devtools?

In chrome (js client), after connect to backend (golang) via websocket, I saw 2 connections in chrome devtools:

  1. Frist connection, shows request url as: ws://localhost:3000/, and 3000 is the port of my frontend UI.
    messages:

    • a single connected message
    • a serial of ping message (every 30 seconds).
  2. Second connection, shows request url as ws://localhost:18081/api/v1/.., and 18081 is the port of my websocket backend.
    messages:

    • the read/write messages that client/server send to each other, by programmer.

The questions are:

  • How many websocket connections are there between the js browser client & go server?
    I suppose there is only 1.
  • If there is only 1, why chrome devtools shows it as 2 connections?
    Or, chrome just shows them separately for easier debug?

Customize DateTimeRangeContainer

I’m creating the ability to select a range by date and time. For this I use DateTimeRangeContainer from the react-advanced-datetimerange-picker library.

However, in order to save space, I would like to get rid of some elements that are unnecessary for me. Below in the photo is a window in which the functionality is presented. And with red rectangles, I marked the elements that I would like to get rid of.

enter image description here

My code below:

      .........
     return (
    <ArrowDropdown
        isExpanded={isExpanded}
        setIsExpanded={setIsExpanded}
        title="Date and Time range"
        onClick={() => setIsExpanded(!isExpanded)}>
                  <div>
                  <Container>
        <br />
        <Row className="show-grid" style={{ textAlign: "center" }}>
          
          <Col xs={15} md={16} id="DateTimeRangeContainerMobileMode">
            <DateTimeRangeContainer
              start={start}
              end={end}
              local={local}
              applyCallback={applyCallback}
              forceMobileMode
            >
              <FormControl
                  id="formControlsTextB"
                  type="text"
                  label="Text"
                  placeholder="Enter text"
                  style={{ cursor: "pointer" }}
                  disabled={disabled}
                  value={value}
              />
            </DateTimeRangeContainer>
          </Col>
          <Col xs={3} md={4} />
        </Row>
        <br />
      </Container>
    </div>

    </ArrowDropdown>
  );
}

How to get OAuth token after Google One Tap sign in

I have been reading the documentation and so far no luck, require the oAuth Access token as well. however the Google Identity service does not give back oAuth Access token. instead it returns a JWT token.

Link to documentation :
Google One Tap Sign in

<script src="https://accounts.google.com/gsi/client" async defer></script>
<script>

    window.onload = function () {
        google.accounts.id.initialize({
            client_id: 'myid.apps.googleusercontent.com',
            callback: handleCredentialResponse
        });
        google.accounts.id.prompt();
    }

</script>

<script>
    function parseJwt(token) {
        var base64Url = token.split('.')[1];
        var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
        var jsonPayload = decodeURIComponent(atob(base64).split('').map(function (c) {
            return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
        }).join(''));

        return JSON.parse(jsonPayload);
    };

    function handleCredentialResponse(response) {
        console.log(response);
        const responsePayload = parseJwt(response.credential);
        console.log(responsePayload);
    }
</script>

Is it possible to read variable names inside template literal function

I have a function for template literals and when using it like this I want to get the variable name which is here ‘count’ as string inside my html template string function, is there any way?

const count = 0;

html`<h3>Count: ${count}</h3>`;

Get ‘count’ as string here, or even the whole unprocessed string like “<h3>Count: ${count}</h3>“

export function html(literals, ...vars) {
  // get function and variable names like 'count' here
  console.log(literals.raw);
  console.log(...vars);
}

JavaScript: How to merge two object but keep only the property of the second object if it exists?

This code merges two objects. How to amend it so that a property is discarded of the first object if it exists in the second object?

E.g. object 1 has this property:

surname: {
    test: '123',
    other: '124'
},

and object 2:

surname: {
    test: '124'
},

The merge would use the property of object 2 (other: '124' would not exist in the merged result)

function merge(...objects) {
    function m(t, s) {
        Object.entries(s).forEach(([k, v]) => {
            t[k] = v && typeof v === 'object' ? m(t[k] || {}, v) : v;
        });
        return t;
    }

    return objects.reduce(m, {});
}

var obj1 = {
        name: '112',
        surname: {
            test: '123',
            other: '124'
        },
        age: 151,
        height: '183',
        weight: 80
    },
    
    obj2 = {
        name: '114',
        surname: {
            test: '124'
        },
        age: 151,
        height: 184,
        weight: 81
    },
    
    result = merge(obj1, obj2);

console.log(result);

Get the text next to @ char in string with JavaScript

I’m implementing a mentions mechanism in a React based chat application. When the user types @ in the textarea I am opening a list of members of the group and performing a search in that list using the text which comes after the @ char. The code for search query extraction is as follows:

const regexp = /@(S+)/g;
const text = regexp.exec(message);
let mentionText = '';
mentionText = text ? text[0] : '@';

This works only if there’s 1 @ char in the string. For example, if there’s an e-mail written in the message text before the @ char which opens the list of members, this will not work because I’m taking the first item in the array which is the e-mail.

Is there a better/more elegant/better working way to get the search term from the entered string? I basically need to take the text which comes after @ char which is not an e-mail, for example. Yes, to be more precise – text before @ char which has a heading space. That way I can tell for sure that the user wants to write a mention. Basically I think it should be like this @. If there’s a space and a @ sign next to it – the user is writing a mention. The problem is how to identify that @ – with a heading space.

Thanks!

How can I prevent states from resetting after a http request?

when I send the server an HTTP request ( patch request in the checkbox onChange function) and update the state other states will be deleted until i reload the page and they will be back
so how can I update the states without losing the others?
I’m not totally sure but I think the problem is where I save the state with the response I get from the server I think I’m not updating it and I’m just adding the new response

here’s my code



const Form = () => {
  const [todos, setTodos] = React.useState([]);

  const debounce = (func, timeout = 350) => {
    let timer;
    return (...args) => {
      clearTimeout(timer);
      timer = setTimeout(() => {
        func.apply(this, args);
      }, timeout);
    };
  };
  const saveInput = (e, id) => {
    const x = !e.target.checked;
    console.log(x);

    axios
      .patch(`http://127.0.0.1:8000/todo/todos/${id}/`, {
        completed: x,
      })
      .then(
        (response) => {
          console.log(response.data);

          setTodos([response.data]);
        },
        (error) => {
          console.log(error);
        }
      );
  };
  const processChange = debounce((e, id) => saveInput(e, id));

  useEffect(() => {
    axios.get("http://127.0.0.1:8000/todo/todos/").then((response) => {
      setTodos(response.data);
    });
  }, []);

  return (
    <form>
      <h1>Todo list</h1>
      <button>Add</button>
      <div>
       
          {todos.map((todo) => (
            <ul key={todo.id}>
              <li>{todo.title}</li>
              <li>{todo.description}</li>
              <button onClick={() => deleteHandler(todo.id)}>delete</button>
              <input
                type="checkbox"
                placeholder="completed"
                onChange={(e) => processChange(e, todo.id)}
                checked={todo.completed}
              />
            </ul>
          ))}
       
      </div>
    </form>
  );
};

export default Form;

Hello, my qustion is “html write text in to text file on the website”

i only found something that download me the text file but i want that the guys can write stuff in the text file, and maybe with ther name before the text come, so like that:

“Name”: I want cookies for all

btw pls give me no php stuff

and that is all what i found
and that what is write in the text file i a bit good, because that there is the name and the massage
sooo here is what i found now:

<!DOCTYPE html>
<html>
<head>
<title>Save form Data in a Text File using JavaScript</title>
<style>
    * {
        box-sizing: border-box;
    }
    div {
        padding: 10px;
        background-color: #f6f6f6;
        overflow: hidden;
    }
    input[type=text], textarea, select {
        width: 100%;
        padding: 12px;
        border: 1px solid #ccc;
        border-radius: 4px;
    }
    input[type=button]{ 
        width: auto;
        float: right;
        cursor: pointer;
        padding: 7px;
    }
</style>
</head>
<body>
<div>
    
    <!--Add few elements to the form-->

    <div>
        <input type="text" id="txtName" placeholder="Enter your name" />
    </div>
    <div>
        <input type="text" id="txtAge" placeholder="Enter your age" />
    </div>
    <div>
        <input type="text" id="txtEmail" placeholder="Enter your email address" />
    </div>
    <div>
        <select id="selCountry">
            <option selected value="">-- Choose the country --</option>
            <option value="India">India</option>
            <option value="Japan">Japan</option>
            <option value="USA">USA</option>
        </select>
    </div>
    <div>
        <textarea id="msg" name="msg" placeholder="Write some message ..." 
    <style="height:100px"></textarea>
    </div>

    <!--Add to button to save the data.-->
    <div>
        <input type="button" id="bt" value="Save data to file" onclick="saveFile()" />
    </div>
</div>
</body>
<script>
let saveFile = () => {
    
    // Get the data from each element on the form.
    const name = document.getElementById('txtName');
    const age = document.getElementById('txtAge');
    const email = document.getElementById('txtEmail');
    const country = document.getElementById('selCountry');
    const msg = document.getElementById('msg');
    
    // This variable stores all the data.
    let data = 
        'r Name: ' + name.value + ' rn ' + 
        'Age: ' +age.value + ' rn ' + 
        'Email: ' + email.value + ' rn ' + 
        'Country: ' + country.value + ' rn ' + 
        'Message: ' + msg.value;
    
    // Convert the text to BLOB.
    const textToBLOB = new Blob([data], { type: 'text/plain' });
    const sFileName = 'formData.txt';      // The file to save the data.

    let newLink = document.createElement("a");
    newLink.download = sFileName;

    if (window.webkitURL != null) {
        newLink.href = window.webkitURL.createObjectURL(textToBLOB);
    }
    else {
        newLink.href = window.URL.createObjectURL(textToBLOB);
        newLink.style.display = "none";
        document.body.appendChild(newLink);
    }

    newLink.click(); 
}

the code is from here:
https://www.encodedna.com/javascript/how-to-save-form-data-in-a-text-file-using-javascript.htm

How can clean a select2 option selected after main option changed with json values?

I’m trying to cleanup an option selected but only is working with the last select2 option and i’m facing issues when i choose the first select2, the last select2 is still active showing old values

<html lang="en">
<head> 
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet"/>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
</head>
<body>

 <select name="customerId" id="customerId">
   <option value="">Seleccione</option>
 </select>

 <select name="customerDetail" id="customerDetail"></select>

<select name="customerDetail2" id="customerDetail2"></select>

<script>
let getCustomers = async (id, path) => {
    let data = []
    await fetch(path)
        .then(response => response.json())
        .then(response => {
            data = response.map((value, index) => {
                return {
                    id: value.id,
                    text: value.name
                }
            })
            $(id).select2({
                placeholder: "Seleccione",
                width: '250px',
                data: data
            })
        });
    return data
}
let getCustomerDetails = async (id, path, $el, field) => {
    let data = []
    await fetch(path)
        .then(response => response.json())
        .then(response => {
            let filter = response.filter((value, index) => {
                return ($el.value == value[field])
            })
            data.push({
                id: 0,
                text: 'Seleccione',
            }) 
            filter.forEach((value, index) => {
                data.push({
                    id: value.id,
                    text: value.name
                })
            })
            $(id).empty()
            $(id).select2({
                placeholder: "Seleccione",
                width: '250px',
                data: data
            })
        });
    return data
}
$(window).on('load', () => {
    $('select').select2({
        placeholder: "Seleccione",
        width: '250px',
    })
    getCustomers('#customerId', 'customers.json')
    
    $('#customerId').on('change', (e) => {
        let $element = e.target
        getCustomerDetails('#customerDetail', 'customersDetails.json', $element, 'customer_id')
    })
    $('#customerDetail').on('change', (e) => {
        let $element = e.target
        getCustomerDetails('#customerDetail2', 'customersDetails.json', $element, 'customer_owner')
    })
})

</script>

</body>
</html>

Here is the customers.json

[
 {
   "id": 1,
   "name": "company demo"
  }
]

Here is customerDetails.json

[
 {
   "id": 1,
   "customer_id": 1,
   "customer_owner": 1,
   "name": "Customer detail 1",
 }
]

I will appreciate all your comments.

Honestly i don’t know how to display on jsfiddle but the information is here:

https://jsfiddle.net/cmorales/cw91ts3n/2/