Problem while adding many options to multiple select js - javascript

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])
// ....

Related

Select another dropdown value based on the previous dropdown selection

I am new to html javascript and trying to learn it. I am having an issue that when I select a value of a dropdown it will select another dropdown value when certain criteria matches.
If they Select the option 4 (takeout) from service_type dropdown, the counter dropdown will automatically selected the option 2 driveway. else user are free to select any value on both dropdown. Only if they select Takeout, it will make driveway selected and also make the table service option inactive.
if they select 1,2 or 3 from the Service type dropdown then option 1 will be enabled.
I need a javascript and no jquery. Please help me
<div class="form-group col-md-12">
<select name="service_type" id="service_type" class="form-control form-control-line" required>
<option value="" selected="selected" >Select Service</option>
<option value="1">Dining</option>
<option value="2">Beverages</option>
<option value="3">Liquor</option>
<option value="4">Takeout</option>
</select>
</div>
<div class="form-group col-md-12">
<select name="counter" id="counter" class="form-control form-control-line" required>
<option value="" selected="selected" >Select Counter</option>
<option value="1">Table Service</option>
<option value="2">Driveway</option>
</select>
</div>
You can use javascript like this:
function Checker(el){
const select = document.getElementById('counter');
removeOptions(select);
if(el.value == '4'){
var option1 = document.createElement("option");
option1.text = "Driveway";
option1.value = "2";
select.add(option1);
}else{
var option2 = document.createElement("option");
option2.text = "Table Service";
option2.value = "1";
select.add(option2);
var option1 = document.createElement("option");
option1.text = "Driveway";
option1.value = "2";
select.add(option1);
}
}
function removeOptions(selectElement) {
var i, L = selectElement.options.length - 1;
for (i = L; i >= 0; i--) {
selectElement.remove(i);
}
}
<div class="form-group col-md-12">
<select name="service_type" id="service_type" class="form-control form-control-line" onChange="Checker(this)" required>
<option value="" selected="selected" >Select Service</option>
<option value="1">Dining</option>
<option value="2">Beverages</option>
<option value="3">Liquor</option>
<option value="4">Takeout</option>
</select>
</div>
<div class="form-group col-md-12">
<select name="counter" id="counter" class="form-control form-control-line" required>
<option value="" selected="selected" >Select Service Fist</option>
</select>
</div>
Create two function one for create option base to first choise and second for remove option everytime function is called.
const firstSelect = document.querySelector('#serviceType');
const secondSelect = document.querySelector('#counter');
firstSelect.addEventListener('change', (event) => {
if (event.target.value === '4') {
secondSelect.value = '2';
secondSelect.disabled = true;
} else if (typeof event.target.value === 'string' && event.target.value.length > 0) {
secondSelect.disabled = false;
secondSelect.value = '1';
} else {
secondSelect.disabled = false;
secondSelect.value = '';
}
});
<div class="form-group col-md-12">
<select name="service_type" id="serviceType" class="form-control form-control-line" required>
<option value="" selected="selected" >Select Service</option>
<option value="1">Dining</option>
<option value="2">Beverages</option>
<option value="3">Liquor</option>
<option value="4">Takeout</option>
</select>
</div>
<div class="form-group col-md-12">
<select name="counter" id="counter" class="form-control form-control-line" required>
<option value="" selected="selected" >Select Counter</option>
<option value="1">Table Service</option>
<option value="2">Driveway</option>
</select>
</div>
How does it work?
You need to select your Select controls from DOM and then listen to change event on first select, then you can get value from it and depending on your choice change value of Select #2. In order to disable ability to choose another option in second dropdown, you can disable it.

how to make an input column readonly while selecting some option?

