Change position of an option using JavaScript - javascript

I have a dropdown list with several options and now I want to insert a new option to the top of the list. How do I do that?
function insertOptionAll (DOMtarget)
{
var option = document.createElement("option");
option.text = "Some option";
option.value = 0;
option.title = "Some option";
DOMtarget.add(option); //appends to the end
//DOMtarget.options[DOMtarget.options.length - 1].index = 0; --> doesnt work
}

Try ...
DOMtarget.insertBefore(option, DOMtarget.options[0]);
See: Add new <option> to all dropdown <select> tags using javascript

function insertOption(selectId) {
var selectList = document.getElementById(selectId);
var option = document.createElement("option");
option.text = "Some option";
option.value = 0;
option.title = "Some option";
selectList.insertBefore(option, selectList.options[0]);
}

Related

How can I load this select input field with options passed using JS?

When loading an HTML table, there is this select input field, which should make available some options.
Right after the HTML table row is built, I'm calling a function, which should populate this input field, getting it by its class.
Here is the HTML piece and the function:
function loadTelaOptions(telaOptions) {
telaOptions = ["09-Black", "11-LT Jaspe"]; //Here for tests
document.querySelector('tableBodySelect').value = '';
let selectList = document.querySelector('tableBodySelect');
let options = selectList.getElementsByTagName('option');
for (let i = options.length; i--;) {
selectList.removeChild(options[i]);
}
let option = document.createElement("option");
option.value = "";
option.text = "";
selectList.appendChild(option);
telaOptions.forEach(function(item, index) {
let option = document.createElement("option");
option.value = item.toLowerCase();
option.text = item;
selectList.appendChild(option)
});
}
<td>
<select name='tableselect' required='required' class='tableBodySelect' value='Trying'>
</select>
</td>
Appreciate any help!
Your selectors for .querySelector('tableBodySelect') doesn't match your desired elements. You try to match the classes, therefore you need to prepend a . to your selector .querySelector('.tableBodySelect')
This does already resolve your issue.
function loadTelaOptions(telaOptions) {
telaOptions = ["09-Black", "11-LT Jaspe"]; //Here for tests
document.querySelector('.tableBodySelect').value = '';
let selectList = document.querySelector('.tableBodySelect');
let options = selectList.getElementsByTagName('option');
for (let i = options.length; i--;) {
selectList.removeChild(options[i]);
}
let option = document.createElement("option");
option.value = "";
option.text = "";
selectList.appendChild(option);
telaOptions.forEach(function(item, index) {
let option = document.createElement("option");
option.value = item.toLowerCase();
option.text = item;
selectList.appendChild(option)
});
}
loadTelaOptions();
<td>
<select name='tableselect' required='required' class='tableBodySelect' value='Trying'>
</select>
</td>

Get values of multiple select boxes in PHP and add them to an array

