update existing option in select list - javascript

Let's say that I have select list with 3 options inside:
<select>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
Now, I want to update one of these options, so i create textfield & button.
The option appear inside the textfield everytime i press on one of the options at the select list.
Can someone direct me what do i need to do?
thanks

Adding up to the first example that we had this morning jsfiddle
HTML:
<select id='myselect'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
</select>
<input type='text' value='1' name='mytext' id='mytext' />
<button value='add' id='addbtn' name='addbtn'>add</button>
<button value='edit' id='editbtn' name='editbtn'>edit</button>
<button value='delete' id='deletebtn' name='deletebtn'>delete</button>
JavaScript:
var myselect = document.getElementById('myselect');
function createOption() {
var currentText = document.getElementById('mytext').value;
var objOption = document.createElement("option");
objOption.text = currentText;
objOption.value = currentText;
//myselect.add(objOption);
myselect.options.add(objOption);
}
function editOption() {
myselect.options[myselect.selectedIndex].text = document.getElementById('mytext').value;
myselect.options[myselect.selectedIndex].value = document.getElementById('mytext').value;
}
function deleteOption() {
myselect.options[myselect.selectedIndex] = null;
if (myselect.options.length == 0) document.getElementById('mytext').value = '';
else document.getElementById('mytext').value = myselect.options[myselect.selectedIndex].text;
}
document.getElementById('addbtn').onclick = createOption;
document.getElementById('editbtn').onclick = editOption;
document.getElementById('deletebtn').onclick = deleteOption;
myselect.onchange = function() {
document.getElementById('mytext').value = myselect.value;
}
Basically i added an edit field that when clicked it'll edit the value and text of the currently selected option, and when you select a new option it'll propogate the textfield with the currently selected option so you can edit it. Additionally, i also added a delete function since i figure you might need it in the future.

Use jquery :selected selector and val() method.
$('select:selected').val($('input_textbox').val());

First of all always give an ID to your input tags. For eg in this case you can do something like: <select id='myDropDown'>
Once you have the ID's in place its simple matter of picking up the new value from textbox and inserting it into the dropdown:
Eg:
// Lets assume the textbox is called 'myTextBox'
// grab the value in the textbox
var textboxValue = document.getElementById('myTextBox').value;
// Create a new DOM element to be inserted into Select tag
var newOption = document.createElement('option');
newOption.text = textboxValue;
newOption.value = textboxValue;
// get handle to the dropdown
var dropDown = document.getElementById('myDropDown');
// insert the new option tag into the dropdown.
try {
dropDown.add(newOption, null); // standards compliant; doesn't work in some versions of IE
}
catch(ex) {
dropDown.add(newOption); // IE only
}

Below is a pure js example using your markup.
EDIT
After rereading your question Im not sure if you wanted the option to update when a user clicked the button or not.. To just put the option into an input you can do this.
var select = document.getElementsByTagName("select")[0],
input = document.getElementById("inputEl");
select.onchange = function(){
input.value = this[this.selectedIndex].text;
}
To update the option to what the user typed in is below.
http://jsfiddle.net/loktar/24cHN/6/
Markup
<select>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<br/>
<input type="text" id="inputEl"/>
<button id="button">Update</button>
Javascript
var select = document.getElementsByTagName("select")[0],
input = document.getElementById("inputEl"),
button = document.getElementById("button");
select.onchange = function(){
input.value = this[this.selectedIndex].text;
var selected = this,
selectedIndex = this.selectedIndex;
button.onclick = function(){
selected[selectedIndex].text = input.value;
}
}

Related

how to fill two or more selects with the same option elements

