So, I'm trying to make a JS action where it should display the selected items from the list, I can only select one but I want to select more than one and view it in a list
<body>
<label for="issue">Issue Type:</label>
<select multiple="multiple" name="issue" id="issue">
<option value="passport">passport</option>
<option value="selfie">selfie</option>
<option value="nationalId">nationalId</option>
</select>
<p> you are missing the following information:</p>
<ul id="issue-type">
<script>
var output = '';
let issues = document.getElementById("issue");
for (i = 0; i < issues.length; i++) {
output += document.write("<li>" + issues[i].text + </li>").innerHTML = issues;
}
</script>
</ul>
</body>
You need to use an event listener to listen for a change of selection and you need to update the html of the element. You rarely ever want to use document.write in an application.
const issueSelect = document.getElementById("issue");
// listen for a change
issueSelect.addEventListener("change", selChanged);
function selChanged() {
var output = '';
let issues = issueSelect.options;
// loop over the options
for (var i = 0; i < issues.length; i++) {
// is it selected?
if (issues[i].selected) {
// yes, build a list item
output += "<li>" + issues[i].value + "</li>";
}
}
// set the list's content
document.getElementById("issue-type").innerHTML = output;
}
<body>
<label for="issue">Issue Type:</label>
<select multiple="multiple" name="issue" id="issue">
<option value="passport">passport</option>
<option value="selfie">selfie</option>
<option value="nationalId">nationalId</option>
</select>
<p> you are missing the following information:</p>
<ul id="issue-type">
</ul>
</body>
How I would have coded it
const issueSelect = document.getElementById("issue");
// listen for a change
issueSelect.addEventListener("change", selChanged);
function selChanged() {
const selectedOpts = issueSelect.querySelectorAll("option:checked");
const output = [...selectedOpts].map(opt => `<li>${opt.value}</li>`).join('');
document.getElementById("issue-type").innerHTML = output;
}
<body>
<label for="issue">Issue Type:</label>
<select multiple="multiple" name="issue" id="issue">
<option value="passport">passport</option>
<option value="selfie">selfie</option>
<option value="nationalId">nationalId</option>
</select>
<p> you are missing the following information:</p>
<ul id="issue-type">
</ul>
</body>
Here is one solution and I commented each line.
let output = '';
let issues = document.querySelector("#issue");
let issue_types = document.querySelector("#issue-type");
issues.addEventListener("change", function(e) { //change event listener to check for when the select is changed
issue_types.innerHTML = ""; //empties destination div
let options = e.target.selectedOptions; //grabs the selected options
options = Array.from(options).map(({ value }) => value); //converts the selected options to an array of values
options.forEach(function(opt){ //loops through the options
let li = document.createElement("li"); //creates a LI element
li.innerHTML = opt; //sets the innerHTML of the list item to the option
issue_types.appendChild(li) //appends the list to the destination UL
});
});
<label for="issue">Issue Type:</label>
<select multiple="multiple" name="issue" id="issue">
<option value="passport">passport</option>
<option value="selfie">selfie</option>
<option value="nationalId">nationalId</option>
</select>
<p> you are missing the following information:</p>
<ul id="issue-type">
</ul>
Related
Here is my code for js
function addTag(tag) {
var tags = document.getElementById("tags");
var span = document.createElement("span");
span.textContent = tag.value;
tag.value = "";
span.setAttribute("onclick", "this.remove()");
tags.append(span);
}
function addOption() {
var x = document.getElementById("tag");
var option = document.createElement("option");
option.textContent = tags.textContent;
x.add(option);
}
Once the user click on the tags it will close can should display the value to the option but, I only manage to create a blank space inside the option.
Here is related JS Fiddle
Changed tags span to contain all option spans.
Then made each span inside tags responsible to add itself back to select and remove itself from tags span.
Please see the changes in the code as per above logic.
function addTag(tag) {
var tags = document.getElementById("tags");
var span = document.createElement("span");
span.textContent = tag.value;
tag.value = ""; //clear the field when choose or pressed enter key
span.style.backgroundColor = "#E5E6E7";
span.style.margin = " 5px";
span.style.padding = "5px";
//span will add itself back to select and remove itself from tags
span.setAttribute("onclick", "addOption(this)");
if (span.textContent == "Fast Food") {
$('option[value="Fast Food"]').remove();
} else if (span.textContent == "Vegan") {
$('option[value="Vegan"]').remove();
} else {
$('option[value="Food"]').remove();
}
tags.append(span);
}
function addOption(span) {
var x = document.getElementById("tag");
var option = document.createElement("option");
option.textContent = span.textContent;
x.add(option);
span.remove();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-3">
<div class="form-group">
<label class="control-label">Food Type</label><br>
<span id="tags"></span>
<select id="tag" onchange="addTag(this)" class="form-control">
<option value="">-All-</option>
<option value="Fast Food">Fast Food</option>
<option value="Vegan">Vegan</option>
<option value="Food">Food</option>
</select>
</div>
</div>
Since you're using jQuery, we can make use of the event system. This makes for cleaner code.
The main issue with your code is that you were trying to get textContent of tags which *doesn't exist as a variable. Instead it will reference the id="tags" element.
textContent only returns the text value of that element, not its children. In this case it is empty.
// here we use jQuery's event system to define what happens
// for the events below
$(document)
.on("click", ".tag", function(){
removeTag(this);
})
.on("change", "#tag", function(){
addTag(this);
});
function removeTag(tag){
addOption(tag.textContent);
tag.remove();
}
function addTag(tag) {
var tags = document.getElementById("tags"),
span = document.createElement("span");
span.textContent = tag.value;
tag.value = ""; //clear the field when choose or pressed enter key
// could you add the following styles as a class?
span.style.backgroundColor = "#E5E6E7";
span.style.margin = "5px";
span.style.padding = "5px";
span.className = "tag";
// no need to set `onclick` here as we're handling at the top of this code
// we can use the text to find the element
// instead of a repeating if else statment
$('option[value="' + span.textContent + '"]').remove();
tags.append(span);
}
function addOption(text) {
var x = document.getElementById("tag"),
option = document.createElement("option");
option.textContent = text;
// we also need to set the value here
// since we're looking for it in `addTag`
option.value = text
x.add(option);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-3">
<div class="form-group">
<label class="control-label">Food Type</label><br>
<span id="tags"></span>
<select id="tag" class="form-control">
<option value="">-All-</option>
<option value="Fast Food">Fast Food</option>
<option value="Vegan">Vegan</option>
<option value="Food">Food</option>
</select>
</div>
</div>
ES6 and improvements
$(document)
.on("click", ".tag", (event) => removeTag(event.currentTarget))
.on("change", "#tag", (event) => addTag(event.currentTarget));
function removeTag(tag){
addOption(tag.textContent);
tag.remove();
}
function addTag(tag) {
let tags = $("#tags"),
span = $('<span class="tag" />');
span.text(tag.value);
tag.value = ""; //clear the field when choose or pressed enter key
// we can use the text to find the element
// instead of a repeating if else statment
$(`option[value="${span[0].textContent}"]`).remove();
tags.append(span);
}
function addOption(text) {
let x = $("#tag"),
option = $('<option />');
option
.text(text)
.val(text);
x.append(option);
}
.tag {
background-color: #E5E6E7;
margin: 5px;
padding: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-3">
<div class="form-group">
<label class="control-label">Food Type</label><br>
<span id="tags"></span>
<select id="tag" class="form-control">
<option value="">-All-</option>
<option value="Fast Food">Fast Food</option>
<option value="Vegan">Vegan</option>
<option value="Food">Food</option>
</select>
</div>
</div>
You had made some logical mistakes,
You can update the fiddle as follows:
function addTag(tag) {
var tags = document.getElementById("tags");
var span = document.createElement("span");
span.textContent = tag.value;
span.setAttribute("onclick", "removeTag(this);");
tag.options[tag.selectedIndex].remove();
tags.append(span);
}
function removeTag(elm) {
elm.remove();
var x = document.getElementById("tag");
var option = document.createElement("option");
option.textContent = elm.textContent;
x.add(option);
}
#tags span{
background-color: #E5E6E7;
margin:5px;
padding:5px;
cursor: pointer;
}
<div class="col-sm-3">
<div class="form-group">
<label class="control-label">Food Type</label><br>
<span id="tags"></span>
<select id="tag" onchange="addTag(this)" class="form-control">
<option value="">-All-</option>
<option value="Fast Food">Fast Food</option>
<option value="Vegan">Vegan</option>
<option value="Food">Food</option>
</select>
</div>
</div>
I'm pretty new to JS, and I want to add many options to multiple select. But the problem is that when I'm trying to show them only the last record is triggering the function (showing). But when I'm doing console.log it is showing every thing perfectly.
This is my HTML:
<form class="cart" method="post" action="{{ route('cart.add') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="product_size" class="grey">Model</label>
<span class="red">*</span>
<select class="form-control" id="productModel" name="product" onchange=" addRelatedproducts();">
<option value="">Wybierz model produktu...</option>
#foreach($productModels as $productModel)
<option value="{{$productModel->id}}">{{$productModel->modelName}} - {{$productModel->modelPrice}} #if($productModel->modelPriceCurrency === 1) PLN #else EUR #endif</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="exampleSelect1">Ilość:</label>
<select class="form-control" id="exampleSelect1" name="quantity">
<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>
</select>
</div>
<div>
<div class="form-group" id="relatedProductsDiv" style="display: none;">
<label for="exampleSelect1">Produkty powiązane:</label>
<select id="select" multiple="multiple" class="relatedProducts" name="relatedProduct">
</select>
</div>
</div>
This is my JS:
function addRelatedproducts(){
var model = [
<?php foreach($productModels as $productModel):?>
<?=$productModel?>,
<?endforeach;?>
];
var relatedProducts = [
<?php foreach($relatedProductArray as $relatedProduct): ?>
<?=$relatedProduct ?>,
<?endforeach; ?>
];
var e = document.getElementById("productModel");
var selectedModelId = e.options[e.selectedIndex].value;
var select = document.getElementById("select");
for (var i = 0; i < relatedProducts.length + 1; i++) {
select.remove(relatedProducts[i].relatedProductName);
if(parseInt(relatedProducts[i].model_id) === parseInt(selectedModelId)){
console.log(relatedProducts[i])
console.log(selectedModelId)
document.getElementById("relatedProductsDiv").style.display = "";
var option = document.createElement("option");
option.value = relatedProducts[i].id;
option.text = relatedProducts[i].relatedProductName;
select.add(option);
}
else{
document.getElementById("relatedProductsDiv").style.display = "none";
}
}
}
I don't really know why it isn't working. Can anybody help me with this problem?
select.remove(relatedProducts[i].relatedProductName);
select.remove expects an option index as an argument. And I suppose when it receives a product name string (probably not a number) apparently it evaluates it as NaN and just removes the very first option in the select on every step. So it comes up with an empty select in the end.
Maybe the better approach would be to clear all the select options right before iterating relatedProducts and then to populate only with the needed ones?
while(select.options.length) {
select.remove(0);
}
for (var i = 0; i < relatedProducts.length + 1; i++) {
if(parseInt(relatedProducts[i].model_id) === parseInt(selectedModelId)){
console.log(relatedProducts[i])
// ....
Basically, I want to make a site with a button that repeatedly asks user for input. However, one of the inputs that the site asks for involves a select field and depending on the select field, have a corresponding text field appear or dissapear(values none). My javascript utilizes a for loop as the user can repeatedly press the button to add more and more select fields( and corresponding text field).
Here is jsfiddle
Below is the example code of what I'm trying to do.
HTML
<div><select class="DISPLAYTYPE" id="QBox" data-fieldtype="P">
<option value = "text">TextBox</option>
<option value = "check">CheckBox</option>
<option value = "radio">Radio</option>
</select></div>
<input type="number" min="1" value="LENGTH" class="quantumBox" id="P">
JAVASCRIPT
var textBoxList = document.getElementsByClassName("DISPLAYTYPE");
for (var i=0; i<textBoxList.length;i++){
textBoxList[i].addEventListener('change', function(){
var subParam = textBoxList[i].options[textBoxList.selectedIndex].value;
if(subParam ="text"){
//make ONLY corresponding input box appear
}else{
//make ONLY corresponding input box dissapear
}
})
};
EDIT: This is the Structure
[table id="rootPlacement"]
//insert here
[/table]
[button/] <--This will make a duplicate of invisible html and place it under invisible root
//The invisible html stuff we want to duplicate into //insert here
Given your feedback about the HTML structure in the comments, you can use the following to achieve what you are trying to. Just look into
You are trying to get the selected value inside the change event for the drop-down by using var subParam = textBoxList[i].options[textBoxList.selectedIndex].value; rather than using textBoxList[i] you can use this so that i becomes var subParam = this.options[this.selectedIndex].value.
For showing hiding the inputs you can use the function findRoot() which takes the target element object i.e ``selectand finds a parent with the class namedrootPlacement` and returns the node and then you can iterate it's children to show the selected node and hide the rest.
See a demo below
var textBoxList = document.querySelectorAll(".DISPLAYTYPE");
for (var i = 0; i < textBoxList.length; i++) {
textBoxList[i].addEventListener('change', function() {
var selectedType = this.options[this.selectedIndex].value;
let rootPlacement = findRoot(this, 'rootPlacement');
let children = rootPlacement.children;
for (var c = 0; c < children.length; c++) {
let element = children[c];
let elementType = element.type;
let isInputElement = typeof elementType !== 'undefined';
if (isInputElement) {
if (elementType == selectedType) {
element.style.display = 'inline';
} else {
element.style.display = 'none';
}
}
}
});
};
function findRoot(el, cls) {
while ((el = el.parentElement) && !el.classList.contains(cls));
return el;
}
input {
display: none;
}
<div class="rootPlacement">
<div>
<select class="DISPLAYTYPE" id="QBox1" data-fieldtype="P">
<option value="text">TextBox</option>
<option value="checkbox">CheckBox</option>
<option value="radio">Radio</option>
</select>
</div>
<input type="text" value="" class="quantumBox" id="P1">
<input type="checkbox" value="" class="quantumBox" id="q1">
<input type="radio" value="" class="quantumBox" id="r1">
</div>
<div class="rootPlacement">
<div>
<select class="DISPLAYTYPE" id="QBox2" data-fieldtype="P">
<option value="text">TextBox</option>
<option value="checkbox">CheckBox</option>
<option value="radio">Radio</option>
</select>
</div>
<input type="text" value="LENGTH" class="quantumBox" id="P2">
<input type="checkbox" value="" class="quantumBox" id="q2">
<input type="radio" value="LENGTH" class="quantumBox" id="r2">
</div>
<div class="rootPlacement">
<div>
<select class="DISPLAYTYPE" id="QBox3" data-fieldtype="P">
<option value="text">TextBox</option>
<option value="checkbox">CheckBox</option>
<option value="radio">Radio</option>
</select>
</div>
<input type="text" value="LENGTH" class="quantumBox" id="P3">
<input type="checkbox" value="" class="quantumBox" id="q3">
<input type="radio" value="LENGTH" class="quantumBox" id="r3">
</div>
how do I get my javascript to show more than one selected in de text field I am planning on adding way more 's so I don't want to make a insane long array
function myFunction() {
var skilllist = document.getElementById("skilllist");
console.log(skilllist.selectedIndex);
document.getElementById("skillfield").value = skilllist.options[skilllist.selectedIndex].text;
}
<form>
Select your favorite browser:
<select name="skillist[]" id="skilllist" multiple>
<option value="HTML">HTML</option>
<option value="CSS">CSS</option>
<option value="Javascript">Javascript</option>
<option value="PHP">PHP</option>
<option value="Laravel">Laravel</option>
<option value="Wordpress">wordpress</option>
</select>
<p>jouw skills zijn: <input type="text" id="skillfield" size="50"></p>
</form>
</div>
I suggest adding an event handler on blur event to the select element.
With such an approach you are able to select one or more list items and dynamically render their text content.
document.getElementById("skilllist").addEventListener('blur', function(e){
var options = e.target.options,
selected_content = "";
for (var i = 0; i < options.length; i++) {
if (options[i].selected) selected_content += options[i].textContent + ", ";
}
document.getElementById("skillfield").value = selected_content;
});
https://jsfiddle.net/zLyw7vhd/
For mobile devices : try to replace event name 'blur' to 'focusout'
(or 'change') in addEventListener function
I'm trying to take multiple user inputs from an HTML document and then transfer that data into a table using Javascript. Numerical data will transfer without an issue but dropdown select menus have been showing up as undefined, I've tried many different solutions I've seen on questions here but none of them have yielded any results. Any help anyone can provide would be much appreciated. Here is the relevant code...
HTML
<form class="items" action="" method="post" name="items">
<ul>
<li>
<label>Paint:</label>
<select id="paintColour">
<option value="White" selected="selected">White</option>
<option value="Blue">Blue</option>
<option value="Beige">Beige</option>
<option value="Red">Red</option>
<option value="Yellow">Yellow</option>
</select>
<select id="paintType">
<option value="Gloss">Gloss</option>
<option value="Matte">Matte</option>
<option value="Emulsion">Emulsion</option>
</select>
<input type="number" name="quantity" value="0" size="2" id="paintVolume">
<input type="button" value="Add" id="addPaint" onclick="Javascript:addPaints()">
</li>
Javascript
function addPaints(){
var paintColour = document.getElementById("paintColour").selectedIndex;
var paintType = document.getElementById("paintType").selectedIndex;
var paintVolume = document.getElementById("paintVolume");
var tblPaint = document.getElementById("tblPaint");
var paintRowCount = tblPaint.rows.length;
var paintRow = tblPaint.insertRow(paintRowCount);
paintRow.insertCell(0).innerHTML = '<input type="button" value="Delete" onClick=deletePaint(this) ">';
paintRow.insertCell(1).innerHTML = paintColour.value;
paintRow.insertCell(2).innerHTML = paintType.value;
paintRow.insertCell(3).innerHTML = paintVolume.value;
}
function deletePaint(obj){
var index = obj.parentNode.parentNode.rowIndex;
var tblPaint = document.getElementById("tblPaint");
tblPaint.deleteRow(index);
}
Your problem with select is you are selecting index and then try to get value. Instead choose element and get value.
function addPaints(){
var paintColour = document.getElementById("paintColour");
var paintType = document.getElementById("paintType");
var paintVolume = document.getElementById("paintVolume");
var tblPaint = document.getElementById("tblPaint");
var paintRowCount = tblPaint.rows.length;
var paintRow = tblPaint.insertRow(paintRowCount);
paintRow.insertCell(0).innerHTML = '<input type="button" value="Delete" onClick=deletePaint(this) ">';
paintRow.insertCell(1).innerHTML = paintColour.value;
paintRow.insertCell(2).innerHTML = paintType.value;
paintRow.insertCell(3).innerHTML = paintVolume.value;
}
function deletePaint(obj){
var index = obj.parentNode.parentNode.rowIndex;
var tblPaint = document.getElementById("tblPaint");
tblPaint.deleteRow(index);
}