I have a button which allows an ingredient to be added to a database. When the button is clicked, the user can add the name, measurement and unit for the ingredient which is done using Javascript:
function addIngredient() {
var area = document.getElementById("addedIngredient");
var num = document.createElement("p");
numText = document.createTextNode(countIngredient + ". ");
num.appendChild(numText);
area.appendChild(num);
//Ingredient Name
var ingredientNameLabel = document.createElement("p");
ingredientNameLabelText = document.createTextNode("Name");
ingredientNameLabel.appendChild(ingredientNameLabelText);
area.appendChild(ingredientNameLabel);
countIngredient++;
var ingredientNameInput = document.createElement("INPUT");
ingredientNameInput.setAttribute("name", "ingredient_name[]");
ingredientNameInput.setAttribute("type", "text");
ingredientNameInput.setAttribute("class", "form-control");
ingredientNameInput.setAttribute("class", "ingName");
area.appendChild(ingredientNameInput);
//Ingredient Measure
var ingredientMeasureLabel = document.createElement("p");
ingredientMeasureLabelText = document.createTextNode("Measure");
ingredientMeasureLabel.appendChild(ingredientMeasureLabelText);
area.appendChild(ingredientMeasureLabel);
var ingredientMeasureInput = document.createElement("INPUT");
ingredientMeasureInput.setAttribute("name", "ingredient_measure[]");
ingredientMeasureInput.setAttribute("type", "text");
ingredientMeasureInput.setAttribute("class", "form-control");
ingredientMeasureInput.setAttribute("class", "ingMeasure");
area.appendChild(ingredientMeasureInput);
//Ingredient Unit
var ingredientUnitLabel = document.createElement("p");
ingredientUnitLabelText = document.createTextNode("Unit");
ingredientUnitLabel.appendChild(ingredientUnitLabelText);
area.appendChild(ingredientUnitLabel);
var select = document.createElement("SELECT");
select.setAttribute("name", "ingredient_unit[]");
area.appendChild(select);
var option = document.createElement("option");
option.setAttribute("value", "grams");
var value = document.createTextNode("g");
option.appendChild(value);
select.appendChild(option);
var option = document.createElement("option");
option.setAttribute("value", "milimeters");
var value = document.createTextNode("ml");
option.appendChild(value);
select.appendChild(option);
var option = document.createElement("option");
option.setAttribute("value", "kilograms");
var value = document.createTextNode("kg");
option.appendChild(value);
select.appendChild(option);
var option = document.createElement("option");
option.setAttribute("value", "litres");
var value = document.createTextNode("litre(s)");
option.appendChild(value);
select.appendChild(option);
var option = document.createElement("option");
option.setAttribute("value", "slice");
var value = document.createTextNode("slice");
option.appendChild(value);
select.appendChild(option);
var option = document.createElement("option");
option.setAttribute("value", "whole");
var value = document.createTextNode("whole");
option.appendChild(value);
select.appendChild(option);
var option = document.createElement("option");
option.setAttribute("value", "pinch");
var value = document.createTextNode("pinch");
option.appendChild(value);
select.appendChild(option);
}
I am looking to get the unit selected for every ingredient added.
Can anyone tell me how I could do this using PHP?
I am trying the following way:
$units = [];
foreach ($_POST["ingredient_unit[]"] as $key => $unit) {
array_push($units, $unit);
}
This does not work nor does it give an error.
Thanks.
Change the following code:
foreach ($_POST["ingredient_unit[]"] as $key => $unit) {
array_push($units, $unit);
}
And use this instead:
foreach ($_POST["ingredient_unit"] as $key => $unit) {
array_push($units, $unit);
}
And you should be getting a notice when you try to access $_POST["ingredient_unit[]"] since its not defined. If you are not seeing a notice, maybe the error_reporting level is too low. You could use something like the following to active all errors except the deprecated ones:
error_reporting(E_ALL &~ E_DEPRECATED);

Replacing option in select field (not adding)

I have a select field as follows:
<select id="field">
I add options based on values found in another div (OtherDiv) on my page like this:
window.onload = function onload()
{
var OtherDiv = document.getElementById('OtherDiv').innerHTML;
var result = OtherDiv.match(/SomeRegex/gi);
var select = document.getElementById("field");
for(var i = 0; i < result.length; i++)
{
var option = document.createElement("option");
option.value = i+1;
option.innerHTML = result[i];
select.add(option);
}
}
However, I would like to set up some alternative value for the field to show, if there are no matches to the regex. How would I best achieve that?
Use if condition
window.onload = function onload()
{
var OtherDiv = document.getElementById('OtherDiv').innerHTML;
var result = OtherDiv.match(/SomeRegex/gi);
var select = document.getElementById("field");
if(result.length){
for(var i = 0; i < result.length; i++)
{
var option = document.createElement("option");
option.value = i+1;
option.innerHTML = result[i];
select.add(option);
}
}else{
//add alternative options here
var option = document.createElement("option");
option.innerHTML = "No records found"; //whatever text you want to show
select.add(option);
}
}

Creating elements in javascript and appending them to the DOM