I'd like to add the same options elements to more than one select, using one JavaScript function.
<select id="select1" name="select1"></select>
<select id="select2" name="select2"></select>
I want selects become:
<select id="select1" name="select1">
<option value="0">Txt1</option>
<option value="1">Txt2</option>
<option value="2">Txt3</option>
</select>
<select id="select2" name="select2">
<option value="0">Txt1</option>
<option value="1">Txt2</option>
<option value="2">Txt3</option>
</select>
Here is part of function to fill selects with options:
function window_onload(){
var SpecTxt = new Array("Txt1","Txt2","Txt3");
for(var i=0; i<SpecTxt.length; i++) {
var oOption = document.createElement("OPTION");
oOption.text = SpecTxt[i];
oOption.value=i;
select1.add(oOption); // Option to first SELECT
select2.add(oOption); // Option to second SELECT
}
}
But I've got Internet Explorer Script Error "Invalid argument", result is only one first option in "select1" and no options in "select2". If I remove from function window_onload() the last string select2.add(oOption);, there are no IE errors and "select1" is filled as must be, but "select2" is empty. How is it possible in JS to add the same options to different SELECTs?
Update
The reason why the Demo didn't work for IE is because it doesn't recognize the property .valueAsNumber.
From:
var opts = qty.valueAsNumber;
To:
var opts = parseInt(qty.value, 10);
When you create an option within the loop:
var oOption = document.createElement("OPTION");
That is only one <option> not two <option>s. So that is the reason why:
select1.add(oOption); // Succeeds
select2.add(oOption); // Fails
You can either make 2 <option>s per loop:
var oOption1 = document.createElement("OPTION");
var oOption2 = document.createElement("OPTION");
OR try cloneNode(). See Demo below:
Demo
// See HTMLFormControlsCollection
var form = document.forms.ui;
var ui = form.elements;
var qty = ui.qty0;
var s0 = ui.sel0;
var s1 = ui.sel1;
// Declare a counter variable outside of loop
var cnt = 0;
// Add event handler to the change event of the input
qty.onchange = addOpt;
/* Get the value of user input as a number
|| within the for loop...
|| create an <option> tag...
|| add text to it with an incremented offset...
|| add a incremented value to it...
|| then clone it...
|| add original <option> to the first <select>...
|| add duplicate <option> to the second <select>
*/
function addOpt(e) {
var opts = parseInt(qty.value, 10);
for (let i = 0; i < opts; i++) {
var opt = document.createElement('option');
opt.text = 'Txt' + (cnt + 1);
opt.value = cnt;
var dupe = opt.cloneNode(true);
s0.add(opt);
s1.add(dupe);
cnt++;
}
}
input,
select,
option {
font: inherit
}
input {
width: 4ch;
}
<form id='ui'>
<fieldset>
<legend>Enter a number in the first form field</legend>
<input id='qty0' name='qty0' type='number' min='0' max='30'>
<select id="sel0" name="sel0"></select>
<select id="sel1" name="sel1"></select>
</fieldset>
</form>
Reference
HTMLFormControlsCollection

How to populate select options from an array based on a select value?

