Home > front end >  How to store value of an input box in a variable?
How to store value of an input box in a variable?

Time:02-10

I am trying to make a chat application with scaledrone. I was following this tutorial: https://www.scaledrone.com/blog/javascript-chat-room-tutorial/ but after setting up the basic chat, I wanted to let users define their own name. So I made an input box and then tried using js to take the input box value and assign it to a variable. And then for the name part of the chat application, instead of using the random name function I was using earlier. However, I got the error "can not read properties of null(reading addEventListener) in my console and the submit button did not show up at all. What did I do wrong? The code I used is in pastebin links below. The scaledrone documentation is here: https://www.scaledrone.com/docs/api-clients/javascript Thanks in advance. also, I added the raw text of my javascript file below because stack overflow won't let me post without adding some code(first time posting to stack overflow lol).

https://pastebin.com/9DvF3WnX https://pastebin.com/UrZ1xsMB

const CLIENT_ID = 'keECa1lpVtgABa1F';
const splash=document.querySelector('.splash');
const stuffjs=document.querySelector('.stuff');
var yourname;

/*function createMenuItem(name) {
  let inputname = document.createElement('input');
  inputname.placeholder = name;
  inputname.className='inputnamefield';
  return inputname;
}*/
/*function createButton(btnname){
  let btn = document.createElement('input');
  btn.type = 'submit';
  btn.className='submitbtn';
  return btn;
}*/
const inputnameagain=document.querySelector('.inputnamefield');
const buttoon=document.querySelector('.submitbtn');
buttoon.addEventListener('click',(e) => {
  setTimeout(()=>{
  yourname=inputboxstuff.value()
  },1);
});





/*document.addEventListener('DOMContentLoaded',(e)=>{
  setTimeout(()=>{
    splash.classList.add('display-none');
    
  },2000);
})
splash.addEventListener('mousedown',
(e)=>{
  setTimeout(()=>{
    splash.parentElement.removeChild(splash);
    
  },1);
})*/
 

const drone = new ScaleDrone(CLIENT_ID, {
  data: { // Will be sent out as clientData via events
    name: yourname,
    color: getRandomColor(),
  },
});

let members = [];

drone.on('open', error => {
  if (error) {
    return console.error(error);
  }
  console.log('Successfully connected to Scaledrone');

  const room = drone.subscribe('observable-room');
  room.on('open', error => {
    if (error) {
      return console.error(error);
    }
    console.log('Successfully joined room');
  });

  room.on('members', m => {
    members = m;
    updateMembersDOM();
  });

  room.on('member_join', member => {
    members.push(member);
    updateMembersDOM();
  });

  room.on('member_leave', ({id}) => {
    const index = members.findIndex(member => member.id === id);
    members.splice(index, 1);
    updateMembersDOM();
  });

  room.on('data', (text, member) => {
    if (member) {
      addMessageToListDOM(text, member);
    } else {
      // Message is from server
    }
  });
});

drone.on('close', event => {
  console.log('Connection was closed', event);
});

drone.on('error', error => {
  console.error(error);
});

function getRandomName() {
  const adjs = ["autumn", "hidden", "bitter", "misty", "silent", "empty", "dry", "dark", "summer", "icy", "delicate", "quiet", "white", "cool", "spring", "winter", "patient", "twilight", "dawn", "crimson", "wispy", "weathered", "blue", "billowing", "broken", "cold", "damp", "falling", "frosty", "green", "long", "late", "lingering", "bold", "little", "morning", "muddy", "old", "red", "rough", "still", "small", "sparkling", "throbbing", "shy", "wandering", "withered", "wild", "black", "young", "holy", "solitary", "fragrant", "aged", "snowy", "proud", "floral", "restless", "divine", "polished", "ancient", "purple", "lively", "nameless"];
  const nouns = ["waterfall", "river", "breeze", "moon", "rain", "wind", "sea", "morning", "snow", "lake", "sunset", "pine", "shadow", "leaf", "dawn", "glitter", "forest", "hill", "cloud", "meadow", "sun", "glade", "bird", "brook", "butterfly", "bush", "dew", "dust", "field", "fire", "flower", "firefly", "feather", "grass", "haze", "mountain", "night", "pond", "darkness", "snowflake", "silence", "sound", "sky", "shape", "surf", "thunder", "violet", "water", "wildflower", "wave", "water", "resonance", "sun", "wood", "dream", "cherry", "tree", "fog", "frost", "voice", "paper", "frog", "smoke", "star"];
  return (
    adjs[Math.floor(Math.random() * adjs.length)]  
    "_"  
    nouns[Math.floor(Math.random() * nouns.length)]
  );
}

function getRandomColor() {
  return '#'   Math.floor(Math.random() * 0xFFFFFF).toString(16);
}

//------------- DOM STUFF

const DOM = {
  membersCount: document.querySelector('.members-count'),
  membersList: document.querySelector('.members-list'),
  messages: document.querySelector('.messages'),
  input: document.querySelector('.message-form__input'),
  form: document.querySelector('.message-form'),
};

DOM.form.addEventListener('submit', sendMessage);

function sendMessage() {
  const value = DOM.input.value;
  if (value === '') {
    return;
  }
  DOM.input.value = '';
  drone.publish({
    room: 'observable-room',
    message: value,
  });
}

function createMemberElement(member) {
  const { name, color } = member.clientData;
  const el = document.createElement('div');
  el.appendChild(document.createTextNode(name));
  el.className = 'member';
  el.style.color = color;
  return el;
}

function updateMembersDOM() {
  DOM.membersCount.innerText = `${members.length} users in room:`;
  DOM.membersList.innerHTML = '';
  members.forEach(member =>
    DOM.membersList.appendChild(createMemberElement(member))
  );
}

function createMessageElement(text, member) {
  const el = document.createElement('div');
  el.appendChild(createMemberElement(member));
  el.appendChild(document.createTextNode(text));
  el.className = 'message';
  return el;
}

function addMessageToListDOM(text, member) {
  const el = DOM.messages;
  const wasTop = el.scrollTop === el.scrollHeight - el.clientHeight;
  el.appendChild(createMessageElement(text, member));
  if (wasTop) {
    el.scrollTop = el.scrollHeight - el.clientHeight;
  }
}

CodePudding user response:

The reason why the submit btn didn't show up is that you didn't close the input tag.

<input  name="inputboxstuff"</input>
<input type="submit" ></input>

How to store a input box value in a variable

const inputnamefield = document.querySelector('.inputnamefield');
const button = document.querySelector('.submitbtn');

button.addEventListener('click', (e) => {
   setTimeout(() => {
       const yourname = inputnamefield.value
   }, 1);
})
  •  Tags:  
  • Related