I have a list of options. When selectting an option in the list I create new elemets and append them to another div.
HTML:
<select multiple="multiple">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<div class="tankListProduct">
// things get appended here
</div>
Script
$(function(){
$("#SelectedProduktValues")
.on("change", function(e) {
var optionValueArray = $(this).val();
var optionValue = optionValueArray[optionValueArray.length-1];
var optionText = $("#SelectedProduktValues option[value='" + optionValue + "']").text();
var $options = $("#SelectedTanksValues > option").clone();
var div = "<div class='col-xs-20 adminRow'>";
div += "<p class='col-xs-20 text-center'>" + optionText + "</p>";
div += "<select class='form-control tankList'</select>";
div += "</div>";
$(".tankListProduct").append(div);
$('.tankList').last().selectpicker();
});
})
This works perfectly and is shown in the fiddle below but I can't figre out how I can detect if an option in the list has been deselected so that I can remove the inserted element that corresponds to that option?
Fiddle
EDIT:
If it was uncelar, this is a multiSelect list
You forgot to close the select tag.
Clearing the html before you append should help "deselect" the no longer selected ones.
And a jQuery each loop to loop over the selected elements.
I've added a button to clear the selected items, if you dont want anything selected. I'm sure you can come up with something more clever though.
HTML
<select id="SelectedProduktValues" multiple="multiple">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<div class="clearList"> Click to clear selction </div>
<div class="tankListProduct">
</div>
Javscript/JQuery
$(function() {
$("#SelectedProduktValues")
.on("change",
function(e) {
var optionValueArray = $(this).val();
var div = '';
$.each(optionValueArray, function(key, value) {
var optionValue = value;
var optionText = $("#SelectedProduktValues option[value='" + optionValue + "']").text();
div += "<div class='col-xs-20 adminRow'>";
div += "<p class='col-xs-20 text-center'>" + optionText + "</p>";
div += "<select class='form-control tankList'> </select>";
div += "</div>";
});
$(".tankListProduct").html('');
$(".tankListProduct").append(div);
$('.tankList').last().selectpicker();
});
})
$(".clearList").on("click", function(e) {
$(".tankListProduct").html('');
});
And here's a fiddle.
https://jsfiddle.net/uhnkwx1g/8/
Hope this helps.
on onchange event you can just clearout the existing html and add new contents of the selected option
check this snippet
$(function() {
$("#SelectedProduktValues")
.on("change", function(e) {
var optionValueArray = $(this).val();
var optionValue = optionValueArray[optionValueArray.length - 1];
var options = $("#SelectedProduktValues").find('option');
var element = $(".tankListProduct");
var elem = $(element[0]);
options.each(function(option) {
var isSelected = $(options[option]).prop('selected');
var optionText = $(options[option]).text();
var child = "div#" + optionText;
if (isSelected) {
var $options = $("#SelectedTanksValues > option").clone();
if (elem.find(child).length == 0) {
var div = "<div class='col-xs-20 adminRow' id='" + optionText + "'>";
div += "<p class='col-xs-20 text-center'>" + optionText + "</p>";
div += "<select class='form-control tankList'</select>";
div += "</div>";
$(".tankListProduct").append(div);
}
} else {
$(".tankListProduct").find("div#" + optionText).remove();
}
})
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select id="SelectedProduktValues" multiple="multiple">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<div class="tankListProduct">
// things get appended here
</div>
Hope it helps
Related
I'm trying to let the user select a value from a dropdown selector, which in turn will conditionally load a second dropdown selector. Once both fields have a value, a link will appear that has been dynamically generated from those two values.
For example: User selects "audi" from first form, which shows the audi form, then they select "r8" from the second form, which would produce www.example.com/**audi**/**r8**/
However, it seems that I can't get the event.target.value of the second dropdown; I'm assuming because when the script loads the value isn't there.
How would I go about writing this so I could get both values, then fill it into a link?
<form>
<select name="cars" id="cars">
<option value="" disabled selected>Select your Car</option>
<option value="audi">Audi</option>
<option value="volkswagen">Volkswagen</option>
</select>
</form>
<br><br>
<div class="model-field" id="model-field"></div>
<div class="button-field">
<h4>link:</h4>
<p id="button-field"></p>
</div>
<script>
var audiForm = '<form class="audi-model">' +
'<select name="audi-model" id="audi-model">' +
'<option value="" disabled selected>Select Audi model</option>' +
'<option value="a4">A4</option>' +
'<option value="a5">A5</option>' +
'<option value="r8">r8</option>' +
'</select>' +
'</form>';
var vwForm = '<form class="vw-model">' +
'<select name="vw-model" id="vw-model">' +
'<option value="" disabled selected>Select VW model</option>' +
'<option value="jetta">Jetta</option>' +
'<option value="passat">Passat</option>' +
'</select>' +
'</form>';
var carsForm = document.getElementById("cars");
if (carsForm) carsForm.addEventListener('change', function(event) {
var carType = (event.target.value);
console.log(carType);
if(event.target.value == 'audi') {
document.getElementById("model-field").innerHTML = audiForm;
}
if(event.target.value == 'volkswagen') {
document.getElementById("model-field").innerHTML = vwForm;
}
});
var audiModelForm = document.getElementById("audi-model");
if (audiModelForm) audiModelForm.addEventListener('change', function(event) {
var audiModel = event.target.value;
console.log(audiModel); // Doesn't work as the above line is likely null
var link = '<h4>' + carType + '/' + audiModel + '</h4>';
console.log(link);
document.getElementById("button-field").innerHTML = link;
});
var vwModelForm = document.getElementById("vw-model");
if (vwModelForm) vwModelForm.addEventListener('change', function(event) {
var vwModel = event.target.value;
console.log(vwModel); // Doesn't work as the above line is likely null
var link = '<h4>' + carType + '/' + vwModel + '</h4>';
console.log(link);
document.getElementById("button-field").innerHTML = link;
});
</script>
Another solution is to store the options in a javascript object, and just auto fill in the select as needed. This will allow you to easily update the system to accept more makes and models.
var data = {
"audi": ["a4","a5","r8"],
"volkswagen": ["Bug","Jetta","Golf"]
};
var make = document.querySelector("#cars");
var model = document.querySelector("#model");
var link = document.querySelector("#link");
make.addEventListener("change",function(){
if(make.value != ""){
var models = data[make.value];
var length = model.options.length;
for (i = length-1; i >= 0; i--) {model.options[i] = null;}
link.innerHTML = "";
let opt= document.createElement("option");
opt.text = "Select " + make.value + " Model";
opt.value = "";
model.appendChild(opt);
models.forEach(function(k,v){
let opt= document.createElement("option");
opt.text = k;
opt.value = k;
model.appendChild(opt);
});
}
});
model.addEventListener("change",function(){
if(model.value != ""){
link.innerHTML = '<h4>' + make.value + '/' + model.value + '</h4>';
}
});
<form>
<select name="cars" id="cars">
<option value="" disabled selected>Select your Car</option>
<option value="audi">Audi</option>
<option value="volkswagen">Volkswagen</option>
</select>
<select name="model" id="model"></select>
</form>
<div id="link">
</div>
The problem is that your code attempts to find and set up an event handler for the second dropdown before it gets created. Moving that code so that it is within the first event handler makes it work.
<form>
<select name="cars" id="cars">
<option value="" disabled selected>Select your Car</option>
<option value="audi">Audi</option>
<option value="volkswagen">Volkswagen</option>
</select>
</form>
<br><br>
<div class="model-field" id="model-field"></div>
<div class="button-field">
<h1>link:</h1>
<p id="button-field"></p>
</div>
<script>
var audiForm = '<select name="audi-model" id="audi-model">' +
'<option value="" disabled selected>Select Audi model</option>' +
'<option value="a4">A4</option>' +
'<option value="a5">A5</option>' +
'<option value="r8">r8</option>' +
'</select>' +
'</form>';
var vwForm = '<select name="vw-model" id="vw-model">' +
'<option value="" disabled selected>Select VW model</option>' +
'<option value="jetta">Jetta</option>' +
'<option value="passat">Passat</option>' +
'</select>' +
'</form>';
var carsForm = document.getElementById("cars");
if (carsForm) carsForm.addEventListener('change', function(event) {
var carType = (event.target.value);
console.log(carType);
if(event.target.value == 'audi') {
document.getElementById("model-field").innerHTML = audiForm;
}
if(event.target.value == 'volkswagen') {
document.getElementById("model-field").innerHTML = vwForm;
}
var audiModelForm = document.getElementById("audi-model");
if (audiModelForm) {
audiModelForm.addEventListener('change', function(event) {
var audiModel = event.target.value;
console.log(audiModel);
var link = '<h4>' + carType + '/' + audiModel + '</h4>';
console.log(link);
document.getElementById("button-field").innerHTML = link;
});
}
});
var vwModelForm = document.getElementById("vw-model");
if (vwModelForm) vwModelForm.addEventListener('change', function(event) {
var vwModel = event.target.value;
console.log(vwModel); // Doesn't work as the above line is likely null
var link = '<h4>' + carType + '/' + vwModel + '</h4>';
console.log(link);
document.getElementById("button-field").innerHTML = link;
});
</script>
But really, a better solution is to have the select already statically built from the start, but just hidden. Then, you can set up its handler right away, but only populate its option elements after the first selection has been made. You'll also only need one secondary select for whatever set of option elements are relevant based on the first choice.
Also, you shouldn't be creating form elements that wrap each select. If you are going to submit this data somewhere, you just want one form around all the form elements. And, if not, you don't need a form at all.
Lastly, don't use HTML heading elements because of the size that they make your text. You can't have an h4 unless you've already got an h3. Use CSS to style your text.
var audi = '<option value="" disabled selected>Select Audi model</option>' +
'<option value="a4">A4</option>' +
'<option value="a5">A5</option>' +
'<option value="r8">r8</option>';
var vw = '<option value="" disabled selected>Select VW model</option>' +
'<option value="jetta">Jetta</option>' +
'<option value="passat">Passat</option>';
var cars = document.getElementById("cars");
var models = document.getElementById("models");
cars.addEventListener('change', function(event) {
if(event.target.value == 'audi') {
models.innerHTML = audi;
} else if(event.target.value == 'volkswagen') {
models.innerHTML = vw;
}
models.classList.remove("hidden"); // Time to show the second list
});
models.addEventListener('change', function(event) {
var link = '<h1>' + cars.value + '/' + models.value + '</h1>';
console.log(link);
document.getElementById("button-field").innerHTML = link;
});
.hidden { display:none; }
h1 { font-size:.8em;}
<form>
<select name="cars" id="cars">
<option value="" disabled selected>Select your Car</option>
<option value="audi">Audi</option>
<option value="volkswagen">Volkswagen</option>
</select>
<div class="model-field" id="model-field">
<select name="models" id="models" class="hidden"></select>
</div>
</form>
<div class="button-field">
<h1>link:</h1>
<p id="button-field"></p>
</div>
I have some JavaScript-generated html code. The JavaScript generates the elements (option) in a drop down list (select). I then want to get the value of the selected option '1', however instead 'test' is returned.
The html is generated using:
var newSelect = document.createElement('option');
selectHTML = "<option value=\"" + 1 + "\">" + test + "</option>";
newSelect.innerHTML = selectHTML;
document.getElementById('siteID').add(newSelect);
I have then tried the following methods to get the value of the selected option:
var siteId = $('#siteID').val(); // returns 'test'
var siteId2 = $('#siteID').data("value"); // returns undefined
var siteId3 = $('#siteID').attr("value"); // returns undefined
var siteId4 = $('#siteID').prop("value"); // returns 'test'
You are using a very strange way to create your option - you create an option and then insert an option string as innerHTML
Fixed code (see example later)
var opt = document.createElement('option');
opt.value=1;
opt.text="test"
document.getElementById('siteID').appendChild(opt);
Also you do not actually select the option, so the value will be whatever the browser thinks is selected
Why not use jQuery?
$("<option />", { value: 1, text: "test" }).appendTo('#siteID1')
$('#siteID1').prop("selectedIndex", 1); // NOW the value is 1
console.log(
$('#siteID1').val()
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="siteID1">
<option value="">Please select</option>
</select>
Your code:
var test ="Test";
var newSelect = document.createElement('option'),
selectHTML = "<option value=\"" + 1 + "\">" + test + "</option>";
newSelect.innerHTML = selectHTML;
document.getElementById('siteID').add(newSelect);
console.log(document.getElementById('siteID').outerHTML)
<select id="siteID">
</select>
Your FIXED code
var opt = document.createElement('option');
opt.value=1;
opt.text="test"
document.getElementById('siteID').appendChild(opt);
console.log(document.getElementById('siteID').value, $('#siteID').val())
console.log(document.getElementById('siteID').outerHTML)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="siteID">
</select>
You created the option newSelect then you try to insert an option inside of it with innerHTML which is where you went wrong.
This is what you should have done.
var newSelect = document.createElement('option');
newSelect.innerHTML = 'test';
newSelect.value= '1';
document.getElementById('siteID').add(newSelect);
You need remove //selectHTML = "<option value=" + 1 + ">" + test + "</option>";
And change to newSelect.value = 1; for add value to option by javascript
newSelect.innerHTML = test;
newSelect.value = 1;
var newSelect = document.createElement('option');
var test = 'test';
//selectHTML = "<option value=" + 1 + ">" + test + "</option>";
newSelect.innerHTML = test;
newSelect.value = 1;
document.getElementById('siteID').appendChild(newSelect);
$(document).ready(function(){
var siteId = $('#siteID').val(); // r
console.log(siteId);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id='siteID'>
</select>
Please try this
var test = 'test';
selectHTML = "<option value=\"" + 1 + "\">" + test + "</option>";
$("#siteID").append(selectHTML);
var siteId = $('#siteID').val();
console.log(siteId);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="siteID"></select>
You can first create the Select tag and after that try to append the option tag. I have attached the code as below:
// create the select tag and append with the main div tag
var string = '<select id="dropdown_tag"></select>';
$("#test").append(string);
// create as many option you want and append with the select tag
var newSelect = document.createElement('option');
selectHTML = "<option>---select---</option>";
selectHTML += "<option value='1'>1</option>";
selectHTML += "<option value='2'>2</option>";
$("#dropdown_tag").append(selectHTML);
// Onchange event of dropdown tag
$(document).on('change',"#dropdown_tag", function()
{
alert($(this).val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Dropdowm:<div id='test'></div>
I have two select box. on change event of first select box, i'm adding that text into second select box. but i don't want to add duplicate record.for this i'm using filter function,(if any text that has already added then i don't want to add again) but it's not working as i want.
html
<select id="ddlCategory">
<option value="0">Select Category</option>
<option value="1">Category 1</option>
<option value="2">Category 2</option>
<option value="3">Category 3</option>
</select>
<select multiple="multiple" id="my-select" name="my-select[]" class="multiDrop"> </select>
<select multiple="multiple" id="your-select" name="my-selectyour[]" class="multiDrop">
myJs:
$('#my-select').change(function () {
var getValue = $(this).find('option:selected').val();
var getText = $(this).find('option:selected').text();
var getCategory = $('#ddlCategory').find('option:selected').text();
if ($('#your-select > option').hasClass(getCategory)) {
$("#your-select > option").filter(function (index) {
if ($(this).html() == getText) {
return;
}
$('#your-select').append('<option value="' + getValue + '" class="' + getCategory + '">' + getText + '</option>');
});
} else {
$('#your-select').html('<option value="' + getValue + '" class="' + getCategory + '">' + getText + '</option>');
}
});
Jsfiddle
Here you go... my edited fiddle: http://jsfiddle.net/stoz1m6v/2/
This way it does not duplicate the entries in myselect...
you had some checking of class/category there which I removed, because I found it incorrectly done, however I could not comprehend how exactly you wanted to check the category...
and the script goes like this... I have changed only the change handler of the my-select:
$('#my-select').change(function () {
var getValue = $(this).find('option:selected').val();
var getText = $(this).find('option:selected').text();
var getCategory = $('#ddlCategory').find('option:selected').text();
if ($("#your-select > option").filter(function (index) {
return $(this).html() == getText; }).length ==0) {
$('#your-select').append('<option value="' + getValue + '" class="' + getCategory + '">' + getText + '</option>');
}
});
HTML
<input type="text" value="" id="ip1" class="ip1" />
<input type="button" value="Add" class="bt1" id="bt1">
</br>
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
</select>
JQUERY
$(document).ready(function(e) {
$(".bt1").click(function(){
var opt = $("#ip1").val();
});
});
Hi friends here i want to add value from text box to select option using jquery,
i got the value from textbox but don't know how to insert, help me.
you can do like this:
HTML:
<select id="List">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
</select>
JQUERY:
$(".bt1").click(function(){
var opt = $("#ip1").val();
$('#List')
.append($("<option></option>")
.attr("value",opt )
.text(opt));
});
FIDDLE DEMO
Use append
$(document).ready(function(e) {
$(".bt1").click(function(){
var opt = $("#ip1").val();
$("select").append('<option value="' + opt+ '">' + opt +'</option>')
});
});
$(document).ready(function (e) {
$(".bt1").click(function () {
var opt = $("#ip1").val();
$('select').append(' <option value="' + opt + '">' + opt + '</option>')
});
});
DEMO
$(".bt1").on('click',function () {
var optionval= $("#ip1").val();
$('select').append(' <option value="' + opt + '">' + opt + '</option>')
});
$(document).ready(function(e) {
$("select").change(function(){
var opt = $("#ip1").val();
});
});
Try this:
$(".bt1").click(function () {
var opt = $("#ip1").val();
//check if option already exists in the drop down
if (!$("select").find("option[value='" + opt + "']").length) {
//add option to the drop down
$("select").append("<option value='" + opt + "'>" + opt + "</option>");
}
//select entered option
$("select").find("option[value='" + opt + "']").attr("selected", "selected");
});
See DEMO here.
Hope this will help
$(document).ready(function (e) {
var $txtVal = $('#ip1');
$(".bt1").click(function () {
var opt = $("#ip1").val();
if($txtVal.val()){
$('<option />', { text: $txtVal.val(),value: $txtVal.val()}).appendTo('select');
}
});
});
FIDDLE HERE >>
This script produce a drop down form where I can select the number of drop down fields that can be displayed. However I'm kind of stuck on that. My problem now is how to make default text field base on the value of the second drop down form? For example if I select 'Ms.' It will produce Two text field else it will just one text field.
jQuery
$(document).ready(function() {
$('#bookinfo_adult').change(function() {
var num = $('#bookinfo_adult').val();
var i = 0;
var html = '';
for (i = 1; i <= num; i++) {
html += '<br>' + i + '. <select name="gender4-' + i + '">' + '</' + 'option>' + '<option value=' + '"m">Mr. ' + '</option' + '>' + '<option value=' + '"f">' + 'Ms. ' + '</option' + '>' + '</select' + '></br>';
}
$('#list').html(html);
});
});
HTML
<select id="bookinfo_adult" name="bookinfo_adult">
<option value="0">- SELECT -</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
<div id="list"></div>
Not quite sure what you're asking, but I guess you want to display input fields dynamically based on the current selection in your generated select elements?
So how about this?
HTML:
<input type="text" id="bookinfo_adult">
<div id="list"></div>
CSS:
#list input { display: none; }
JS:
$(document).ready(function() {
$('#bookinfo_adult').change(function() {
var num = $('#bookinfo_adult').val(), i = 0, html = '';
for (i = 1; i <= num; i++) {
html += '<div>' + i + '. \
<select name="gender4-'+i+'"><option/><option value="m">Mr.</option><option value="f">Ms.</option><select> \
<input type="text" class="ms"> <input type="text" class="mr">\
</div>';
}
$('#list').html(html);
});
$(document).on("change", "#list select", function(){
var parent = $(this).closest("div");
switch ($(this).val()) {
case "m": parent.find(".mr").show(); parent.find(".ms").hide(); break;
case "f": parent.find("input").show(); break;
default: parent.find("input").hide(); break;
}
});
});
I just added two text fields (hidden with CSS at first) and wrapped every "line" of your dropdown in a div for easier selection. Then a onchange handler is created that works for all elements being added to the DOM in the future (once you could use jQuery.live() for that, but it's deprecated as of version 1.7). The handler itself should be self-explanatory. ;)
Working example: http://jsfiddle.net/DfXEE/