如何从输入字段获取数字值进入Bootstrap模式?

时间:2019-04-09 20:56:29

标签: javascript html

这应该是一件微不足道的任务,但是由于某些原因,我无法将输入字段中的值传递/获取到Boostrap 4模态中。当我使用以下代码时,它会显示所有信息,但会显示输入this.qtyAskValue = document.querySelector("#qtyAsk").value.trim()的值。知道我的JS代码有什么问题吗?我正在尝试使用普通香草JS解决问题。

HTML

<input type="number" id="qtyAsk" name="qtyAsk" placeholder="0">
<button type="button" id="buyTicket" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter">Buy</button>

JavaScript

const buyTicket = document.querySelector("#buyTicket")
buyTicket.addEventListener("click", getModalInfo)

class UI {
  constructor() {
    this.show = document.querySelector("#modalContent")
    this.qtyAskValue = document.querySelector("#qtyAsk").value.trim()
  }
  showData() {
    this.show.innerHTML = `<div class="modal-header">
      <h5 class="modal-title" id="exampleModalCenterTitle">Modal title</h5>
      <button type="button" class="close" data-dismiss="modal" aria-label="Close">
        <span aria-hidden="true">&times;</span>
      </button>
      </div>
      <div class="modal-body">
      <p>You are placing an order for ${this.qtyAskValue} shares</p>
      </div>
      <div class="modal-footer">
      <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      <button type="button" class="btn btn-primary">Save changes</button>
      </div>`
  }
}
const ui = new UI()

function getModalInfo() {
  ui.showData()
}

解决方案-JavaScript 按照@Chris G-这里的主要问题是构造函数在用户选择值之前运行了很长时间。像this.qtyAskValue = document.querySelector("#qtyAsk").value.trim()这样的语句不会扩展到将来。它会在被调用时运行一次,然后再次运行,除非您再次调用它。因此this.qtyAskValue将保持""(因为这是初始值)。

const buyTicket = document.querySelector("#buyTicket")

buyTicket.addEventListener("click", getModalInfo)

class UI {
  constructor() {
    this.show = document.querySelector("#modalContent")
  }
  showData() {
    const qtyAskValue = document.querySelector("#qtyAsk").value.trim()

    this.show.innerHTML = `<div class="modal-header">
      <h5 class="modal-title" id="exampleModalCenterTitle">Modal title</h5>
      <button type="button" class="close" data-dismiss="modal" aria-label="Close">
        <span aria-hidden="true">&times;</span>
      </button>
      </div>
      <div class="modal-body">
      <p>You are placing an order for ${qtyAskValue} shares of  at</p>
      </div>
      <div class="modal-footer">
      <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      <button type="button" class="btn btn-primary">Save changes</button>
      </div>`
  }
}
const ui = new UI()

function getModalInfo() {
  ui.showData()
}

0 个答案:

没有答案