簡體   English   中英

從html獲取值並使用javascript更新DOM

[英]Take a value from html and update DOM with javascript

我有一個基本網頁(未連接到服務器),該網頁以某種形式獲取信息並在同一頁面上顯示此信息。 輸入選項之一是復選框,我正在努力在頁面上顯示這些選定的值。 我一直無法破譯我遇到的其他解決方案。 下面有很多文字,但這很基礎。

我需要顯示復選框選擇的結果嗎? 復選框輸入的結果是否保存在數組中?

任何幫助將很有用。

 document.addEventListener('DOMContentLoaded', () => { const newItem = document.querySelector('#new-item'); newItem.addEventListener('submit', handleNewItemForm); }) const handleNewItemForm = function (event) { event.preventDefault(); const whiskyItem = createWhiskyListItem(event.target); const whiskyList = document.querySelector('#drunk-whiskies'); whiskyList.appendChild(whiskyItem); event.target.reset(); } const createWhiskyListItem = function (form) { const whiskyItem = document.createElement('li'); whiskyItem.classList.add('drunk-whiskies-item'); const name = document.createElement('h2'); name.textContent = form.name.value; whiskyItem.appendChild(name); const type = document.createElement('h3'); type.textContent = form.type.value; whiskyItem.appendChild(type); /**** This is the problem area. As above, I am looking to take the values from the form, make this into some text, before appending this to whiskyItem, which is then appended to whiskyList. */ return whiskyItem; } 
 <form id="new-item"> <div id="form-wrapper"> <div class="form-item"> <label for="name" class="primary">Name</label> <input type="text" id="name" required /> </div> <div class="form-item"> <label for="type" class="primary">Type</label> <input type="text" id="type" required /> </div> <div class="form-item"> <label for="flavour" class="primary">What did you taste?</label><br> <input type="checkbox" id="flavourProfile" value="boozy" name="boozy" checked> <label for="boozy">Booze</label> <input type="checkbox" id="flavourProfile" value="malty" name="malty"> <label for="malty">Malt</label> </div> </div> <input type="submit" value="save" /> </form> <h1>You've consumed...</h1> <div id="drunk-whiskies"></div> <ul></ul> 

兩個復選框的ID值都相同,這是不正確的。 分別將ID的值更改為“ flavorProfile1”和'flavorProfile2',然后嘗試以下代碼,它將在<div id='drunk-whiskies'></div>顯示選定的復選框值。

    $("#flavourProfile1").click( function(){
   if( $(this).is(':checked') ) $("#drunk-whiskies").append('Booze');
    });

  $("#flavourProfile2").click( function(){
   if( $(this).is(':checked') ) $("#drunk-whiskies").append('Malt');
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM