Adding new option to select menu - javascript

This is a very simple select bar. Why is it not working?
<html>
<form>
<label>
<select id="sel1">
<option> op1 </option>
<option> op2 </option>
<option> op3 </option>
</select>
<input onclick="s()" type="submit" value=" ok! ">
</label>
</form>
<script>
function s(){
document.getElementById("sel1").innerHTML += "<option> op4 </option>";
}
</script>
</html>
If I want people to add new option, I need to put some variable on it. How can I add php variable instead of op4, op5, etc?

Create an actual option element and append it to the select element.
var option = document.createElement("option");
option.value = "op4";
option.innerHTML = "op4";
var select = document.getElementById("sel1");
select.appendChild(option);
You should probably be using value attributes in your options too.
This is the next question. Then if i want people to add new option , i need to put some php variable on it. how can i add php variable instead of op4 , op5 and... options?
No, this has nothing to do with PHP.
<input id="option-name">
Using the example above, instead of using a fixed "op4", use the value from the input
var input = document.getElementById("option-name");
var option = document.createElement("option");
option.value = input.value;
option.innerHTML = input.value;
var select = document.getElementById("sel1");
select.appendChild(option);
Now the input value will be used as the name/value for the new option

Change this:
<input onclick="s()" type="submit" value=" ok! ">
To this:
<input onclick="s()" type="button" value=" ok! ">
Using type="submit" will result in your form being submitted and thus your page being reloaded. Using type="button" prevents this.

What happens is the form is submitted and as the form element doesn't have action attribute the current page is reloaded.
You should listen to submit event and prevent the default action of the event using preventDefault method of the event object.
document.querySelector('form').addEventListener('submit', function(event) {
event.preventDefault();
var option = new Option('optionText', 'optionValue');
document.getElementById("sel1").add(option);
});
Another option is using a button element with type attribute of button instead of a submit input.

Try this:
<script>
function s(){
var o=new Option();
o.value="<?php echo $option; ?>";
o.text="<?php echo $option; ?>";
var os=document.getElementById("sel1").options;
os[os.length]=o;
}
</script>

I finally write completed Answer. In 2 ways; The first way is safer than another. first way is :
<html>
<form>
<label>
<input type="text" id="option-name">
<select id="sel1">
<option> Option1 </option>
<option> Option2 </option>
<option> Option3 </option>
</select>
<input onclick="s()" type="button" value=" Create ! "><br/><br/>
</label>
</form>
<script>
function s(){
var input = document.getElementById("option-name");
var option = document.createElement("option");
option.value = input.value;
option.innerHTML = input.value;
var select = document.getElementById("sel1");
select.appendChild(option);
}
</script>
</html>
That is other guys answer too. But the second way is easier and useful. not safer (I think innerhtml is not so safe for this purpose! but if I wrong , please tell me.)!
<html>
<form method="post" action="index.php">
<label>
<input type="text" name="txt1">
<select id="sel1">
<option> Option1 </option>
<option> Option2 </option>
<option> Option3 </option>
</select>
<input type="submit" value=" Create ! ">
</label>
</form>
<script>
document.getElementById("sel1").innerHTML += "<option><?php echo $_POST['txt1']; ?></option>";
</script>

Related

dynamic Drodown in html

I have to make a html page in which there should be TextBox and a add Button and if user add something via Textbox then it should be visible in Dropdown.
kindly help with code.
thanks in advance.
I'm not exactly sure what you need but based on your description, I was able to build this basic page:
const list = document.getElementById("lists");
const text = document.getElementById("myText");
function addEntry(){
var newOption = document.createElement("OPTION");
newOption.value = text.value;
newOption.innerHTML = text.value;
list.appendChild(newOption);
text.value = "";
text.focus();
}
<select id="lists">
<option selected disabled>-- SELECT ONE --</option>
</select>
<br><br>
<input type="text" id="myText" placeholder="Type here...">
<input type="button" onclick="addEntry()" value="+ ADD">
Basically, this uses a function that takes the value, creates an HTML <option> element, then inserts it into the dropdown menu.

Is there a way to disable a dropdown to users while still being able to submit a form with the disabled dropdown?

I have a dropdown that is disabled to the user. I want for the user to be able to press a button that changes the selected item to a different one. For example: from the 4th item in the dropdown to the 7th.
I've tried disabling the dropdown, but when I do that and submit the form, I get a PHP error saying Undefined index: id.
HTML:
<form>
<select id='id' name='id' autocomplete='none' disabled required>
<option value='2'>apple</option>
<option value='6'>banana</option>
<option value='10'>orange</option>
</select>
<button type='submit'>Submit</button>
</form>
JavaScript:
const dropdown = document.getElementById('dropdown');
const options = dropdown.options;
for (let i = 0; i < options.length; ++i) {
if (options[i].value === id) {
dropdown.selectedIndex = i;
break;
}
}
PHP (This line seems to be the one breaking):
$id = $_POST['id'];
It seems you haven't defined method and action in your form tag. By default, I think, the method is set to 'GET', so when checking 'POST' you'll run into your error.
Therefore, set "method='post'" (and best also an action, e.g. "action='/yourPageName.php') and see if that helps.
I figured out a solution that suits my needs. It was kind of simple. I just enabled the dropdown when I submitted the form, and instantly disabled it again.
id.removeAttribute('disabled');
const data = new FormData(document.getElementById('form'));
id.setAttribute('disabled', '');
request.send(data);
Thanks for the help though :)
A disabled input field will be ignored when you submit the form. I would suggest creating a hidden input field of name="id" if you want the user to view the dropdown but not select it.
<form>
<select id='id' autocomplete='none' disabled required>
<option value='2'>apple</option>
<option value='6'>banana</option>
<option value='10'>orange</option>
</select>
<input type="hidden" name='id' value="6" />
<button type='submit'>Submit</button>
</form>
You can make an hidden input with the id="id" and change the select id to "temp_id". Then, since you are making the request from javascript, you can just update the hidden field before making the request.
<select id='temp_id' autocomplete='none' disabled required>
<option value='2'>apple</option>
<option value='6'>banana</option>
<option value='10>orange</option>
</select>
<input type="hidden" name="id" id="id" value="">
Then, on your javascript, just before you make the request, run the code:
document.getElementById("id").value = document.getElementById("temp_id").value;

Using innerHTML of <select> for windows.open()

On a page of my website I want user to select one choice of a and when they click on "connect" it open a new tab with the correct link.
code :
<select name="choice" id="choice">
<option value="Server1.html">Server1</option>
<option value="Server2.html">Server2</option>
<option value="Server3.html">Server3</option>
</select>
<input type="button" name="go_button" id= "go_button" value="go" onclick="go_to_the_link()"/>
<script>
function go_to_this_link(){
var element = document.getElementById("choice");
var link = element.innerHTML;
myWindow = window.open(link,"_blank");
}
</script>
According to the documentation this should works ... but since I'm new to JS and not expert in HTML I must have failed something.
I want to use JS only and make something that also works with datalist.
Any help is welcome !
Solved:
Ok I had 2 problem :
In order to post this on stackoverflow I changed all my variable and function name, and I forgot to change one ...
As said in the comment, I needed to use "value" and not innerHTML. I tried with value once but it also failed that's why I gave up this, I guess something else was wrong.
Thx for helping solving the problem !
(working) code :
<select name="choice" id="choice">
<option value="Server1.html">Server1</option>
<option value="Server2.html">Server2</option>
<option value="Server3.html">Server3</option>
</select>
<input type="button" name="go_button" id= "go_button" value="go" onclick="go_to_the_link()"/>
<script>
function go_to_the_link(){
var element = document.getElementById("choice");
var link = element.value;
myWindow = window.open(link,"_blank");
}
</script>

Two forms on the same page needs the value of the same element

I have two forms on a php page. They post to different pages when they are submitted. Both forms need the value of a dropbox that is inside form A. How do I get this value posted when form B is submitted?
Create a hidden input in form B and put a change event on the dropdown in form A which copies it's value to that.
Example (using jQuery - if you want to do it with another library or plain javascript you'll need to adapt it).
<script type="text/javascript">
$(function(){
$('#copy-src').change(function(){
$('#copy-target').val( $(this).val() );
}).change();
});
</script>
<form id="a" action="/a">
<input type="text" name="a_only" />
<select id="copy-src" name="also_b">
<option value=""></option>
<option value="foo">Foo</option>
<option value="bar">Bar</option>
</select>
<button type="submit">Submit</button>
</form>
<form id="b" action="/b">
<input type="text" name="b_only" />
<input type="hidden" name="also_a" id="copy-target" />
<button type="submit">Submit</button>
</form>
The .change(function(){}) creates a change event to copy the value while the final .change() triggers that event (on page load) to ensure the value is right initially.
You can copy dropbox value to Form B while submitting;
On formB;
<form onsubmit="getDropdownValue()">
.....
</form>
And in function;
function getDropdownValue() {
var formB = document.getElementById("formB");
// Get selected value from FormA
var e = document.getElementById("formADropdown");
var value = e.options[e.selectedIndex].value;
// Append it to formB
var input = document.createElement("input");
input.type = "hidden";
input.name = "dropdownValue";
formB.appendChild(input);
}
You can see demo: Demo . I demo when you click submit, you will see dropdownvalue from form A will be copied to formB before submit

Display the selected value of a Drop down list in a text field (javascript)

For Example:
These are the items in a drop down list.
<select name="cmbitems" id="cmbitems">
<option value="price1">blue</option>
<option value="price2">green</option>
<option value="price3">red</option>
</select>
When the user selects blue, i want to display the value of price1 in a text field below:
<input type="text" name="txtprice" id="txtprice" onClick="checkPrice()">
Thank you for answering
All you need to do is set the value of the input to the value of the select, in a select.onchange event handler.
var select = document.getElementById('cmbitems');
var input = document.getElementById('txtprice');
select.onchange = function() {
input.value = select.value;
}
Here is a link to a jsFiddle demo
This is the brute force way to look up the currently selected option, check its value and use its display text to update your input. Like Daniele suggested, if you have jquery at your disposal, this gets much, much easier. But if you can't use a JS framework for any reason, this should get you what you need.
<select name="cmbitems" id="cmbitems" onchange="updateTextField()">
...
</select>
<input type="text" ..... />
<script type="text/javascript">
function updateTextField()
{
var select = document.getElementById("cmbitems");
var option = select.options[select.selectedIndex];
if (option.id == "price1")
{
document.getElementById("txtprice").value = option.text;
}
}
</script>
$.on('change', '#cmbitems', function() {
$('#txtprice').val($('#cmbitems option:selected').val());
});
If you are using jquery just go with
$('select.foo option:selected').val(); // get the value from a dropdown select
UPDATE ( I forgot to inlcude the <input> population)
First, inlcude jquery in your html file.
In the <header> you include it:
<header>
<script type="text/javascript" src="YOUR_PATH_TO_LIBRARY/jquery-1.7.1-min.js"></script>
</header>
Then
<input type="text" name="txtprice" id="txtprice" onClick="javascript:$('select.foo option:selected').val();">

Categories

Resources