multiselect list with quantity option for each item - javascript

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.

Try this:
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( ', ' )
}
#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
}
<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>

Related

Add fileupload input fields inside multiple div at a same time according to radiobox selection

I have a input field that takes numeric inputs. Then i have a button which display the number of divs as per that input. after displaying div there is two radio-box buttons (paired end and single end) if I select paired end then i want two file upload fields in each divs. and if i select single end then i want only one file upload fields in each div.
I have tried but fileupload fields working on only first div.
function CreateText() {
var text = `<div class="row border-top py-3">
<div class="col-md-3">
<label">sample name *</label></br>
<input type="sample" id="sample" name="sample[]">
</div>
<div class="col-md-3" style="display:none" id="showsingle">
<div class="form-group">
<label for="form_upload">Upload file *</label></br>
<input type="file" id="myFile" name="filename1[]">
</div>
</div>
<div class="col-md-3" style="display:none" id="showpair">
<div class="form-group">
<label for="form_upload">Upload file *</label></br>
<input type="file" id="myFile" name="filename2[]">
<label for="form_upload">Upload file *</label></br>
<input type="file" id="myFile" name="filename2[]">
</div>
</div>
<div class="col-md-3 d-grid">
<div class="form-group">
<button class="btn btn-danger remove_add_btn">Remove</button>
</div>
</div>
</div>`;
var textCount = document.getElementById('textInput').value;
var html = '';
for (var i = 0; i < $('#textInput').val(); i++) {
html = document.getElementById('divDynamicTexts').innerHTML;
document.getElementById('divDynamicTexts').innerHTML = html + text.replace('', i);
}
}
function onlyOne() {
let SradioBox = document.getElementById("singleradio"),
Sfileupload = document.getElementById("showsingle"),
PradioBox = document.getElementById("pairedradio"),
Pfileupload = document.getElementById("showpair");
if (SradioBox.checked == true) {
Sfileupload.style.display = "block",
Pfileupload.style.display = "none";
} else if (PradioBox.checked == true) {
Pfileupload.style.display = "block",
Sfileupload.style.display = "none";
} else {
Pfileupload.style.display = "none",
Sfileupload.style.display = "none";
}
};
$(document).ready(function() {
$(document).on('click', '.remove_add_btn', function(e) {
e.preventDefault();
let row_item = $(this).parent().parent().parent();
$(row_item).remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="text-center">
<input type="text" id="textInput" value="" />
<input type="button" id="" value="Create upload fields" onclick="CreateText();" />
<div class="col-md-4" id="filebutton">
<div class="form-group ">
<label for="form_need">Library Type *</label>
</br>
<div class="px-2">
<label for="myradio">Single end:</label>
<input type="radio" id="singleradio" name="check" onclick="onlyOne();">
<label for="myradio">Paired end:</label>
<input type="radio" id="pairedradio" name="check" onclick="onlyOne();">
</div>
</div>
</div>
</div>
<div id="divDynamicTexts"></div>
ID attributes must be unique. It would be better to remove the IDs altogether ( or change to dataset attributes perhaps ) and use a delegated event listener to process the various clicks related to the task of adding/removing dynamic elements.
In the code below all ID attributes were either removed entirely or changed to data-id type values.
To avoid the need to process different form file input fields at the server the file-input fields are named the same but have an index so can be identified more readily in PHP ( or whatever backend you have )
The delegated listener, because it is bound to the document, will work for all elements whether or not they are static or added dynamically and makes heavy use of the event.target property to help identify the element that invoked the event.
The label element was being used incorrectly previously. If the form-input is within the label then there is no need for the for="ID" syntax ( note that the ID should be the ID of the input element to which the label belongs! ) - as it was the label's appeared to have a for attribute which did not related to an element in the form!
Using querySelector and querySelectorAll you can easily identify nodes of interest within the DOM so button clicks or radio button selection can fire a query to find nodes that are relevant - thus simplifying the hiding/showing of the file input elements.
const strhtml = `
<div data-id="dynrow" class="row border-top py-3">
<div class="col-md-3">
<label>sample name *<input type="text" name="sample[]"></label>
</div>
<div class="col-md-3" style="display:none" data-id="single" data-role="file-field">
<div class="form-group">
<label>Upload file *<input type="file" name="filename[1]" /></label>
</div>
</div>
<div class="col-md-3" style="display:none" data-id="pair" data-role="file-field">
<div class="form-group ">
<label>Upload file *<input type="file" name="filename[1]" /></label>
<label>Upload file *<input type="file" name="filename[2]" /></label>
</div>
</div>
<div class="col-md-3 d-grid">
<div class="form-group">
<button class="btn btn-danger remove_add_btn" data-id='remove'>Remove</button>
</div>
</div>
</div>`;
const _radio = document.querySelectorAll('[type="radio"][data-id]');
const _bttn = document.querySelector('[type="button"][data-id="add"]');
const _div = document.querySelector('#divDynamicTexts');
const _input = document.querySelector('input[type="number"][data-id="textInput"]');
let choice = false;
let qty = false;
/*
Disable radio buttons and the "Create" button initially
and enable when changes are made in the correct sequence.
1: select quantity -> enable radio bttns
2: select single or double -> enable "create" bttn
3: click bttn, create as per radio selection
*/
_input.addEventListener('change', e => {
_radio.forEach(n => {
n.disabled = e.target.value > 0 ? false : true;
});
qty=e.target.value;
});
document.addEventListener('click', e => {
if (e.target instanceof HTMLInputElement && e.target.dataset.id != null) {
/*
set global "choice" variable
and enable "Create" bttn.
*/
if (e.target.type == 'radio') {
choice = e.target.dataset.id;
_bttn.disabled = false;
}
}
/*
If the "choice" has been made the radio
buttons will be enabled. Based on radio
button selected create new HTML and then
unhide the appropriate single/pair DIV
element
*/
if (choice && qty > 0 && e.target.type == 'button') {
_div.innerHTML = '';
for (let i = 0; i < qty; i++) _div.insertAdjacentHTML('afterbegin', strhtml);
let expr = `div[data-id="${choice}"]`;
document.querySelectorAll(expr).forEach(n => n.style.display = 'block');
}
/*
unchanged: delete DIV & contents when "Remove" bttn is clicked.
*/
if (e.target instanceof HTMLButtonElement && e.target.dataset.id != null) {
if (e.target.dataset.id == 'remove') {
_div.removeChild(e.target.closest('[data-id="dynrow"]'));
}
}
});
body {
font-family: arial;
}
label {
display: block;
}
.px-2 {
display: inline-block;
}
.px-2 label {
display: inline-block;
margin: 0.5rem;
}
h2 {
font-size: 1.1rem;
margin: 1rem 0 0 0;
display: inline-block;
width: auto;
}
.inline {
display: inline;
margin: 0 1rem 0 0;
}
#divDynamicTexts {
min-height: 1rem;
margin: 2rem auto
}
div.row {
padding: 0.5rem;
border: 1px dotted grey;
margin: 0.5rem;
}
div[data-id='single'] .form-group label {
background: aliceblue
}
div[data-id='pair'] .form-group label {
background: lightsteelblue
}
div[data-id] .form-group label {
outline: 1px solid grey;
padding: 0.5rem;
margin: 0.5rem 0
}
.bold {
font-weight: bold
}
[disabled]{
border:1px solid red;
outline:2px solid red;
background:rgba(255,0,0,0.25);
}
<div class='text-center'>
<label class='inline bold'>Quantity:<input type='number' data-id='textInput' /></label>
<div class='col-md-4'>
<div class='form-group'>
<h2>Library Type</h2>
<div class='px-2'>
<label>Single end: <input type='radio' data-id='single' name='check' disabled /></label>
<label>Paired end: <input type='radio' data-id='pair' name='check' disabled /></label>
</div>
</div>
</div>
<input type='button' data-id='add' value='Create upload fields' disabled />
</div>
<div id='divDynamicTexts'></div>

How to reset an input type=number element when the user clicks it using JavaScript

I'm experimenting with the <input type="number" ...> list option to create a numeric input field that displays a set of predefined 'favorite' values, but still allow other values to be typed in by the user.
Here is what I have, so far:
<label>
Zoom(%)
<input type="number"
min="50" step="50" value="100"
list="favorites"
title="Please enter or choose a zoom value." />
<datalist id="favorites">
<option value="100" />
<option value="150" />
<option value="200" />
<option value="250" />
<option value="300" />
</datalist>
</label>
Problems:
There are two problems:
After the first time selecting/entering a value and exiting the field, the next time the field had the focus, the drop-down list only shows some of options that sort of match the current input value, and
The input element must be cleared and clicked twice in order to display the full list of options.
Goal:
How do I get the full list of options to show everytime the drop-down list shows?
I tried adding an inline onclick="this.value = '';" code segment to the input element in order to reset the input element each time the user clicks the input element, but while sometimes this seems to work, it doesn't always work, even in the same browser, so this isn't a cross-browser issue.
Is there a way to reset an input element, like a form reset does, without actually using an enclosing form element?
My issue about using a form is that when I'm using a form element to enclose the input field and reset the parent form, I can't nest forms to isolate just the one input element and resetting the parent form resets all of the input elements, which I don't want.
Here is a CodePen examples showing my test case and others.
The last example in the CodePen example shows an alternate to the input type number, but without the list attribute. This separates the list feature from the input element so that the drop-down-list doesn't show until the user presses the down-triangle list button, next to the input element. When before the list actually displays, the options in the list are filters with anything that the user may have typed into the input field and supports partial matches. The initial/default value of the input field is not used as a filter, so that the whole list is displayed until something is typed into the field or after the clear button is clicked.
Here is an example that combines a number input and a down-list to achieve a better solution than using the number input with its data list option.
div {
display: inline-block;
vertical-align: top;
padding-right: 10px;
}
span.h {
font-weight: 900;
font-size: x-large;
}
button.blacktriangledown {
position: relative;
top: -1px;
margin-left: -5px;
padding: 0;
height: 21px;
width: 20px;
outline: none;
}
button.blacktriangledown > div {
position: relative;
top: -7px;
left: -3px;
font-size: 26px;
}
button.times {
outline: none;
padding: 0;
height: 20px;
width: 20px;
}
button.times > div {
position: relative;
top: -8px;
font-size: 26px;
}
datalist {
display: none;
position: absolute;
top: 20px;
left: 0px;
border: thin solid black;
background-color: white;
cursor: pointer;
}
datalist > option:hover {
border: thin solid black;
background-color: lightskyblue;
}
<div>
<p>
<span class="h">Input-7</span><br />
<b><u>with</u> an inline reset inline code segment and list and clear buttons</b>
</p>
<label>
Zoom(%)
<div style="position: relative;">
<input type="number" id="input7" min="50" step="50" filter="" value="100"
datalist="favorites7"
title="Please enter or choose a zoom value."
oninput="this.setAttribute( 'filter', this.value );" />
<button class="blacktriangledown" onclick="listButton( this );">
<div>&blacktriangledown;</div>
</button>
<button class="times" onclick="clearButton( this );">
<div>×</div>
</button>
<script>
function listButton( This ) {
var input = This.parentElement.querySelector( 'input' );
var filter = input.getAttribute( 'filter' );
var value = input.value;
var list = This.parentElement.querySelector( 'datalist' );
var options = list.options;
var option;
for( var i = 0, l = options.length; i < l; ++i ) {
option = options[ i ];
option.style.backgroundColor = ( ( option.value === value )
? 'lightblue'
: 'inherit' );
if( filter !== '' )
option.hidden = ( option.value.indexOf( filter ) === -1 );
}
list.style.display = ( ( list.style.display === 'inline' )
? 'none'
: 'inline' );
}
function clearButton( This ) {
var input = This.parentElement.querySelector( 'input' );
var list = This.parentElement.querySelector( 'datalist' );
var options = list.options;
list.style.display = 'none';
for( var i = 0, l = options.length; i < l; ++i )
options[ i ].hidden = false;
input.setAttribute( 'filter', '' );
input.value = input.defaultValue;
input.focus();
}
</script>
<datalist id="favorites7">
<option value="50">50% (half-size)</option>
<option value="100">100% (full-size)</option>
<option value="150">150%</option>
<option value="200">200%</option>
<option value="250">250%</option>
<option value="300">300%</option>
</datalist>
<script>
( function() {
var lists = document.querySelectorAll( 'datalist' );
var list = lists[ lists.length - 1 ];
var options = list.options;
list.value =
list.selectedOption = null;
list.selectedIndex = -1;
list.length = list.length;
for( var i = 0, l = options.length; i < l; ++i ) {
options[ i ].index = i;
options[ i ]
.addEventListener( 'click',
function() {
var list = this.parentElement;
list.style.display = 'none';
list.value = this.value;
list.selectedOption = this;
list.selectedIndex = this.index;
list.parentElement
.querySelector( 'input' )
.value = this.value ;
} );
}
} )();
</script>
</div>
</label><br />
<span id="span7"></span>
</div>

jQuery issue for deleting input field

I'm trying to add an input field when clicking on add, and it should be removed when clicking on delete click.
Here is JS Bin link:
JS issue with deletion
var newTextBoxDiv;
var rowCount = 0;
var counter = 1;
var delCounter = 1;
$(document).ready(function() {
$(document).on('focus', '.txtFocus', function() {
$(this).next('.clearContent').hide()
});
$(document).on('focusout', '.txtFocus', function() {
$('.clearContent').show()
})
});
function addTags(obj) {
var newTextBoxDiv = '<div class="col-md-4 TextBoxMainDiv"><div style=""><div class="input-group" id="" style="width: 40%;margin: 0;padding: 0;padding: 2px;float:left;width:80%;"><input type="text" name="textbox' + counter + '" id="textbox' + counter + '" value="" class="txtFocus" required placeholder="Add Tag" autocomplete="false" style="width: 100%" ><span class="clearContent"><i class="fas fa-times"></i></span> </div><div style="width: 15%;display: inline-block;text-align:right;"><span id="addMore" onClick="addTags(this);"><i class="fas fa-plus-square"></i></span></div></div></div>';
$(obj).hide();
$("#tagElement").append(newTextBoxDiv);
$('.txtFocus').focus();
counter++;
if (counter == 1) {
$(obj).show()
}
}
function deleteTag(obj) {
$(obj).closest('.TextBoxMainDiv').last().find('#addMore').show();
$(obj).closest('.TextBoxMainDiv').last().find('#addMore').css('display', 'block');
$(obj).closest('.TextBoxMainDiv').remove();
counter--;
if (counter == 1) {
$('#addMore').show()
}
}
<div class="row">
<div id="tagElement">
<div> </div>
<div class="col-md-4 TextBoxMainDiv">
<div style="">
<div class="input-group" id="" style="width: 40%;margin: 0;padding: 0;padding: 2px;float:left;width:80%;">
<input type="text" class="txtFocus" required placeholder="Add Tag" id="textBox" autocomplete="false" autofocus="autofocus" style="width: 100%">
<span class="clearContent">
Add
</span>
</div>
<div style="width: 15%;display: inline-block;text-align:right;">
<span id="addMore" onClick="addTags(this);">
cancel
</span>
</div>
</div>
</div>
</div>
</div>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
I manage to add the input fields properly, but have issues deleting them. They seem to be deleted randomly.
I think the add and delete button are mixed up, but I couldn't spend time on analysing the code because it's too much code for something that does very little. The following demo:
has a single button that adds a row of form controls:
a checkbox
a text input
a button that deletes it's own row as well as itself.
Demo
var index = 0;
var template = `
<figure class='frame'><input class='status' type='checkbox'><label class='tag'></label><input class='text' type='text' placeholder='Enter New Task'><button class='del' type='button'>➖</button></figure>`;
$('.set').on('click', 'button', function(e) {
if ($(this).hasClass('add')) {
index++;
$('.set').prepend(template);
$('.status:eq(0)').attr('id', 'chx' + index);
$('.tag:eq(0)').attr('for', 'chx' + index);
} else {
$(this).prevUntil('.del, .add').add(this).remove();
}
});
.set {
position: relative;
padding: 2px 0 1px 2px;
min-height: 28px;
border-radius:7px;
}
.frame {
padding: 0;
margin: 0;
min-width:90vw;
}
.add {
position: absolute;
right: 6px;
top: 3px;
display:block;
}
.status {
display: none
}
.tag {
display: inline-table;
font-size: 28px;
line-height: 1;
vertical-align: middle
}
.tag::before {
content: '\2610';
}
.status:checked+.tag::before {
content: '\2611'
}
.text {
display:inline-table;
width: 75%;
margin: 2px 5px 0
}
<form id='ui'>
<fieldset class='set'>
<figure class='frame'>
<input id='chx0' class='status' type='checkbox'>
<label for='chx0' class='tag'></label>
<input class='text' type='text' placeholder='Enter New Task' style='margin:2.5px 2px 0 0' autofocus>
<button class='del' type='button'>➖</button>
</figure>
<button class='add' type='button'>➕</button>
</fieldset>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I think your code's logic is working, however, the icon for addition and deletion of inputs is not being rendered.
You can replace your newTextBoxDiv with this:
var newTextBoxDiv = `
<div class="col-md-4 TextBoxMainDiv">
<div style="">
<div class="input-group" id="" style="width: 40%;margin: 0;padding: 0;padding: 2px; float:left; width:80%;">
<input type="text" name="textbox${counter}" id="textbox${counter}" value="" class="txtFocus" required placeholder="Add Tag" autocomplete="false" style="width: 100%" >
<span class="clearContent">
Delete<i class="fas fa-times"></i>
</span>
</div>
<div style="width: 15%;display: inline-block;text-align:right;">
<span id="addMore" onClick="addTags(this);">
Add
</span>
</div>
</div>`;
Notice that I added the word "Add" and "Delete" between the tags, so that you have something to click on
Also, I think you need to swap the word "Add" and "Cancel" in the initial HTML to convey a clearer message, as they are now doing the opposite thing.
Another fix that's needed is to replace the id="addMore" with class="addMore"
<span class="addMore" onClick="addTags(this);">
Since id is meant to be unique. In your code, however, when you append new element, you added new elements with duplicate id, making jquery's selector not selecting the element you want.
After replacing id with class, you also need to change the deleteTag function to select the last "addMore" span and show it.
function deleteTag(obj) {
$(obj).closest('.TextBoxMainDiv').last().find('.addMore').show();
$(obj).closest('.TextBoxMainDiv').last().find('.addMore').css('display', 'block');
$(obj).closest('.TextBoxMainDiv').remove();
counter--;
$('.addMore').last().show();
}
For the layout, you need to do it with css, removing float and setting the div tag with appropriate width and display: inline-block. I suggest you use a separate css file to style the elements instead of doing it inline.
function deleteTodo() {
$(this).parent().remove();
}
function addTodo() {
var inputTemplate =
'<div class="todo-input-wrapper">' +
'<input class="todo-input" type="text" placeholder="Add Tag" />' +
'<button class="delete-button">Delete</button>' +
'</div>';
$('.todo-wrapper').append(inputTemplate);
$('.delete-button').last().on('click', deleteTodo);
$('.todo-input').last().focus();
}
$(document).ready(function () {
$('.delete-button').on('click', deleteTodo);
$('.add-button').on('click', addTodo);
});
.todo-wrapper {
display: inline-block;
width: max-content;
font-size: 0;
}
.todo-input-wrapper {
margin: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="todo-wrapper">
<div class="todo-input-wrapper">
<input class="todo-input" type="text" placeholder="Add Tag" />
<button class="delete-button">Delete</button>
</div>
</div>
<button class="add-button">Add</button>

Form validation, normal button, red box and clean data

I have a popup form and I have to validate fields in this form before I close this popup, I need to use this validation with a normal button, not a submit, if the fields are emty I need to mark these on a red box and put the 'This field is empty' after. After I close the form I need to clean up data from form. How should I do this using jQuery and Javascript?
<form id="frmUsers" data-userid="">
<img id="btnClose" src="resources/img/close_window.png">
<h2 id="popupTitle"></h2>
<ul>
<li>
<label for="username">Username:</label>
<input type="text" id="username" name="txtUsername" placeholder="Please select username" class="required"/>
<p></p>
</li>
<li>
<label for="level">Level:</label>
<input type="number" id="level" name="txtLevel" placeholder="Please select level"/>
<p></p>
</li>
<li>
<label for="registrationStatus">RegistrationStatus:</label>
<select name="txtRegistrationStatus" id="registrationStatus"
placeholder="Please select registration status">
<option value="Registered">Registered</option>
<option value="Unregistered">Unregistered</option>
</select>
<p></p>
</li>
<li>
<label for="registrationDate">RegistrationDate:</label>
<input type="text" id="registrationDate" name="txtRegistrationDate"
placeholder="Please select date"/>
<p></p>
</li>
<div class="btnZone">
<input class="btnDown" type="button" value=" " id="btnPopup" />
<input class="btnDown" type="button" value="Cancel" id="btnCancel"/>
</div>
</ul>
</form>
And my form validation function:
function validateForm() {
var txtUsername = $("#username").val();
if(txtUsername == ""){
("#username").css("border-color", "red");
}
// $(":input").each(function () {
// if ($(this).val() == "") {
// $(this).css("border-color", "red");
// // $("p").html("This field is empty");
// // $("input").val("This field is required");
// // alert($(this).attr("id") & " validate error");
// }else{
// $(this).css("border-color", "black");
// }
//
// });
}
You can use one of many popup/modal plugins, but if you want to create your own, than you should do something similar to this:
var txtUsername = $("#username");
function validateForm() {
txtUsernameValid = $.trim(txtUsername.val());
txtUsername.toggleClass('invalid-input', !txtUsernameValid);
return txtUsernameValid;
};
$('[data-popup]').each(function(i) {
var thisButton = $(this);
var toPopup = $(thisButton.data('popup'));
toPopup.wrap('<div class="popup-container"><div class="popup-content"></div></div>');
var popupContainer = toPopup.closest('.popup-container').hide();
popupContainer.find('.popup-content').append('<span class="popup-close">X</span>')
thisButton.on('click', function(e) {
e.preventDefault();
popupContainer.show();
});
popupContainer.find('.popup-close').on('click', function(e) {
popupContainer.hide();
});
popupContainer.find('#btnSave').on('click', function(e) {
/* Save your data, than reset the form */
if( validateForm() ) {
popupContainer.find('form')[0].reset();
popupContainer.hide();
};
});
popupContainer.find('#btnCancel').on('click', function(e) {
popupContainer.find('form')[0].reset();
popupContainer.hide();
});
});
body {
font-family: sans-serif;
}
.popup-container {
background: none rgba(0, 0, 0, .5);
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%;
text-align: center;
}
.popup-container::before {
content: "";
display: inline-block;
height: 100%;
vertical-align: middle;
}
.popup-content {
position: relative;
display: inline-block;
vertical-align: middle;
background: none #fff;
padding: 10px 20px;
text-align: left;
}
form ul {
list-style: none;
padding: 0;
}
.popup-close {
display: inline-block;
padding: 4px;
position: absolute;
top: 5px;
right: 5px;
cursor: pointer;
}
.invalid-input {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-popup="#frmUsers">
Open form
</button>
<form id="frmUsers" data-userid="">
<img id="btnClose" src="resources/img/close_window.png">
<h2 id="popupTitle"></h2>
<ul>
<li>
<label for="username">Username:</label>
<input type="text" id="username" name="txtUsername" placeholder="Please select username" class="required" />
<p></p>
</li>
<li>
<label for="level">Level:</label>
<input type="number" id="level" name="txtLevel" placeholder="Please select level" />
<p></p>
</li>
<li>
<label for="registrationStatus">RegistrationStatus:</label>
<select name="txtRegistrationStatus" id="registrationStatus" placeholder="Please select registration status">
<option value="Registered">Registered</option>
<option value="Unregistered">Unregistered</option>
</select>
<p></p>
</li>
<li>
<label for="registrationDate">RegistrationDate:</label>
<input type="text" id="registrationDate" name="txtRegistrationDate" placeholder="Please select date" />
<p></p>
</li>
<div class="btnZone">
<input class="btnDown" type="button" value="Save" id="btnSave" />
<input class="btnDown" type="button" value="Cancel" id="btnCancel" />
</div>
</ul>
</form>
It is not complicated indeed, but I never try to invent hot water, I just take one of existing plugins, as Magnific Popup.
Same code on JSFiddle.

Add/remove textbox value when checkbox change

I have the following jquery code where i want to remove the value from the textfield if the checkbox is unchecked and add if it is checked.
initially all the values comes in the textbox as the ^ seperator. and all checkboxes checked
here is y piece of code:
$(document).on('change','._invoice',function() {
var mystr = $(this).attr('data-id').is(":checked");
if(mystr) {
var returnVal = confirm("Are you sure?");
$(this).attr("checked", returnVal);
}
});
});
Text field values and i also want to remove the separator and add the name at the last with ^ as separator.
Robert Berenson^Nancy Foster^Richard Gourhan^LORI HEDMAN^Pui Hoang^Linda Lee^Kristen McDonald^Matthew Miller^Tricia Roland^Terry West
A simple way is that change text of textbox on checkbox change event. Then means you need to get text of every checked checkbox and set it to textbox, when any checkbox is changed.
$(".check").change(function(){
var text = "";
$(".check:checked").each(function(){
text += text != "" ? "^" : "";
if ($(this).prop("checked"))
text += $(this).val();
});
$(".text").val(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="check" value="Text1" />
<input type="checkbox" class="check" value="Text2" />
<input type="checkbox" class="check" value="Text3" />
<input type="checkbox" class="check" value="Text4" />
<input type="checkbox" class="check" value="Text5" />
<br/>
<input type="text" class="text" />
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' )
} )
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() {
calc()
} )
} )
function calc() {
for ( var i = 0, arr = []; i < list.length; i++ ) {
let spanArray = [];
document.querySelectorAll('span').forEach(element => {
spanArray.push(element.innerHTML);
});
if ( list[ i ].checked ) arr.push( list[ i ].value + " "+ spanArray)
}
txt.value = arr.join(', ')
}
h1 {
color: #0000ff;
}
#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
}
.content div {
padding: 10px 15px
}
.content div:hover {
background-color: #ddd
}
.show {
display: block
}
<h1>KIAAT</h1>
<b>Adding/Removing Checkbox Values into TextArea</b>
<br><br>
<input type="text" id="droptxt" class="list" placeholder="Select the values" readonly>
<div id="content" class="content">
<div id="market" class="list">
<label><input type="checkbox" id="market" class="list" value="apple" /> Apple</label>
</div>
<div class="list">
<label><input type="checkbox" id="banana" class="list" value="Banana" /> Banana</label>
</div>
<div class="list">
<label><input type="checkbox" id="pineapple" class="list" value="Pineapple" /> Pineapple</label>
</div>
</div>

Categories