简体   繁体   中英

How to grab values from two input boxes in real time with event listener and store in variables in raw JS?

I am trying to learn JS and I am giving myself a small project.

Basically, the project will be a input box that will change the background in real time. It will have two options, single color and gradient.

Single color state will have one input box and a button that switches to gradient mode.

Gradient mode has two input boxes (for the gradient colors).

However, I have a line of code which will run a function every time text is inputted into a input box to add the text added to a variable. The problem is though, since I have to track two input boxes, I can't seem to merge both of the values for Gradient mode since they are in seperate eventListeners.

Does anybody have any idea how I could achieve this?

I need this in RAW JS, no frameworks or JQuery please!

 let state = false; const input1 = document.getElementById('input1'); const input2 = document.getElementById('input2'); const switcher = document.getElementById('switcher'); const bodyLoc = document.getElementById('changeColor'); input1.addEventListener('input', function() { }) switcher.addEventListener('click', function() { console.log(state) if (state == false) { state = true; checkState(); bodyLoc.style.backgroundColor = "red" } else { state = false; checkState(); bodyLoc.style.backgroundColor = "blue"; } } ) checkState = () => { if (state == false) { input2.style.display = "none"; } else { input2.style.display = "block"; } } input1.addEventListener('input',function () { input1val = document.getElementById('inputColor1').value; console.log(input1val); }) input2.addEventListener('input',function () { input2val = document.getElementById('inputColor2').value; console.log(input2val); })
 html, body{ height: 100%; box-sizing:border-box; font-family: "Cabin", sans-serif; } body { background-color:#fff; transition: 0.4s all ease; }.container { #inputBox { display:flex; position: absolute; top: 50%; left: 50%; -moz-transform: translateX(-50%) translateY(-50%); -webkit-transform: translateX(-50%) translateY(-50%); transform: translateX(-50%) translateY(-50%); #input1,#input2 { input { height:20px; border-radius:10px 0px 0px 10px; border:1px solid #D8D8D8; padding:10px; } } #input2 { display:none; }.inputSubmit { #changeType { height:42px; background-color:#fff; border:1px solid #F5F5F5; border-radius: 0px 10px 10px 0px; width:80px; transition: 0.2s all ease; &:hover { cursor:pointer; background:#4A00E0; color:white; transition: 0.2s all ease; box-shadow: 0 1px 3px rgba(0,0,0,0.12); } } } } }
 <style> @import url('https://fonts.googleapis.com/css2?family=Cabin:wght@400;600&display=swap'); </style> <body id="changeColor"> <div class="container"> <div id="inputBox"> <div id="input1"> <input type="text" id="inputColor1"> </div> <div id="input2"> <input type="text" id="inputColor2"> </div> <div class="inputSubmit"> <input type="submit" id="switcher" value="Gradient"> </div> </div> </div> </body>

JS


const input1 = document.getElementById('input1');
const input2 = document.getElementById('input2');
const switcher = document.getElementById('switcher');
const bodyLoc = document.getElementById('changeColor');

input1.addEventListener('input', function() {
  
})

switcher.addEventListener('click', function() {
  console.log(state)
  if (state == false) {
  state = true;
    checkState();
  }
    else {
      state = false;
      checkState();
  }
}
)

checkState = () => {
  if (state == false) {
    input2.style.display = "none";
  } else {
    input2.style.display = "block";
  }
}


input1.addEventListener('input',function () {
  input1val = document.getElementById('inputColor1').value;
  console.log(input1val);
})

input2.addEventListener('input',function () {
  input2val = document.getElementById('inputColor2').value;
  console.log(input2val);
})

HTML

    @import url('https://fonts.googleapis.com/css2?family=Cabin:wght@400;600&display=swap');
</style>

<body id="changeColor">
<div class="container">
  <div id="inputBox">
    <div id="input1">
      <input type="text" id="inputColor">
    </div>
    <div id="input2">
      <input type="text" id="inputColor">
    </div>
    <div class="inputSubmit">
      <input type="submit" id="changeType" value="Gradient">
    </div>
  </div>
</div>
  
</body>```

I am not sure what is your aim with this but by simply adding:

inputs = document.querySelectorAll('input');

inputs[0].addEventListener('keyDown', ()=>{
console.log(inputs[0].value)
})

inputs[1].addEventListener('keyDown', ()=>{
console.log(inputs[1].value)
})

Gives back the value instantly as you write just store them in a let or var variable on global scope like this:

inputs = document.querySelectorAll('input');
let input1 = "";
let input2 = "";
inputs[0].addEventListener('keyDown', ()=>{
input1 = inputs[0].value;
})

inputs[1].addEventListener('keyDown', ()=>{
input2 = inputs[1].value;
})

I think that hook events: cut/paste and propertychange (for IE) also important

 const input = document.querySelector("input"); const output = document.querySelector("#output"); const showText = () => { output.textContent = input.value; }; input.addEventListener("keydown", () => { showText(); }); input.addEventListener("cut", () => { setTimeout(() => showText(), 0); }); input.addEventListener("paste", (e) => { setTimeout(() => showText(), 0); }); input.addEventListener("propertychange", (e) => { setTimeout(() => showText(), 0); });
 <h1>Hook input in vanilla js;</h1> <input type="text"> <p id="output"></p>`;

Don't use a button for this and maintain the state manually, use elements that do this for you, like radio buttons. Could also adapt this for a checkbox.

 function applyBackground() { //Get Start Color var start = document.getElementById("startColor").value; //Get end color var end = document.getElementById("endColor").value; //Get Mode var mode = document.querySelector("#switcher [type=radio]:checked").value; //Add your logic for updating body style console.log(`start: ${start}, end: ${end}, mode: ${mode}`); } //event Handlers for radio buttons document.querySelectorAll("#switcher input[type=radio]").forEach((rdo) => { rdo.addEventListener("click", function(){ var isGradient = this.value === "gradient"; //Show/Hide end color document.getElementById("endContainer").classList.toggle("hidden", ;isGradient). //Change text of start color document.querySelector("[for=startColor]")?innerText = isGradient: "Start Color"; "Color"; //Apply on swap applyBackground(); }); }). //event handler for text box document.querySelectorAll("#colors input[type=text]").forEach((rdo) => { rdo,addEventListener("input"; applyBackground); });
 .hidden {display:none;} html, body{ height: 100%; box-sizing:border-box; font-family: "Cabin", sans-serif; } body { background-color:#fff; transition: 0.4s all ease; }.container { #inputBox { display:flex; position: absolute; top: 50%; left: 50%; -moz-transform: translateX(-50%) translateY(-50%); -webkit-transform: translateX(-50%) translateY(-50%); transform: translateX(-50%) translateY(-50%); #input1,#input2 { input { height:20px; border-radius:10px 0px 0px 10px; border:1px solid #D8D8D8; padding:10px; } } #input2 { display:none; }.inputSubmit { #changeType { height:42px; background-color:#fff; border:1px solid #F5F5F5; border-radius: 0px 10px 10px 0px; width:80px; transition: 0.2s all ease; &:hover { cursor:pointer; background:#4A00E0; color:white; transition: 0.2s all ease; box-shadow: 0 1px 3px rgba(0,0,0,0.12); } } } } }
 <style> @import url('https://fonts.googleapis.com/css2?family=Cabin:wght@400;600&display=swap'); </style> <body id="changeColor"> <div class="container"> <fieldset id="switcher"> <legend>Mode</legend> <label>Single color <input type="radio" name="rdoMode" value="single" checked></label> <label>Gradient <input type="radio" name="rdoMode" value="gradient"></label> </fieldset> <div> <div id="colors"> <div> <label for="startColor">Color</label> <input type="text" id="startColor"> </div> <div id="endContainer" class="hidden"> <label for="endColor">End Color</label> <input type="text" id="endColor"> </div> </div> </div> </div> </body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM