【问题标题】:How to limit number in input tag of html through Javascript?如何通过Javascript限制html输入标签中的数量?
【发布时间】:2021-05-02 14:21:48
【问题描述】:

您好,我正在做一个报价网站项目。要清楚地理解问题,请参阅我的 html、css 和 Javascript。

我的 HTML

<html>
<head>
<style>/* Main Status */

.pagable {
  display: flex;
  flex-direction: column;
  border: var(--pageable-border);
  background: var(--pageable-background);
}
.status-copy-alert {
 position: relative;
 background-color: #18b495;
 color: #ffffff;
 padding: 10px 10px;
 border-radius: 5px;
 left: 8px;
 text-transform: uppercase;
 letter-spacing: 0.05em;
 font-weight: 500;
 visibility: hidden;
}
.status-copy-alert:before{
 content:"";
 position: absolute;
 height: 10px;
 width: 10px;
 background-color: #18b495;
 left: -5px;
 transform: rotate(45deg);
 top: 39%;
}

.pagable .pagable-results {
  display: flex;
  flex-direction: column;
  flex: 1;
  padding: 0.25em;
}

.pagable .pagable-status {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding: 0.25em;
  background: var(--pageable-status-background);
}

.pagable .pagable-actions {
  display: grid;
  grid-auto-flow: column;
  grid-gap: 0.25em;
}
.pagable .pagable-actions input[name="page-curr"] {
  width: 3em;
}
.status-copy-alert {

 position: relative;

 background-color: #18b495;

 color: #ffffff;

 padding: 10px 10px;

 border-radius: 5px;

 left: -42px;

 text-transform: uppercase;

 letter-spacing: 0.05em;

 font-weight: 500;

 visibility: visible;
  
 opacity: 0;
  
 transition: left 0.4s, opacity 0.4s;

}

.animatedClass {
    left: 20px;
    opacity: 1;
}

.status-copy-alert:before{

 content:"";

 position: absolute;

 height: 10px;

 width: 10px;

 background-color: #18b495;

 left: -5px;

 transform: rotate(45deg);

 top: 39%;

}
</style>
</head>
<body>
    <a href="hindinj.html">caeman</a>
<div class="mainStatus">
   <h2 class="statusHeading">Latest English Status</h2>
<div class="allquotes"></div>
<div class="pagable-status">
  <label>Page <span class="page-no-curr"></span> of <span class="page-no-count"></span></label>
  <div class="pagination">
    <button class="page-btn-prev btn">PRE</button>
<span class="manho">1</span>
    <button class="page-btn-next btn">NEXT</button>
  </div>
      
 <input name="current-page" class="value-page" type="number" value="1" min="1">
<button class="jump-btn">Go</button>
</div>
</body>
</html>

我的 Javascript

const resultEl = document.querySelector('.allquotes');
const pageCurr = document.querySelector('.manho')
const pageNoCurr = document.querySelector('.page-no-curr');
const pageNoCount = document.querySelector('.page-no-count')
const btnPrev = document.querySelector('.page-btn-prev');
const btnNext = document.querySelector('.page-btn-next');

let results = [];

const getResultCount = () => results.length;
const getPageSize = () => 12;
const getCurrPage = () => +pageCurr.innerText;
const getPageCount = () => Math.ceil(getResultCount() / getPageSize());

const pageResponse = (records, pageSize, page) =>
  (start => records.slice(start, Math.min(records.length, start + pageSize)))
  (pageSize * (page - 1));

const btnJump =  document.querySelector('.jump-btn');
const pageValue =  document.querySelector('.value-page');

const main = async() => {
  btnPrev.addEventListener('click', navPrev);
  btnNext.addEventListener('click', navNext);
  btnJump.addEventListener('click', navJump);

  results = await retrieveAllQuotes();
  updatePager(results);
  redraw();
};
const redraw = () => {
  resultEl.innerHTML = '';
  const paged = pageResponse(results, getPageSize(), getCurrPage());
  const contents = document.createElement('div');
  contents.classList.add("allStatus");
  const quotes = paged.map((record) => `<div class='latestatus'><p class='copytxt'>${record.quotes}</p><div> <button class="copystatus btn">Copy</button><span class="status-copy-alert hidden" id="status-copy-alert">Copied!</span></div></div>`);
  const quoteGroupNumer = Math.ceil(quotes.length / 2);
  const groups = Array(quoteGroupNumer).fill('').map((value, index) => {
    const groupQuoteFirst = quotes[2 * index]; // 0, 2, 4, 6
    const groupQuoteSecond = quotes[2 * index + 1] || ''; // 1, 3, 5, 7

    return `<div class="flex">${groupQuoteFirst}${groupQuoteSecond}</div>`;
  });

  contents.innerHTML = groups.join('');
  resultEl.append(contents);
};

const navPrev = (e) => {
  const pages = getPageCount();
  const curr = getCurrPage();
  const prevPage = curr > 1 ? curr - 1 : curr;
  pageCurr.innerText = prevPage;
  pageNoCurr.textContent = prevPage;
  redraw();
}

const navNext = (e) => {
  const pages = getPageCount();
  const curr = getCurrPage();
  const nextPage = curr < pages ? curr + 1 : curr;
  pageCurr.innerText = nextPage;
  pageNoCurr.textContent = nextPage;
  redraw();
}

const navJump = (e) => {
  const pages = getPageCount();
  const curr = getCurrPage();  
  pageCurr.innerText = pageValue.value;
  pageNoCurr.textContent = pageValue.value;
  redraw();
}

const updatePager = () => {
  const count = getPageCount();
  const curr = getCurrPage();
  pageCurr.innerText = curr > count ? 1 : curr;
  pageNoCurr.textContent = curr > count ? 1 : curr;
  pageNoCount.textContent = count;
};

const retrieveAllQuotes = async function() {
  return[{
      quotes: "1The cat is better than dog."
    },
    {
      quotes: "2Google is a open source library."
    },
    {
      quotes: "3Cats are better than ferrets."
    },
    {
      quotes: "4Love books."
    },
    {
      quotes: "5Life is short make it possible."
    },
    {
      quotes: "6The cat is better than dog"
    },
    {
      quotes: "7Google is a open source library."
    },
    {
      quotes: "8Cats are better than ferrets."
    },
    {
      quotes: "9Love books."
    },
    {
      quotes: "10Life is short make it possible."
    },
    {
      quotes: "1The cat is better than dog."
    },
    {
      quotes: "2Google is a open source library."
    },
    {
      quotes: "3Cats are better than ferrets."
    },
    {
      quotes: "4Love books."
    },
    {
      quotes: "5Life is short make it possible."
    },
    {
      quotes: "6The cat is better than dog"
    },
    {
      quotes: "7Google is a open source library."
    },
    {
      quotes: "8Cats are better than ferrets."
    },
    {
      quotes: "9Love books."
    },
    {
      quotes: "10Life is short make it possible."
    },
    {
      quotes: "1The cat is better than dog."
    },
    {
      quotes: "2Google is a open source library."
    },
    {
      quotes: "3Cats are better than ferrets."
    },
    {
      quotes: "4Love books."
    },
    {
      quotes: "5Life is short make it possible."
    },
    {
      quotes: "6The cat is better than dog"
    },
    {
      quotes: "7Google is a open source library."
    },
    {
      quotes: "8Cats are better than ferrets."
    },
    {
      quotes: "9Love books."
    },
    {
      quotes: "10Life is short make it possible."
    },
{
      quotes: "1The cat is better than dog."
    },
    {
      quotes: "2Google is a open source library."
    },
    {
      quotes: "3Cats are better than ferrets."
    },
    {
      quotes: "4Love books."
    },
    {
      quotes: "5Life is short make it possible."
    },
    {
      quotes: "6The cat is better than dog"
    },
    {
      quotes: "7Google is a open source library."
    },
    {
      quotes: "8Cats are better than ferrets."
    },
    {
      quotes: "9Love books."
    },
    {
      quotes: "10Life is short make it possible."
    },
]; 
}
document.querySelector('.allquotes').addEventListener(

  'click',

  function (e) {

    e.preventDefault();
    

    if (e.target && e.target.matches('.copystatus')) {

        const quote = e.target.parentNode.closest('.latestatus')

            .childNodes[0].textContent;
      
      const notify = e.target.nextSibling.closest('.status-copy-alert');
      notify.classList.add('animatedClass')
        setTimeout(() => {
            notify.classList.remove('animatedClass')
        }, 1000);

        const textArea = document.createElement('textarea');

        textArea.value = quote;

        document.body.appendChild(textArea);

        textArea.select();

        document.execCommand('Copy');

        textArea.remove();

    }

  },

  false

);
main();

运行上面的代码。您会看到一些具有出色分页的引文。在页面底部,您可以看到一个输入标签和一个 Go 按钮。此输入和按钮用于从一页跳转到另一页。在此上方您可以看到第 1 页,共 4 页,它表明有多少页。

现在让我们将 Page 1 of 4 视为 Page 1 of Y。请记住,当我在 JavaScript 中添加更多引号时,数字 4 会逐渐改变。

现在我的问题是底部的输入标签。我需要将其限制为 Y,因为每次添加引号时 Y 值都可能会发生变化。有什么办法可以让如果用户输入的数字高于值 Y 它应该被替换为值 Y,如果用户输入低于 1 它应该被替换为 1

我尝试了不同的方法来解决这个问题,但它们都不起作用,而且我是 Javascript 的新手。

非常感谢回答这个问题的人。

【问题讨论】:

    标签: javascript html scripting pagination


    【解决方案1】:

    您可以使用 min 和 max 属性限制输入标签可以采用的可能值的数量。但此限制仅适用于用户使用输入的控制按钮而不是键入数字时。 要控制用户类型,您必须使用 Javascript,如下面的 sn-p 所示。此外,当用户按下 go 按钮时,您必须检查输入标签是否有值或为空。 当最大值发生变化时(例如从 10 到 20),您还必须使用此命令 document.querySelector("input").max = 20;

    更改输入标签的 max 属性

    document.querySelector("input").oninput = (e) => {
        let input = e.target;
        if (input.value != "") { //otherwise the user cannot delete the current value
          let value = parseInt(input.value); 
          if (value > parseInt(input.max)) input.value = input.max;
          else if (value < parseInt(input.min)) input.value = input.min;
        }
    }
    <input type="number" value="1" min="1" max="10">
    <button class="jump-btn">Go</button>

    【讨论】:

    • 有什么办法可以避免每次在我的网站上添加引号时都更改最大值。
    • 如果您不更改最大值,每次用户可以使用数字输入标签具有的控件添加超出范围的值。 javascript 代码仅控制用户尝试键入数字而不是使用微调器更改值时的情况。这由 html 以及 min 和 max 属性控制。
    • 有什么办法让最大值等于pageNoCount(在JavaScript中)
    • 是的。您可以在pageNoCount.textContent = count; 之后添加updatePager 以下命令:pageValue.max = count;。因此,每次更新寻呼机时,输入的最大值都会得到新计数的值。
    • 另外,你为什么使用const getPageSize = () =&gt; 12;而不是const getPageSize = 12;?有什么理由这样做吗?您可以使用简单的变量代替函数。
    猜你喜欢
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 1970-01-01
    • 2015-12-02
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多