Trying to get my second select element's options to populate from an array based on the value of the first select element. I can't seem to understand why it only populates the items from the array of the first select element. I know the appendChild is causing the items to keep tacking on at the need, but I've tried to clear the variables, but it seems the option elements that were created stay.
Any help would be great, thanks!
<select id="makeSelect" onChange="modelAppend()">
<option value="merc">Mercedes</option>
<option value="audi">Audi</option>
<option value="bmw">BMW</option>
</select>
<select id="modelSelect">
</select>
<script>
var audiModels = ["TT", "R8", "A4", "A6"]; //audimodels
var mercModels = ["C230", "B28", "LTX",]; //mercmodels
var bmwModels = ["328", "355", "458i",]; //bmwmodels
var selectedMake = document.getElementById("makeSelect"); //grabs the make select
var selectedModel = document.getElementById("modelSelect"); //grabs the model select
var appendedModel = window[selectedMake.value + "Models"]; // appends "Models" to selectedMake.value and converts string into variable
function modelAppend() {
for (var i = 0; i < appendedModel.length; i ++) { // counts items in model array
var models = appendedModel[i]; // // sets "models" to count of model array
var modelOptions = document.createElement("option"); //create the <option> tag
modelOptions.textContent = models; // assigns text to option
modelOptions.value = models; // assigns value to option
selectedModel.appendChild(modelOptions); //appeneds option tag with text and value to "modelSelect" element
}
}
</script>
This line is fishy:
var appendedModel = window[selectedMake.value + "Models"];
You need to get the element when the value has changed, not on page load. Then you need to remove the options on change too, or you will get a very long list if the user selects multiple times. Use an object to store the arrays, that makes it much easier to access them later. Also better use an event listener instead of inline js (though that's not the main problem here).
Try below code:
let models = {
audiModels: ["TT", "R8", "A4", "A6"],
mercModels: ["C230", "B28", "LTX"],
bmwModels: ["328", "355", "458i"]
}
document.getElementById('makeSelect').addEventListener('change', e => {
let el = e.target;
let val = el.value + 'Models';
let appendTo = document.getElementById('modelSelect');
Array.from(appendTo.getElementsByTagName('option')).forEach(c => appendTo.removeChild(c));
if (!models[val] || !Array.isArray(models[val])) {
appendTo.style.display = 'none';
return;
}
models[val].forEach(m => {
let opt = document.createElement('option');
opt.textContent = opt.value = m;
appendTo.appendChild(opt);
});
appendTo.style.display = '';
});
<select id="makeSelect">
<option value=""></option>
<option value="merc">Mercedes</option>
<option value="audi">Audi</option>
<option value="bmw">BMW</option>
</select>
<select id="modelSelect" style="display:none">
</select>

Dropdown Select Getting Text Value instead of the assined value

I'm just wondering if this is possible, supposed I have:
<select name = 'region' id = 'region'>
<option value = '1'>Region 1</option>
<select>
Now, I know I get the value of 1 when I select "Region 1". Is there a way to get
the "Region 1" as the value itself without changing the value = '1'. I need that for javascript for other dropdowns.
Sorry I forgot to mention, I'm referring to PHP. I know that:
$value = $_POST['region'];
will the value of 1, how can I get just the text to pass on $_POST?
var el = document.getElementById('region');
var text = el.selectedIndex == -1 ? null : el.options[el.selectedIndex].text;
console.log(text);
Javascript:
var value1 = document.getElementById("region");
var value2 = value1.options[value1.selectedIndex].text;
alert(value2);
js
$("#region").change(function(){
var domNode = document.getElementById("region");
var value = domNode.selectedIndex;
var selected_text = domNode.options[value].text;
alert(selected_text);
});
First of all, as you haven't mentioned whether you are planning on supporting legacy browsers or not, I've decided to add support for that browsers as well. My script works with all IE versions (IE7 inclusive).
So, first we attach our eventlistener to your select element. Then we retrieve the text of the selected option and return the value;
Have a look at this => DEMO
If you want to submit it via $_POST than do the following ->
Create a hidden input element, set its name attribute to say select, then set its value to the value of our text variable (we will have that variable when one of our options is selected) - See the code below.
After submitting your form you can retrieve the value like so => $_POST['select'] (select is the name attribute we have assigned to our hidden input element)
Javascript
//attaching the eventlistener (modified the code to make it compatible with older IE versions)
function attach(element,listener,ev,tf){
if(element.attachEvent) {
//support for older IE (IE7 inclusive)
element.attachEvent("on"+listener,ev);
}else{
//modern browsers
element.addEventListener(listener,ev,tf);
}
}
function returnTextofTheSelectedElement(sel){
//getting and returning the text of the selected option
selectedIndex = sel[sel.selectedIndex];
return text = selectedIndex.innerText ? selectedIndex.innerText : selectedIndex.textContent;
}
var select = document.getElementById('region');
attach(select,'change',function(){
//pass the select tag you want to get the text of
//*returnTextofTheSelectedElement* function returns our text
alert(returnTextofTheSelectedElement(select));
//so you can store it in a *variable* and use it when submitting your form
text = returnTextofTheSelectedElement(select);
//if you want to submit it via $_POST than do the following
//create a hidden *input* element, set its name attribute to say *select*, then set its value to the value of our *text* variable
input = document.createElement('input');
input.type = 'hidden';
input.name = 'select';
input.value = text;
select.parentNode.appendChild(input);
alert('The value/text of the hidden input is '+input.value);
//when submitting the form, it will also submit out hidden input with the value (text) of the selected option
//you can retrieve the value like so => *$_POST['select']*
},false);
HTML
<select name='region' id='region'>
<option value='1'>Region 1</option>
<option value='2'>Region 2</option>
<option value='3'>Region 3</option>
<select>
Cross Browser:
var select = document.getElementById('region');
if(select.addEventListener) {
select.addEventListener('change', function(evt) {
var target = evt.target || evt.srcElement;
var selected = target[target.selectedIndex];
var text = selected.textContent || selected.innerText;
alert(text);
});
}
else if(select.attachEvent) {
select.attachEvent('onchange', function(evt) {
var target = evt.target || evt.srcElement;
var selected = target[target.selectedIndex];
var text = selected.textContent || selected.innerText;
alert(text);
});
}
http://jsfiddle.net/LrETq/
$(select#region option).click(function(){
var textOfTheSelectedOption= $(this).text();
alert( textOfTheSelectedOption);
});
You can get text value like this. Is it helpful?
var e = document.getElementById("region");
var value = e.options[e.selectedIndex].text;
console.log(value);
<script>
function getSelectedText(){
var theSelect= document.getElementById("region");
var theText= theSelect.options[theSelect.selectedIndex].text;
alert(theText);
}
</script>
<select name = 'region' id = 'region' onchange="getSelectedText()">
<option value = '1'>Region 1</option>
<option value = '2'>Region 2</option>
<select>
<form method="post" action="action.php">
<select name = 'region' id = 'region' onchange="fnc()">
<option value = '1'>Region 1</option>
<option value = '2'>Region 2</option>
<select>
<input type="hidden" name="hidden_region" id="hidden_region">
<input type="submit" value="Send">
</form>
<script type="text/javascript">
function fnc(){
var el = document.getElementById('region');
var text = el.selectedIndex == -1 ? '' : el.options[el.selectedIndex].text;
document.getElementById('hidden_region').value = text;
}
</script>
in php post will be like
$value = $_POST['hidden_region'];