Change input table to be "readonly" while select option matches the keyword. I just want to disable certain tabs while selecting a keyword.
script:
<script>
function block_SN(){
var selects = document.querySelectorAll("select[id=select_host]");
var serials = document.querySelectorAll("select[id=serial_number]");
for (var index = 0; index < selects.length -1; index++) {
if (selects[index].value.match(/keyword/))
serials[index].readOnly = true;
}
}
</script>
HTML:
<div class="form-group">
<input id="serial_number" name="serial_number" value="{{entry.serial_number}}" >
</div>
</td>
<td>
<div class="form-group">
<select id="select_host" name="select_host" class="selectpicker form-control" value="{{entry.hostname}}" onChange="this.form.submit();block_SN()">
{% for entry in hosts %}
<option value="{{entry.hostname}}">{{entry.hostname}}</option>
{% endfor %}
<option selected="selected">{{entry.hostname}}</option>
</select>
</div>
</td>
querySelectorAll should be perform either on tag or class.....but here in your code your performing on id(every html tag can have unique id)....
Add class to your input and select box serial_number and select_host respectively(you can also use name based querySelectorAll).
<script>
function block_SN(){
var selects = document.querySelectorAll(".select_host");**//changed**
var serials = document.querySelectorAll(".serial_number");**//changed**
for (var index = 0; index < selects.length -1; index++) {
if (selects[index].value.match(/keyword/))
serials[index].readOnly = true;
}
}
</script>
<div class="form-group">
<input id="serial_number" class="serial_number" name="serial_number" value="{{entry.serial_number}}" ><!-- added class serial_number-->
</div>
</td>
<td>
<div class="form-group">
<!-- added class select_host -->
<select class="select_host" id="select_host" name="select_host" class="selectpicker form-control" value="{{entry.hostname}}" onChange="this.form.submit();block_SN()">
{% for entry in hosts %}
<option value="{{entry.hostname}}">{{entry.hostname}}</option>
{% endfor %}
<option selected="selected">{{entry.hostname}}</option>
</select>
</div>
</td>
For this HTML Code is like:
<select id="sel_id">
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
<option value="four">Four</option>
</select>
<input type = "text" id = "text1" />
And JS Code is like this:
$(document).ready(function () {
$("#sel_id").change(function () {
var x = $(this).val();
alert("Selected Option other than Three. Input Box is still not Disabled");
alert($(this).val());
if (x == "three") {
alert("Selected Option Three. Input Box is now Disabled");
$(text1).attr("disabled", true);
}
});
});
Here, When the "Three" Option from select is selected then only Input TextBox is disabled.
Update 1: Use onchange="myFunction()" Event on select to get realtime change in Textbox.

How to fix 'script should create dropdown options for each class 'list' '

