mer*_*art 3 html javascript web2py
I have a free text field in my html page, but I want to fill it with given strings. So lets say I have strings, "apple", "banana" and "pineapple", and now I want to have a button "add content" that opens a modal box, or if it's easier simply a list embedded in my page, that gives me a list where I can select multiple items with the option to enter a quantity for each selected item and adds the selected strings to my text field. for example "3 x apple, 2 x pineapple"
I really appreciate any hint, because I'm clueless how to solve this in javascript / html
It's basically a shopping cart, but I couldn't find anything simple.
小智 7
尝试这个:
var txt = document.getElementById( 'droptxt' ),
content = document.getElementById( 'content' ),
list = document.querySelectorAll( '.content input[type="checkbox"]' ),
quantity = document.querySelectorAll( '.quantity' );
txt.addEventListener( 'click', function() {
content.classList.toggle( 'show' )
} )
// Close the dropdown if the user clicks outside of it
window.onclick = function( e ) {
if ( !e.target.matches( '.list' ) ) {
if ( content.classList.contains( 'show' ) ) content.classList.remove( 'show' )
}
}
list.forEach( function( item, index ) {
item.addEventListener( 'click', function() {
quantity[ index ].type = ( item.checked ) ? 'number' : 'hidden';
calc()
} )
} )
quantity.forEach( function( item ) {
item.addEventListener( 'input', calc )
} )
function calc() {
for ( var i = 0, arr = []; i < list.length; i++ ) {
if ( list[ i ].checked ) arr.push( quantity[ i ].value + ' x ' + list[ i ].value )
}
txt.value = arr.join( ', ' )
}Run Code Online (Sandbox Code Playgroud)
#droptxt {
padding: 8px;
width: 300px;
cursor: pointer;
box-sizing: border-box
}
.dropdown {
position: relative;
display: inline-block
}
.content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 200px;
overflow: auto;
box-shadow: 0 8px 16px 0 rgba(0, 0, 0, .2);
z-index: 1
}
.quantity {
float: right;
width: 40px
}
.content div {
padding: 10px 15px
}
.content div:hover {
background-color: #ddd
}
.show {
display: block
}Run Code Online (Sandbox Code Playgroud)
<p>Click on the below text field:</p>
<div class="dropdown">
<input type="text" id="droptxt" class="list" readonly>
<div id="content" class="content">
<div class="list">
<input type="checkbox" id="apple" class="list" value="Apple" />
<label for="apple" class="list">Apple </label>
<input type="hidden" class="list quantity" min="1" value="1" />
</div>
<div class="list">
<input type="checkbox" id="banana" class="list" value="Banana" />
<label for="banana" class="list">Banana </label>
<input type="hidden" class="list quantity" min="1" value="1" />
</div>
<div class="list">
<input type="checkbox" id="pineapple" class="list" value="Pineapple" />
<label for="pineapple" class="list">Pineapple </label>
<input type="hidden" class="list quantity" min="1" value="1" />
</div>
</div>
</div>Run Code Online (Sandbox Code Playgroud)