Dynamically Created Div is getting invisible - javascript

I am trying to create a div dynamically by clicking a button and add it to the parent name "option_selection". But the div get 'vanished' (I don't know what else could I say because saying 'invisible' may mean something else!).
Here is my JS code:
function addMoreOptions(div){
var counter_div = document.getElementById("hidden");
var counter = counter_div.value;
counter_div.setAttribute("id","not_hidden");
counter_div.setAttribute("name","not_hidden");
counter++;
var addString="";
addString = addString+"<div style="\"width:" 250px;="" float:="" left;="" \"="">";
addString = addString+"<p>Choose option type to display :</p></div>";
addString = addString+"<div style="\"float:" left;\"=""><select id="\"option_type\"" name="\"option_type_";" addstring="addString+counter;"><option value="\"1\"">Single Option (radio button)</option>";
addString = addString+"<option value="\"2\"">Multiple Option (check boxes)</option>";
addString = addString+"<option value="\"3\"">Text Entry (text input box)</option>";
addString = addString+"<option value="\"4\"">Menu(Drop Down)</option></select></div>";
addString = addString+"<div style="\"float:" none;="" clear:="" both;="" width:="" 0px;\"=""></div>";
addString = addString+"<div style="\"width:" 250px;="" float:="" left;="" \"="">";
addString = addString+"<p>Enter option text:</p></div><div style="\"float:" left;\"="">";
addString = addString+"<input type="\"text\"" id="\"option_text_1\"" name="\"option_text_";" addstring="addString+counter;"><input id="\"hidden\"" type="\"hidden\"" name="\"hidden\"" value="";
addString = addString+counter;
addString = addString+""></div><div style="\"float:" none;="" clear:="" both;="" width:="" 0px;\"=""></div>";
var element = document.createElement("div");
element.innerHTML= addString;
document.getElementById(div).appendChild(element);
alert(document.getElementById(div).innerHTML);
}
here is the HTML Code
<div id="option_selection">
<div>
<div style="width: 250px; float: left; "><p>Choose option type to display :</p></div>
<div style="float: left;">
<select id="option_type" name="option_type_1">
<option value="1">Single Option (radio button)</option>
<option value="2">Multiple Option (check boxes)</option>
<option value="3">Text Entry (text input box)</option>
<option value="4">Menu(Drop Down)</option>
</select>
</div>
<div style="float: none; clear: both; width: 0px;"></div>
<div style="width: 250px; float: left; "><p>Enter option text:</p></div>
<div style="float: left;">
<input type="text" id="option_text_1" name="option_text_1">
<input id="hidden" name="hidden" type="hidden" value="1">
</div>
<div style="float: none; clear: both; width: 0px;"></div>
</div>
</div>
<div align="right" style="width: 800px;">
<button id="add" onclick="addMoreOptions('option_selection')">Add More Option</button>
Any help would be highly appreciated.
Thanks in Advance.

Your button has no type-attribute. The default type of buttons is submit (also see here).
type
The type of the button. Possible values are:
- submit: The button submits the form data to the server. This is the default if the attribute is not specified, or if the attribute is dynamically changed to an empty or invalid value.
- reset: The button resets all the controls to their initial values.
- button: The button has no default behavior. It can have client-side scripts associated with the element's events, which are triggered when the events occur.
Add type="button" and on click the form won't be submitted.
<button type="button" id="add" onclick="addMoreOptions('option_selection')">Add More Option</button>

Use
document.getElementById(div).innerHTML = element;
Instead of
document.getElementById(div).appendChild(element);

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>

Display div based upon datalist selection

This has probably been asked about before, but after several hours of looking I can't seem to find anything.
I have a datalist which is meant to display a div based on your selection of the datalist. Whatever I do, I can't seem to find out how to do it. The best I can get to work is have both selections display one of the divs, but not have spesific divs display based on the selection.
How do I make it so choosing div1 display div1, div2 displays div2 and so on?
var myinput = document.getElementById('example');
myinput.addEventListener("change", function() {
var mydiv = document.getElementById('#div');
mydiv.style.display = (this.value === '' ? 'none' : 'inline');
});
.hidden {
display: none;
}
<fieldset>
<legend>This is a datalist</legend>
<input type="text" id="example" list="brow" />
<datalist id="brow">
<option value="div1" />
<option value="div2" />
</datalist>
</fieldset>
<div class="hidden" id="div1">This is div1></div>
<div class="hidden" id="div2">This is div2></div>
your script will be like this.
var myinput = document.getElementById('example');
var divs = document.querySelectorAll('.hidden');
myinput.addEventListener('change', function() {
var mydiv = document.getElementById(this.value);
divs.forEach(div => {
div.style.display = div.id === this.value ? 'block' : 'none';
});
});
.hidden {
display: none;
}
<fieldset>
<legend>This is a datalist</legend>
<input type="text" id="example" list="brow" />
<datalist id="brow">
<option value="div1" />
<option value="div2" />
</datalist>
</fieldset>
<div class="hidden" id="div1">This is div1></div>
<div class="hidden" id="div2">This is div2></div>
If you have a selected element, remove .hidden to show it.
Else, search for the div that doesn't have .hidden and add back the class to hide it.
document.getElementById('example').addEventListener("change", () => {
if(event.target.value){
document.getElementById(event.target.value).classList.remove("hidden");
}
else{
document.querySelector(".somediv:not(.hidden)").classList.add("hidden");
}
});
.hidden {
display: none;
}
<fieldset>
<legend>This is a datalist</legend>
<input type="text" id="example" list="brow"/>
<datalist id="brow">
<option value="div1"/>
<option value="div2"/>
</datalist>
</fieldset>
<div class="somediv hidden" id="div1">This is div1</div>
<div class="somediv hidden" id="div2">This is div2</div>

PHP code doesn't see input added through js

I have form that collect datas when SAVE button is pressed from three inputs. First two is already loaded on the site, but last appears when DVD-disk is selected in <select>. So PHP code see values from first two inputs, but not from the last one. I added name and id to all of them. Inputs are in the main container that is in form.
Expected output: echo ($DVDdisk) show data
Real output: Undefined index: DVDsize
let selector = document.getElementById("selector");
let main = document.getElementById("input-main-add");
let div = document.createElement('div');
let h2 = document.createElement('H2');
let input = document.createElement('input');
selector.addEventListener("change", (e) => {
if (selector.value == "DVD") {
div.classList.add('input-add-holder');
main.appendChild(div);
h2.textContent = 'Enter size:';
h2.style.display = 'inline-block';
div.appendChild(h2);
input.setAttribute("name", "DVDsize");
input.setAttribute("id", "DVDsize");
div.appendChild(input);
}
});
<form method="POST" action="add.php">
<button class="accept-btn" type="submit">SAVE</button>
<!-- + -->
<button class="decline-btn">CANCEL</button>
<!-- + -->
</div>
</div>
<div class="input-main-add" id="input-main-add">
<!-- + -->
<div class="input-add-holder">
<H2 style="display:inline-block">SKU: </H2>
<input class="something" name="SKU" id="SKU"></input>
</div>
<div class="input-add-holder">
<H2 style="display:inline-block">Name: </H2>
<input class="something" name="name" id="name"></input>
</div>
<div class="input-add-holder">
<H2 style="display:inline-block">Type Switcher: </H2>
<select name="selector" id="selector">
<option value="DVD" id="DVD" name="DVD">DVD-Disk</option>
<option value="book" id="book" name="book">Book</option>
<option value="furniture" id="furniture" name="furniture">Furniture</option>
</select>
</div>
</div>
</form>
PHP code:
<?php
$SKU = $_POST["SKU"];
$name = $_POST["name"];
$DVDsize = $_POST["DVDsize"];
echo ($SKU);
echo ($name);
echo ($DVDsize);
?>
Your JS listen for change event on Type Switcher select box that the selected value must be DVD-Disk but your default value of this select box is DVD-Disk which is already selected.
So, this event will never happens when you just load the page, fill form (without change select box) and submit.
If this event never happens, it means input name DVDSize will not rendered and not send to server. That's why your PHP doesn't see this input.
You have to manually trigger change event for select box once DOM ready.
let selector = document.getElementById("selector");
let main = document.getElementById("input-main-add");
let div = document.createElement('div');
let h2 = document.createElement('H2');
let input = document.createElement('input');
selector.addEventListener("change", (e) => {
if (selector.value == "DVD") {
div.classList.add('input-add-holder');
main.appendChild(div);
h2.textContent = 'Enter size:';
h2.style.display = 'inline-block';
div.appendChild(h2);
input.setAttribute("name", "DVDsize");
input.setAttribute("id", "DVDsize");
div.appendChild(input);
}
});
// manually trigger change event.
let selectTypeSwitcher = document.getElementById('selector');
if (selectTypeSwitcher) {
selectTypeSwitcher.dispatchEvent(new Event('change'));
}
<form method="POST" action="add.php">
<button class="accept-btn" type="submit">SAVE</button>
<!-- + -->
<button class="decline-btn">CANCEL</button>
<!-- + -->
</div>
</div>
<div class="input-main-add" id="input-main-add">
<!-- + -->
<div class="input-add-holder">
<H2 style="display:inline-block">SKU: </H2>
<input class="something" name="SKU" id="SKU"></input>
</div>
<div class="input-add-holder">
<H2 style="display:inline-block">Name: </H2>
<input class="something" name="name" id="name"></input>
</div>
<div class="input-add-holder">
<H2 style="display:inline-block">Type Switcher: </H2>
<select name="selector" id="selector">
<option value="DVD" id="DVD" name="DVD">DVD-Disk</option>
<option value="book" id="book" name="book">Book</option>
<option value="furniture" id="furniture" name="furniture">Furniture</option>
</select>
</div>
</div>
</form>
Run the code above while open network inspector and you will see DVDSize input send to the server.

Input field validated only for first input field and not able to remove input field

I had created Ul which add the student input field with value and user can remove the field as well,Initially I am comparing student field value with each input field which are created to avoid duplication but it works only for first input field value not for others I used loop as well but its not working and not able to remove one input field at a time.
Here is my fiddle code
$('#addBtn').click(function () {
var studentArray = $(".students").text();
var i=" " ;
console.log(studentArray);
var studentSplitResult = studentArray.split('Remove');
console.log(studentSplitResult);
for (var i = 0; i < studentSplitResult.length; i++) {
if ($("#selectStd").val() !== $(".students").val()) {
$(".stdList").show();
var input_value = $('#selectStd').val();
$('ul').append('<input class="students" value="' + input_value + '">Remove</input>');
console.log($(".students").val());
// console.log(studentSplitResult[i]);
};
return false;
}
});
//prevent default action
$(document).on('click', 'a', function (e) {
e.preventDefault();
$(this).parent().remove();
});
You can simplify your code like below.
Just check any text input has the new value before adding using filter. It will also handle case insensitivity (remove if required).
Also while removing consider the removing the text input only.
Added e.preventDefault() to restrict the form posting. change or remove it as per requirement.
$('#addBtn').click(function(e) {
e.preventDefault();
var input_value = $("#selectStd").val();
var isValid = $('input.students').filter(function() {
return this.value.toLowerCase() == input_value.toLowerCase();
}).length <= 0;
if (isValid) {
$('ul').append('<input class="students" value="' + input_value + '">Remove</input>');
} else {
alert('Duplicate');
}
});
//prevent default action
$(document).on('click', 'a.deleteStd', function(e) {
e.preventDefault();
$(this).prev('.students').remove();
$(this).remove();
});
<body>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<div class="panel panel-body" style=" width:422px;border: 1px solid #00A4CC;">
<div id="errorLabel"></div>
<div id="parentType">
<form id="parentForm" name="parentForm">
<table style="margin-left: 8px;">
<tr>
<th>Select Student</th>
<td><input class="form-control" id="selectStd" placeholder="Please select students"></td>
<td><button id="addBtn" class="btn btn-default" style="margin-left: 17px;">Add</button></td>
</tr>
</table>
<ul class="stdList">
<label>Selected Students:</label><br>
<br>
</ul>
<table>
</table>
</form>
</div>
</div>
</div>
</body>
I have encountered two issues: input validation itself (your question) and the removal of the element when you click on the anchor element.
For input validation, I have rewritten it a bit. What I did is
1. Obtain new student value
2. Check if not empty by if(newStudent). If it's empty, nothing happens
3. obtain other inputs
4. match the new input against the values inside other inputs
4a. if match, don't add it.
4b. if no match, add it
For removing the element, You need to revise your HTML. It's not so correct. I have wrapped it around with a <section> element to have a save removal and corrected the HTML use.
A side note, you may also reconsider this
$(document).on('click', 'a', function(e) {
e.preventDefault();
$(this).parent().remove();
});
If your HTML page has multiple anchor (<a>) elements, this function is used too on another anchor elements. If you click on these, it will remove these from the page upon click. If you don't want it, please revise the above function.
$('#addBtn').click(function(e) {
// obtain new student value
var newStudent = $('#selectStd').val();
// check if it is not empty
if (newStudent) {
// obtain other names and check if there is no match
var studentArray = $(".students");
var hasMatch = false;
studentArray.each(function(i, el) {
if (el.value === newStudent) {
hasMatch = true;
return; // stopping loop
}
});
// if there is no match, add student
if (!hasMatch) {
$('ul.stdList').append('<section><input class="students" value="' + newStudent + '" />Remove</section>');
}
}
return false;
});
//prevent default action
$(document).on('click', 'a', function(e) {
e.preventDefault();
$(this).parent().remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel panel-body" style=" width:422px;border: 1px solid #00A4CC;">
<div id="errorLabel"></div>
<div id="parentType">
<form id="parentForm" name="parentForm">
<table style="margin-left: 8px;">
<tr>
<th>Select Student</th>
<td>
<input class="form-control" id="selectStd" placeholder="Please select students">
</td>
<td>
<button id="addBtn" class="btn btn-default" style="margin-left: 17px;">Add</button>
</td>
</tr>
</table>
<ul class="stdList">
<label>Selected Students:</label>
<br>
<br>
</ul>
</form>
</div>
</div>
When adding you try this:
$('ul').append('<input class="students" value="' + input_value + '">Remove</input>');
Unfortunately this will not result in what you expect. The anchor will be adding by your browser next to the input not nested. Like this:
<input class="students" value="thevalue" />
<a href class="deleteStd">Remove</a>
So if you do this afterwards for removing $(this).parent().remove(); you will remove the entire container.
What you need to do is this:
$('ul').append('<div><input class="students" value="' + input_value + '" />Remove</div>');
This will work. I have updated your fiddle: https://jsfiddle.net/Lojdfyhn/1/
So based on your requirements, try this below code:
Student names can't be duplicate
And on removing, all names shouldn't removed.
While adding, code checks if the student name exists. If yes, it throws an error/alert.
$('#addBtn').click(function() {
var valueToCheck = $("#selectStd").val();
var flag = true;
$(".students").each(function() {
if ($(this).val() === valueToCheck) {
flag = false;
}
});
if (flag) {
$('ul').append('<span class="addedStudent"><input class="students" value="' + valueToCheck + '" />Remove</span>');
} else {
alert(valueToCheck + " already exists.");
}
return false;
});
//prevent default action
$(document).on('click', 'a.deleteStd', function(e) {
e.preventDefault();
$(this).parents(".addedStudent:first").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel panel-body" style=" width:422px;border: 1px solid #00A4CC;">
<div id="errorLabel"></div>
<div id="parentType">
<form id="parentForm" name="parentForm">
<table style="margin-left: 8px;">
<tr>
<th>Select Student</th>
<td><input class="form-control" id="selectStd" placeholder="Please select students"></td>
<td><button id="addBtn" class="btn btn-default" style="margin-left: 17px;">Add</button></td>
</tr>
</table>
<ul class="stdList">
<label>Selected Students:</label><br>
<br>
</ul>
<table>
</table>
</form>
</div>
</div>
You are trying to delete the parent element of anchor tag.
Just update your code like this
$('ul').append('<div><input class="students" value="' + input_value + '">Remove</input></div>');
then clicking on anchor will delete the parent of anchor element.
Hello first of all you need to get a good understanding of the DOM traversing, which can really help you to organise the students that you are adding to the list, and removing.
Here a simple solution can be implemented as follows.
First encapsulate all the students in a div tag with 'students' class name, and in that div, place the student text field with 'stdname' class and the anchor tag to help in removing the student details.
Now when traverse through all the students with 'stdname' class and check if there is a duplicate value.
Here is the code please check out.
and check on jsfiddle too.http://jsfiddle.net/naveen_namani/842bf5ke/1/
$('#addBtn').click(function () {
var student_list=document.querySelectorAll(".students .stdname");
var selectStd=document.getElementById("selectStd");
var duplicate=false;
for(var i=0;i<student_list.length;i++) {
if(student_list[i].value==selectStd.value) duplicate=true;
}
if(duplicate==false) {
$('ul').append('<div class="students"><input value="'+selectStd.value+'" class="stdname"/>Remove');
}
return false;
});
$(document).on('click', 'a', function (e) {
e.preventDefault();
$(this).parent().remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel panel-body" style="width:422px;border:1px solid #00A4CC;">
<div id="errorLabel"></div>
<div id="parentType" >
<form id="parentForm" name="parentForm">
<table style="margin-left: 8px;">
<tr>
<th>Select Student</th>
<td>
<input class="form-control" id="selectStd" placeholder="Please select students">
</td>
<td>
<button id="addBtn" class="btn btn-default" style="margin-left: 17px;" >Add</button>
</td>
</tr>
</table>
<ul class="stdList">
<label>Selected Students:</label>
<br><br>
</ul>
<table ></table>
</form>
</div>
</div>

Javascript multi-selection

I currently have the following functionality (see link: http://jsfiddle.net/eUDRV/3/) and instead of appending the selected values back to the original list, I'd like to return them to the spot that they were previously in. My values are in alphabetical order. I know that I need to index the spot of each value but I'm not quite sure how to accomplish this. Any help would be appreciated, thanks.
Here's my HTML code:
<section class="container">
<div>
<select id="leftValues" size="5" multiple></select>
</div>
<div>
<input type="button" id="btnLeft" value="<<" />
<input type="button" id="btnRight" value=">>" />
</div>
<div>
<select id="rightValues" size="4" multiple>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<div>
<input type="text" id="txtRight" />
</div>
</div>
Javascript code:
$("#btnLeft").click(function () {
var selectedItem = $("#rightValues option:selected");
$("#leftValues").append(selectedItem);
});
$("#btnRight").click(function () {
var selectedItem = $("#leftValues option:selected");
$("#rightValues").append(selectedItem);
});
$("#rightValues").change(function () {
var selectedItem = $("#rightValues option:selected");
$("#txtRight").val(selectedItem.text());
});
CSS code:
SELECT, INPUT[type="text"] {
width: 160px;
box-sizing: border-box;
}
SECTION {
padding: 8px;
background-color: #f0f0f0;
overflow: auto;
}
SECTION > DIV {
float: left;
padding: 4px;
}
SECTION > DIV + DIV {
width: 40px;
text-align: center;
}
You could assign each option within your select a value attribute that corresponds to the text and then in your code:
$("#btnLeft").click(function () {
var selectedItem = $("#rightValues option:selected");
$("#leftValues").append(selectedItem);
});
You could have it look up the value of the selected item, compare it with anything in the list and place it in the appropriate index in that list and do the same for the code which moves it back into the right hand list.
You could also strip the innerHTML value of the option instead if you didn't want to add the value attribute.

Categories