How would I dynamically create input boxes on the fly?

I want to use the value of a HTML dropdown box and create that number of input boxes underneath. I'm hoping I can achieve this on the fly. Also if the value changes it should add or remove appropriately.
What programming language would I need to do this in? I'm using PHP for the overall website.
Here is an example that uses jQuery to achieve your goals:
Assume you have following html:
<div>
<select id="input_count">
<option value="1">1 input</option>
<option value="2">2 inputs</option>
<option value="3">3 inputs</option>
</select>
<div>
<div id="inputs"> </div>
And this is the js code for your task:
$('#input_count').change(function() {
var selectObj = $(this);
var selectedOption = selectObj.find(":selected");
var selectedValue = selectedOption.val();
var targetDiv = $("#inputs");
targetDiv.html("");
for(var i = 0; i < selectedValue; i++) {
targetDiv.append($("<input />"));
}
});
You can simplify this code as follows:
$('#input_count').change(function() {
var selectedValue = $(this).val();
var targetDiv = $("#inputs").html("");
for(var i = 0; i < selectedValue; i++) {
targetDiv.append($("<input />"));
}
});
Here is a working fiddle example: http://jsfiddle.net/melih/VnRBm/
You can read more about jQuery: http://jquery.com/
I would go for jQuery.
To start with look at change(), empty() and append()
http://api.jquery.com/change/
http://api.jquery.com/empty/
http://api.jquery.com/append/
Doing it in javascript is quite easy. Assuming you've got a number and an html element where to insert. You can obtain the parent html element by using document.getElementById or other similar methods. The method assumes the only children of the parentElement is going to be these input boxes. Here's some sample code:
function addInput = function( number, parentElement ) {
// clear all previous children
parentElement.innerHtml = "";
for (var i = 0; i < number; i++) {
var inputEl = document.createElement('input');
inputEl['type'] = 'text';
// set other styles here
parentElement.appendChild(inputEl);
}
}
for the select change event, look here: javascript select input event
you would most likely use javascript(which is what jquery is), here is an example to show you how it can be done to get you on your way
<select name="s" onchange="addTxtInputs(this)" onkeyup="addTxtInputs(this)">
<option value="0">Add</option>
<option value="1">1</option>
<option value="3">3</option>
<option value="7">7</option>
</select>
<div id="inputPlaceHolder"></div>
javascript to dynamically create a selected number of inputs on the fly, based on Mutahhir answer
<script>
function addTxtInputs(o){
var n = o.value; // holds the value from the selected option (dropdown)
var p = document.getElementById("inputPlaceHolder"); // this is to get the placeholder element
p.innerHTML = ""; // clears the contents of the place holder each time the select option is chosen.
// loop to create the number of inputs based apon `n`(selected value)
for (var i=0; i < n; i++) {
var odiv = document.createElement("div"); //create a div so each input can have there own line
var inpt = document.createElement("input");
inpt['type'] = "text"; // the input type is text
inpt['id'] = "someInputId_" + i; // set a id for optional reference
inpt['name'] = "someInputName_" + i; // an unique name for each of the inputs
odiv.appendChild(inpt); // append the each input to a div
p.appendChild(odiv); // append the div and inputs to the placeholder (inputPlaceHolder)
}
}
</script>