I'm creating a script in a html form for adding options to a dropdown but it won't work. Why it's not working ?
I first tried to work with 'getElementByID' and the option got added to the dropdown after submit.
But i wanted the new added option in more than 1 dropdown so I changed the 'id' to 'class' and 'getElementByID' to 'getElementsbyClassName' and now it stopped working. Im unsure about the new added for loop because it worked before.
window.onload = function newoption(a) {
var x = document.getElementsByClassName("list");
var i;
for (i; i < x.length; i++) {
var option = document.createElement("option");
option.text = a;
option.value = a;
x[i].add(option);
}
}
<form action="settings.html" method="GET" name="settings" onsubmit="newoption(add.value); return false;">
<select class="list">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<input name="add" id="add" placeholder="new option">
<button type="submit">add option</button>
</form>
I expected to get a new drop down option but when I enter a text in the input field and press submit I do not get a new option.
Also should be the new entered option appear in all drop downs(not all dropdown's shown here! I have three where it should appear).
I hope I got your requirements right.
You don't need onload -- in fact, you don't even need to submit the form (redirect to another page) if you just want to add options to your dropdown. I made that your form doesn't submit anymore. I achieved that by replacing type="submit" to type="button" inside your button. I also removed unnessecary code from your form.
You need to assign a value to your variable i. Otherwise your loop won't even start because the condition (i < x.length) will always be false.
Either do var i = 0; or for (var i = 0; ...).
function newoption(a) {
var x = document.getElementsByClassName("list");
var i = 0;
for (i; i < x.length; i++) {
var option = document.createElement("option");
option.text = a;
option.value = a;
x[i].add(option);
}
}
<form action="settings.html" method="GET" name="settings">
<select class="list">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<input name="add" id="add" placeholder="new option">
<button type="button" onclick="newoption()">add option</button>
</form>
The value of your new option will be undefined all the time because your parameter a doesn't have any value.
If you want the text that got typed into your input field to be the text of your new option, you can do it by getting the value of your input when running your function:
var newText = document.getElementById('add').value;
All together:
function newoption() {
var x = document.getElementsByClassName("list");
var i = 0;
for (i; i < x.length; i++) {
var newText = document.getElementById('add').value;
var option = document.createElement("option");
option.text = newText;
option.value = newText;
x[i].add(option);
}
}
<form action="settings.html" method="GET" name="settings">
<select class="list">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<input name="add" id="add" placeholder="new option">
<button type="button" onclick="newoption()">add option</button>
</form>

Pass dropdown values to text box with javascript

I don't know much about javascript and unfortunately don't have time to learn before this project is due (wish I did!). I assume it is possible to pass the value of a drop-down selection into a hidden text input field on a form before the form is submitted. Could anyone help me figure out how to do that with javascript? Thank you! Here are my drop-down and text box details:
<div class="formEntryArea">
<div class="formEntryLabel">
<span class="formLabel"><label for=" langdropdown">Would you like to receive library notices in English or Spanish? ><span class="formRequired">*</span></label></span>
</div>
<div class="formMultiSelect" id=”langdropdown”>
<select name=" langdropdown ">
<option value="0" selected="selected">Choose language</option>
<option value="eng">English</option>
<option value="spa">Spanish</option>
<input type="text" id="ddepartment" name="ddepartment" value=””>
</select>
</div>
This is simply. First of all, you have to bind a change event handler for your select. Then, you have to set input text with value selected from dropdown.
var select=document.getElementsByTagName('select')[0];
var input=document.getElementById('ddepartment');
select.onchange=function(){
input.value=select.options[select.selectedIndex].text;
}
<div class="formEntryArea">
<div class="formEntryLabel">
<span class="formLabel"><label for=" langdropdown">Would you like to receive library notices in English or Spanish? ><span class="formRequired">*</span></label></span>
</div>
<div class="formMultiSelect" id=”langdropdown”>
<select name=" langdropdown ">
<option value="0" selected="selected">Choose language</option>
<option value="eng">English</option>
<option value="spa">Spanish</option>
</select>
<input type="text" id="ddepartment" name="ddepartment">
</div>
You can use this code:
var myselect = document.getElementById("MySelect");
myselect.onchange = function(){
alert(myselect.options[myselect.selectedIndex].value);
document.getElementById("ddepartment").value = myselect.options[myselect.selectedIndex].value;
};
Result: https://jsfiddle.net/fh5myefw/
Mind to close the tags, it's better practice.
var select = document.getElementById('selectElem');
var outputElem = document.getElementById('ddepartment');
select.addEventListener('change',function(){
var newValue = !this.selectedIndex ? "":this.options[this.selectedIndex].text;
outputElem.value = newValue;
});
<select name="langdropdown" id="selectElem" required>
<option value="" selected="selected">Choose language</option>
<option value="eng">English</option>
<option value="spa">Spanish</option>
</select>
<input type="text" id="ddepartment" name="ddepartment" value="">
this is javascript function
function func(selectObject)
{
document.getElementById('ddepartment').value = selectObject.value;
}
add onchange event to select element like this
<select name="langdropdown" onchange="func(this)">
Here use this:
var sel = document.getElementById('lang');
sel.onchange = function() {
var val = this.options[this.selectedIndex].value;
var che = document.getElementById('cache').value;
che = val;
console.log(che);
}
SNIPPET
var sel = document.getElementById('lang');
sel.onchange = function() {
var val = this.options[this.selectedIndex].value;
var che = document.getElementById('cache').value;
che = val;
console.log(che);
}
<select id='lang' name="lang">
<option value="" selected>Choose language</option>
<option value="eng">English</option>
<option value="spa">Spanish</option>
<option value="jpn">Japanese</option>
<option value="zho">Chinese</option>
<option value="fin">Finnish</option>
<option value="nav">Navajo</option>
</select>
<input type="hidden" id="cache" name="cache" value=””>

div inside form not being 'seen'

I have a div inside my form which is filled with a field based on the value of the select box above it. This field always comes back as 'null' when submitted, I put a div around other parts of the form to test if it was in fact the div itself and each field with a div around it kept coming back as 'null'.
<form>
<span id="writenode"></span>
<input type="button" value="Add language" onClick="addlanguage()" >
<input type="submit" value="Submit" >
</form>
<!--This div below is called every time I want to add a new 'instance' of this form
this div works fine, its when i add a div inside that one I get 'null'-->
<div id="readnode" style="display: none">
<select name="rank">
<option disabled="disabled" selected="selected">Rating</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
<option value="0">0</option>
</select>
<select name="time">
<option disabled="disabled" selected="selected">Time</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
<option value="0">0</option>
</select>
<input type="button" value="X"
onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />
</div>
So the code above works fine its when i add a div inside i get 'null' like below;
<form>
<span id="writenode"></span>
<input type="button" value="Add language" onClick="addlanguage()" >
<input type="submit" value="Submit" >
</form>
<!--This div below is called every time I want to add a new 'instance' of this form
this div works fine, its when i add a div inside that one I get 'null'-->
<div id="readnode" style="display: none">
<select name="rank">
<option disabled="disabled" selected="selected">Rating</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
<option value="0">0</option>
</select>
<div id='testdiv'>
<select name="time">
<option disabled="disabled" selected="selected">Time</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
<option value="0">0</option>
</select>
</div>
<input type="button" value="X"
onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />
</div>
Whats my best way around this? and how would I go about doing it?
EDIT: The Div 'readnode' is called and placed inside the form when needed, replacing the div 'writenode' which is seen inside the form above. This div works perfectly fine. When i add another div (testdiv) inside the 'readnode' any fields placed inside the new div (testdiv) always come back as null when using $_get.
EDIT2:
Function that puts the readnode in place of the writenode,
<script type="text/javascript">
/* Set the counter that will increase every time
the user adds a new language*/
var counter = 0;
function addlanguage()
{
// Ask the user for input
var language = prompt("Language Name","");
if (language == "" || language == null)
{
alert("Please enter a language.");
}
else
{
counter++;
// Find the element to be copied
var newNode = document.getElementById('readnode').cloneNode(true);
newNode.id = '';
newNode.style.display = 'block';
var newField = newNode.childNodes;
// Give all fields a unique value
for (var i=0;i<newField.length;i++)
{
var theName = newField[i].name;
var theId = newField[i].id;
if (theName)
{
newField[i].name = theName + counter;
}
if (theId == "languagename")
{
// Change the field to the user input
newField[i].innerHTML = language;
}
if (theName == "lang")
{
// Replace the hidden field with the correct language
newField[i].value = language;
}
}
// Insert the elements
var insertHere = document.getElementById('writenode');
insertHere.parentNode.insertBefore(newNode,insertHere);
}
}
</script>
and this is the php;
<?php
if ($_GET["time1"] == null)
{ ?>
<form>
<span id="writenode"></span>
<input type="button" value="Add language" onClick="addlanguage()" >
<input type="submit" value="Submit" >
</form>
<?php
}
else
{
$final = 0;
$i = 1;
while($final == 0)
{
$gettime = "time" . $i;
$getRank = "rank" . $i;
$time = $_GET[$gettime];
$rank = $_GET[$getRank];
if ($language == "")
{
$final = 1;
}
if ($final == 0)
{
// Show the user the input
echo("<p>Your <strong>$time</strong> is <strong>$rank</strong>.</p>");
}
$i++;
}
} ?>
When you put it inside a div, it's no longer part of newNode.childNodes, so you never get to set the name properly. You'll have to check childs of childs or use jQuery to simplify things.
for (var i=0;i<newField.length;i++)
{
var subField = newField.childNodes;
for (var i=0;i<subField.length;i++) {
var theName = subField[i].name;
var theId = subField[i].id;
// ...
}
}

Categories