how can i put a variable in formulaire option in javascript - javascript

I am trying to fill a selectlist with javascript :
for (i=0; i<10; i++)
{
formulaire.choixType[i].options.length= 10;
formulaire.choixType[i].options[i].value =i;
formulaire.choixType[i].options[i].text =i;
}
i have 10 selectlist (K from 0 to 9):
<div>
<select name="choixType[k]" id="choixType" >
<option value="" selected="selected">---choose-</option>
</select>
</button>
</div>
how can i do this , thank you for helping

I have created an exemple here: https://jsfiddle.net/xctty5bd/1/
// get select element with id 'choixType'
var select = document.getElementById('choixType');
for (var i = 0; i < 10; i++) {
// first you create the element <option></option>
var option = document.createElement('option');
// then you add value and text
option.value = i;
option.text = i;
// and then you put option at the end of your select
select.appendChild(option);
}

Related

How to create html select option menu with data from MySql database with nodeJS

How can I add values to options on select menu from MySql db with nodeJS. Instead to hard-codded below.
<select id="select_id" multiple="multiple">
<label for="one">
<option value="test">test</option>
</label>
<label for="two">
<option value="test2">test2</option>
</label>
I tried the code below but something not work.
It won't update the select menu but on console.log(select) give it me the select menu that I whant, but not in the html view
fetch('/data').then(res=>res.json()).then(data=>{
var select = document.getElementById("chkveg");
console.log(select);
for(var i = 0; i < data.length; i++)
{
var option = document.createElement("OPTION"),
txt = document.createTextNode(data[i].username);
option.appendChild(txt);
option.setAttribute("value",data[i].username);
select.insertBefore(option,select.lastChild);
}
})
with code below works fine. Two code blocks give it me same result on console.log(select)
var select = document.getElementById("chkveg"),
arr = ["html","css","java"];
for(var i = 0; i < arr.length; i++)
{
var option = document.createElement("OPTION"),
txt = document.createTextNode(arr[i]);
option.appendChild(txt);
option.setAttribute("value",arr[i]);
select.insertBefore(option,select.lastChild);
fetch('/data').then(res=>res.json()).then(data=>{
var select = document.getElementById("chkveg");
console.log(select);
for(var i = 0; i < data.length; i++)
{
var option = document.createElement("option"),
option.text = data[i].username;
option.value = data[i].username;
select.add(option, select.length-1);
}
})

Loop through a data array variable and select items from multi-select dropdown

Created a multi-select dropdown, when I click on any of the options I have a input field which stores the values in a textbox. When the page reloads- I want to reselect the values in the multi-select drop down. The text box keeps its values so i was hoping to loop through this if i put it in an array.
E.g. Text contains: "cheese,mozarella"
It is important to only check the items that have the value in the textbox
Jquery:
document.getElementById("txt1").value = "cheese,mozarella";
var data = document.getElementById("txt1").value;
var dataarray = data.split(","); //splits values (,)
console.log(dataarray);
var i;
for (i = 0; i < dataarray.length; i++) {
}
HTML:
<input type="text" runat="server" id="txt1" visible="true" value="0" />
<div class="container">
<select id="basic" multiple="multiple">
<option value="cheese">Cheese</option>
<option value="tomatoes">Tomatoes</option>
<option value="mozarella">Mozzarella</option>
<option value="mushrooms">Mushrooms</option>
<option value="pepperoni">Pepperoni</option>
<option value="onions">Onions</option>
</select>
</div>
I have a codeply to demonstrate: https://www.codeply.com/go/mCcxCM0vHs
My aim is to get some jquery code to loop through a dataarray variable and check the box if the value exists and tick it.
This function receives a select and a value and will cycle through the select's options, compare to the given value and mark matching options as selected.
function prepopulateOptions(selectElement, value) {
var options = selectElement.options;
for (var i = 0, numberOfOptions = options.length; i < numberOfOptions; i++) {
if (options[i].value == value) {
options[i].selected = true;
}
}
}
This function clears all selected options.
function clearSelect(selectElement) {
var options = selectElement.options;
for (var i = 0, numberOfOptions = options.length; i < numberOfOptions; i++) {
options[i].selected = false;
}
}
Then tweak your script:
var data = "cheese,mozarella",
dataarray = data.split(","),
selectElement = document.getElementById('basic');
// clear select first
clearSelect(selectElement);
for (var i = 0; i < dataarray.length; i++) {
prepopulateOptions(selectElement, dataarray[i]);
}
Check the fiddle
With jQuery this could be rewritten even easier:
https://jsfiddle.net/rtm0n53b/
Use the localStorage and jQuery.
<script type="text/javascript">
function fnLoadOptions(text){
//--clear selection
$('#basic option').prop("selected", false);
//--load selection
text = text||'';
var items = text.split(',');
for(var i in items) {
$('#basic option[value="'+items[i]+'"]').prop("selected", true);
}
if($.fn.multiselect!=null) {
$('#basic').multiselect('refresh'); //--if using the bootstrap multiselect plugin, then refresh it.
}
}
var key = 'checkedOptions';
//--load previous selection
var previousSelection = localStorage.getItem(key);
fnLoadOptions(previousSelection);
$("#txt1").val(previousSelection);
//--bind to new selection
$('#basic').change(function () {
var v = $('#basic').val();
$("#txt1").val(v);
localStorage.setItem(key,v);
});
$('#txt1').bind("keyup change",function () {
fnLoadOptions($(this).val());
});
</script>

Concatenating text to options with a certain data attribute value

I have a select element:
function find() {
var schoolList = document.getElementByID("schoolList");
if (schoolList.hasAttributes("[data attribute value]") {
//modify text in found option
};
};
find();
<div id="SelectWrapper" class="menu">
<form>
<select id="schoolList">
<option value='student' data-tier="student" data->Student 1</option>
<option value="teacher" data-tier="faculty" data->Teacher</option>
</form>
</div>
Using pure Javascript, I want to create an if statement within a function that checks to see if an option has an appropriate data attribute value (for instance, "student" or "faculty") and then adds to or modifies the existing innerHTML/text.
You can use querySelectorAll() to find all the options with a particular data value, then loop over them.
function find() {
var options = document.querySelectorAll("#schoolList option[data-tier=student]");
for (var i = 0; i < options.length; i++) {
options[i].innerHTML += " (something)";
}
}
The example for you
function find() {
var schoolList = document.getElementById("schoolList");
if (schoolList.hasAttributes("[data attribute value]")) {
var opts = schoolList.getElementsByTagName("option");
for (var i = 0, len = opts.length; i < len; i++) {
var option = opts[i];
// modify
if (option["data-tier"] === "student") {
option.text = "new text content"
}
}
// add new
for (var i =0; i < 5; i++) {
var opt = document.createElement("option");
opt.value = i;
opt.innerHTML = "Option " + i;
schoolList.appendChild(opt);
}
};
};
find();

How to update options of select but keep previously selected one as selected?

Here's my try on implementing this:
var select = document.getElementById(key);
var temp = select.value;
select.options.length = 0; // clear out existing items
for (var i = 0; i < data.length; i++) {
select.options.add(new Option(data.Value, data.Key))
}
select.value = temp;
In case of there is no such value anymore I would like to set some default values for selcted option.
This is a simple function called init_select
It clear the selection tag
-remembers the option that was previously selected
if the item that was previously selected item is not in the list of new options..it will select the option that you want (this is the default_opt) parameter
-if the previously item is IN the list it will ignore the default_opt paramater and use the previously selected item.
demo here (previously selected item NOT in list but default_opt is IN list)
function init_select(id,data,default_opt) {
var select = document.getElementById(id);
var temp = select.value;
select.innerHTML="";
for (var i = 0; i < data.length; i++) {
select.options.add(new Option(data[i]))
}
if (data.indexOf(temp) < 0 && data.indexOf(default_opt)>=0 ) {
select.value = default_opt;
console.log('this is select',select.value,default_opt,select);
} else if (data.indexOf(temp) >= 0){
//select.options.add(new Option(temp));
select.value = temp;
console.log(select.value,data.indexOf(temp));
}
}
init_select('key',["New Value", "New Value2", "New Value3", "New Value4"],"New Value2")
<select id="key">
<option>year1</option>
<option>year2</option>
<option>year3</option>
</select>
demo here (previously selected item IN list and default_opt is IN list, default options is ignored and the previously selected item is selected)
function init_select(id,data,default_opt) {
var select = document.getElementById(id);
var temp = select.value;
select.innerHTML="";
for (var i = 0; i < data.length; i++) {
select.options.add(new Option(data[i]))
}
if (data.indexOf(temp) < 0 && data.indexOf(default_opt)>=0 ) {
select.value = default_opt;
console.log('this is select',select.value,default_opt,select);
} else if (data.indexOf(temp) >= 0){
//select.options.add(new Option(temp));
select.value = temp;
console.log(select.value,data.indexOf(temp));
}
}
init_select('key',["New Value", "New Value2", "New Value3", "New Value4","year1"],"New Value2")
<select id="key">
<option>year1</option>
<option>year2</option>
<option>year3</option>
</select>
Your idea of getting the value of select and resetting it was right. You can achieve your wanted result with jQuery like this.
Note that if the old value is not available, select's value will be set to null.
$("button").on("click", function() {
var def = "4. Option";
var temp = $("select").val();
var select = $("select");
select.empty();
for (i = 2; i <= 10; i++) {
$("<option>").text(i + ". Option").appendTo(select);
}
select.val(temp);
if (select.val() == null)
select.val(def);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option>1. Option</option>
<option>2. Option</option>
<option>3. Option</option>
<option>4. Option</option>
<option>5. Option</option>
</select>
<button>Clear and Fill Select</button>

listbox select count not work dont work

I recently trying to make a form with multiple select box. When someone select the options the number of selected options will be display on another text. I'm a beginner in JavaScript.
The function is called, but it doesn't count the number of the selected options.
<select name="element_17_1[ ]"
size="7" multiple="multiple"
class="element select medium"
id="element_17_1[ ]"
onfocus="selectCount(this.form);"
onClick="selectCount(this.form);"
>
<option value="Opt1">Opt1</option>
<option value="Opt2">Opt2</option>
<option value="Opt3">Opt3</option>
<option value="Opt4">Opt4</option>
<option value="Opt5">Opt5</option>
<option value="Opt6">Opt6</option>
<option value="Opt7">Opt7</option>
</select>
and this is the function I tried in the <head>
function selectCount(f) {
var selObj = myForm.elements['element_17_1[]'];
var totalChecked = 0;
for (i = 0; i < selObj.options.length; i++) {
if (selObj.options[i].selected) {
totalChecked++;
}
}
f.element_9.value = totalChecked;
}
You're trying to get an element named element_17_1[], but your select box is named element_17_1[ ]. JavaScript just sees the name as a bunch of characters, and that space makes a difference.
In your HTML you have:
> <select name="element_17_1[ ]"
> size="7" multiple="multiple"
> class="element select medium"
> id="element_17_1[ ]"
> onfocus="selectCount(this.form);"
> onClick="selectCount(this.form);"
> >
Note that in the listener, this references the element itself, so just pass that:
onfocus="selectCount(this);"
onClick="selectCount(this);"
So a reference to the element is passed directly to the function, which can be:
function selectCount(selObj) {
// The following line isn't needed now
// var selObj = myForm.elements['element_17_1[]'];
var totalChecked = 0;
for (i = 0; i < selObj.options.length; i++) {
totalChecked += selObj.options[i].selected? 1 : 0;
}
// The next line needs the form, so
selObj.form.element_9.value = totalChecked;
}
Now you don't care what the select element is called. :-)
Edit
To click element_9 you might do:
<input name="element_9" onclick="
this.value = selectCount(this.form['element_17_1[ ]']);
">
Then the function is modified to:
function selectCount(selObj) {
var totalChecked = 0;
for (i = 0; i < selObj.options.length; i++) {
totalChecked += selObj.options[i].selected? 1 : 0;
}
return totalChecked;
}
Enough homework for now. ;-)
Change your select's name name="element_17_1"and id id="element_17_1" and in also you don't have myForm in your function so var selObj = myForm.elements['element_17_1']; should be var selObj = f.elements['element_17_1']; and also you can use only on event as follows
onChange="selectCount(this.form);"
instead of
onfocus="selectCount(this.form);"
onClick="selectCount(this.form);"
Complete function:
function selectCount(f) {
var selObj = f.elements['element_17_1'];
var totalChecked = 0;
for (i = 0; i < selObj.options.length; i++) {
if (selObj.options[i].selected) {
totalChecked++;
}
}
f.element_9.value = totalChecked;
}
Update:
For your php scriptyou can keep your select's name name="element_17_1[]" and so in the function it should be var selObj = f.elements['element_17_1[]']; but without space like[ ]
DEMO.

Categories