Search a dropdown

I have this HTML dropdown:
<form>
<input type="text" id="realtxt" onkeyup="searchSel()">
<select id="select" name="basic-combo" size="1">
<option value="2821">Something </option>
<option value="2825"> Something </option>
<option value="2842"> Something </option>
<option value="2843"> _Something </option>
<option value="15999"> _Something </option>
</select>
</form>
I need to search trough it using javascript.
This is what I have now:
function searchSel() {
var input=document.getElementById('realtxt').value.toLowerCase();
var output=document.getElementById('basic-combo').options;
for(var i=0;i<output.length;i++) {
var outputvalue = output[i].value;
var output = outputvalue.replace(/^(\s| )+|(\s| )+$/g,"");
if(output.indexOf(input)==0){
output[i].selected=true;
}
if(document.forms[0].realtxt.value==''){
output[0].selected=true;
}
}
}
The code doesn't work, and it's probably not the best.
Can anyone show me how I can search trough the dropdown items and when i hit enter find the one i want, and if i hit enter again give me the next result, using plain javascript?
Here's the fixed code. It searches for the first occurrence only:
function searchSel() {
var input = document.getElementById('realtxt').value;
var list = document.getElementById('select');
var listItems = list.options;
if(input === '')
{
listItems[0].selected = true;
return;
}
for(var i=0;i<list.length;i++) {
var val = list[i].value.toLowerCase();
if(val.indexOf(input) == 0) {
list.selectedIndex = i;
return;
}
}
}
You should not check for empty text outside the for loop.
Also, this code will do partial match i.e. if you type 'A', it will select the option 'Artikkelarkiv' option.
Right of the bat, your code won't work as you're selecting the dropdown wrong:
document.getElementById("basic-combo")
is wrong, as the id is select, while "basic-combo" is the name attribute.
And another thing to note, is that you have two variable named output. Even though they're in different scopes, it might become confusing.
For stuff like this, I'd suggest you use a JavaScript library like jQuery (http://jquery.com) to make DOM interaction easier and cross-browser compatible.
Then, you can select and traverse all the elements from your select like this:
$("#select").each(function() {
var $this = $(this); // Just a shortcut
var value = $this.val(); // The value of the option element
var content = $this.html(); // The text content of the option element
// Process as you wish
});

Categories