Here's a couple of small questions that I need help with...
I am trying to add multiple values to the select/option form but when I do that the javascript function ends up only adding the last one - here are the details for you to check out -
function addFields1(){
var container = document.getElementById("container1");
container.appendChild(document.createTextNode("Institution Name: "));
var name = document.createElement("input");
name.type = "text";
name.id = "name";
name.name = "certificate";
name.size = 25;
name.maxlength = 25;
container.appendChild(name);
var select = document.createElement("select"); //? how do I fix this up
var option = document.createElement("option");
option.value = "College";
option.innerHTML = "College";
option.value = "Community College";
option.innerHTML = "Community College";
option.value = "High School";
option.innerHTML = "High School";
option.value = "Private";
option.innerHTML = "Private";
option.value = "University";
option.innerHTML = "University";
select.appendChild(option);
container.appendChild(select);
}
When I call the function the only value that shows up is the very last one ("University") - the remaining values are not even on the menu when it drops down.
Another (similar) problem I am having is appending <td> and <input> elements and not being able to print any data when the eventhandler is called -
Here's the code for that below -
function aFields1(){
var container1 = document.getElementById("container");
container1.appendChild(document.createTextNode("Company: "));
var td = document.createElement("td");
var company = document.createElement("input");
company.type = "text";
company.id = "company";
company.name = "company";
company.size = 15;
company.maxlength = 15;
td.appendChild(company);
container1.appendChild(td);
container1.appendChild(company);
}
When i remove the td variable and td element, the information prints properly but if I don't do that it doesn't show up at all! Is there something wrong with what I did in this second function?
With the option elements you actually need to re-run the document.createElement('option') otherwise javascript retains a reference to the originally added option element and only updates it (rather than appending a new element). This allows us to re-use the option variable.
The issue with the <td> element is similar... this line container1.appendChild(company); moves the company input element outside of the td element and into the container1 element.
I have cleaned up and fixed both of your functions:
function addFields1() {
var container = document.getElementById("container1");
container.appendChild(document.createTextNode("Institution Name: "));
var name = document.createElement("input");
name.type = "text";
name.id = "name";
name.name = "certificate";
name.size = 25;
name.maxlenth = 25;
container.appendChild(name);
//create select element and the option variable
var select = document.createElement("select");
var option;
//before each option element we reassign the option variable to a new option element and append it to the select before moving to the next option item
option = document.createElement("option");
option.value = "College";
option.innerHTML = "College";
select.appendChild(option);
option = document.createElement("option");
option.value = "Community College";
option.innerHTML = "Community College";
select.appendChild(option);
option = document.createElement("option");
option.value = "High School";
option.innerHTML = "High School";
select.appendChild(option);
option = document.createElement("option");
option.value = "Private";
option.innerHTML = "Private";
select.appendChild(option);
option = document.createElement("option");
option.value = "University";
option.innerHTML = "University";
select.appendChild(option);
//finally, we append the completed select element
container.appendChild(select);
}
function aFields1() {
var container1 = document.getElementById("container");
container1.appendChild(document.createTextNode("Company: "));
var td = document.createElement("td");
var company = document.createElement("input");
company.type = "text";
company.id = "company";
company.name = "company";
company.size = 15;
company.maxlenth = 15;
//append the company input element to the td element
td.appendChild(company);
//append the td element to the container1 element
container1.appendChild(td);
}
JSFIDDLE DEMO

Auto populate option tag not working java script

I'm trying to populate number in select - option tag .But my script fills number at only one select tag
HTML :
<div class="form_row">
<label>Week Num</label>
<select class="form_select1" id="weeknum"></select>
<b class="bold1">&nbsp TO &nbsp</b>
<select class="form_select1" id="weeknum1"></select>
</div>
Javascript :
<script>
var select = document.getElementById("weeknum");
var select1 = document.getElementById("weeknum1");
for (var i = 52; i >= 1; i--) {
var option = document.createElement('option');
option.text = option.value = i;
select.add(option, 0);
select1.add(option, 0);
}
</script>
How do i achieve that ?
You can add an element only once to a parent node, so you need to create another option element:
var select = document.getElementById("weeknum");
var select1 = document.getElementById("weeknum1");
for (var i = 52; i >= 1; i--) {
var option = document.createElement('option');
option.text = option.value = i;
var option1 = document.createElement('option');
option1.text = option1.value = i;
select.add(option, 0);
select1.add(option1, 0);
}
Here's the JSFIddle.
Try this ...
var option1 = document.createElement('option');
option1.text = option1.value = i;
select.add(option1, 0);
var option2 = document.createElement('option');
option2.text = option2.value = i;
select1.add(option2, 0);
... creating a distinct "option" for each select list. The created elements cannot be reused.
You need to create a distinct option element for each list. A given DOM element can only be in one place in the DOM.
edit: I see it's already answered... well, my first answer :)
try this:
var select = document.getElementById("weeknum");
var select1 = document.getElementById("weeknum1");
for (var i = 52; i >= 1; i--) {
var option = document.createElement('option');
var option1 = document.createElement('option');
option.text = option.value = option1.text = option1.value = i;
select.add(option, 0);
select1.add(option1, 0);
}

Categories

Resources