I am just starting html/javascript, and attempting to create a simple form that populates a specific "Customer Code" when a "Customer Name" is selected from an input list (behaving like an excel vlookup). The examples I found on stackoverflow all resulted in alert windows, but I would like the value to populate in the form.
Here's my html snippet for the Customer Name dropdown list:
<select id="customername">
<option></option>
<option>Doe Inc</option>
<option> Smith LLC </option>
<option> Rogers and Co </option>
Here's the customername to customercode mapping:
Doe Inc = 276. Smith LLC = 852. Rogers and Co = 552.
I would like the customercode to update to the respective customername whenever the customername is updated (without the need for a button), as this is part of a larger form that will an Submit button (in other words, I don't want users to have to click "Submit" to retrieve the customercode, then "Submit" again later in the form).
Thanks!
In order to be included in a form submission, your form controls need to successful controls, which at the simplest means they need a name="" value:
<select id="customername" name="customername">
<option></option>
<option>Doe Inc</option>
<option> Smith LLC </option>
<option> Rogers and Co </option>
</select>
If what you actually care about submitting is the customercode, and the customername is just the "friendly" version, add the value attribute to your options, and rename the select appropriately:
<select id="customercode" name="customercode">
<option value="">Select one...</option>
<option value="276">Doe Inc</option>
<option value="852">Smith LLC </option>
<option value="552">Rogers and Co </option>
</select>
If you want both "values" to be visible on the form and included in the form submission, you could use a data- attribute to sync a readonly input:
<select id="customername" name="customername">
<option data-value="">Select one...</option>
<option data-value="276">Doe Inc</option>
<option data-value="852">Smith LLC </option>
<option data-value="552">Rogers and Co </option>
</select>
<input type="text" name="customercode" id="customercode" readonly />
Then use some JavaScript to sync them:
var select = document.getElementById('customername');
select.onchange = function(e) {
var value = select.options[select.selectedIndex].dataset.value;
var input = document.getElementById('customercode');
input.value = value;
}
Example jsFiddle: https://jsfiddle.net/27jx0q3a/3/
Some links, to help:
W3C: Successful controls
MDN: Using data attributes
I hope this is what you were looking for.
Basically, I used an array to format your numbers, then used the onchange onto the select element and waited for a change. When a change occurs, I fire an event and Javascript gets the values of the field, compares them with the array and returns based on the selected value.
Please refer to Tieson T. Reply, has way more explanations and different approaches for static html!
var drop_down = document.getElementById("customername");
var result = document.getElementById("result");
var list_array = {
"": "Please Select A Value",
"Doe Inc": 276,
"Smith LLC": 852,
"Rogers and Co": 552
}
function change_value() {
if (list_array[drop_down.value]) {
result.innerHTML = list_array[drop_down.value];
}
}
<select id="customername" onchange="change_value()">
<option></option>
<option>Doe Inc</option>
<option>Smith LLC</option>
<option>Rogers and Co</option>
</select>
<span id="result"></span>
Related
I am new to javascript and cannot find an easy-to-understand answer.
I would like a certain value to get passed to a hidden field when a user selects a certain option from the select dropdown.
I know that there are if/else statements but I'm not sure if that would be used in this situation.
For example: I have a select dropdown of a list of states.
<select name="HomeState" required>
<option value="1">Alabama</option>
<option value="1">Alaska</option>
<option value="1">Arizona</option>
<option value="1">Arkansas</option>
<option value="5">California</option>
<option value="1">Colorado</option>
<option value="1">Connecticut</option>
<option value="1">Delaware</option>
</select>
As you can see, any option other than California will be rated at a value of 1.
I would like it to where if the user selects the option of California, then the value of $300 will get passed to a hidden form field.
<input name="AmountNeeded" type="hidden" value="300" />
If they select anything other than California, the hidden field would get passed $100
<input name="AmountNeeded" type="hidden" value="100" />
How would I implement this logic? Would it be using if/else statement? I am new and don't exactly know how to set that up.
To keep this simple you could assign ids to the <select> and hidden <input> and listen to the change event via onchange() on the <select> with a function call.
And based on the selected item, change the value of hidden input.
NOTE: To test the snippet out I have removed the type="hidden". Do place it back.
function homeSelected(){
const home = document.getElementById("homeSelector").value;
if(home == 5){
document.getElementById("amountNeeded").value = 300;
}else{
document.getElementById("amountNeeded").value = 100;
}
}
<select id="homeSelector" name="HomeState" onchange="homeSelected()" required>
<option value="1">Alabama</option>
<option value="1">Alaska</option>
<option value="1">Arizona</option>
<option value="1">Arkansas</option>
<option value="5">California</option>
<option value="1">Colorado</option>
<option value="1">Connecticut</option>
<option value="1">Delaware</option>
</select>
<input id="amountNeeded" name="AmountNeeded" value="100" />
You can do this as follows:
<select name="HomeState" required onChange=myFunction(this)>
<option value="1">Alabama</option>
<option value="1">Alaska</option>
<option value="1">Arizona</option>
<option value="1">Arkansas</option>
<option value="5">California</option>
<option value="1">Colorado</option>
<option value="1">Connecticut</option>
<option value="1">Delaware</option>
</select>
Javascript code is:
<script>
function myFunction(x) {
val = x.options[x.selectedIndex].text;
if(val == 'California')
document.getElementsByName("AmountNeeded")[0].value = 300
else
document.getElementsByName("AmountNeeded")[0].value = 100
}
</script>
If else statement is good for you if you are sure that All other states have value 1 except California. If all states may have different values like some states may have 1 or some may have 2 or some may have 3, then there may be other alternatives to solve this like you can pass give one more attribute data-src-amount to options and give amount to data-src-amount. You can create options like <option value="1" data-src-amount="100">Alabama</option> and in script, you can fetch data-src-amount on select change event instead of if-else statement.
I have a form with cloned elements. The method of the form is POST. When I dump the result of the POST only the final 'select' box value is shown because they are all the same. How can I change the name tag to the cloned elements?
JSFiddle: https://jsfiddle.net/hLefegxz/
HTML
<div id="employees-div">
<label for="employees">Employee(s)</label>
<div class="select-wrapper" id="select-employees">
<select id="employees" name="employees" >
<option value="" selected disabled>- Select Employee -</option>
<option value="1"> Jason Bourne </option>
<option value="2"> James Bond </option>
<option value="3"> Ethan Hunt </option>
</select>
</div>
JS for the Clone
$(function() {
$("#addMore").click(function(e) {
var newSelect = $("#select-employees").clone();
newSelect.val("123");
$("#employees-div").append(newSelect);
});
});
At the moment all fo the elements have the same name tag of employees. It obviously needs to be different to go into the $_POST array. How can I go about making them different? I was thinking maybe of incrementing and keeping a count? It Currently is like so:
Don't worry about changing the name, you can and should use an array for the name, but you should worry about the id, since ids must be unique and you are cloning elements without changing the id of the new element.
By adding the [] to the input name it will be sent to the server as an array, for example, if you're using PHP you can get them from $_GET['employees'] which will be an array you can loop thru.
$(function() {
$("#addMore").click(function(e) {
var newSelect = $('select[name="employees[]"]:first').clone();
$("#select-employees").append("<br>");
$("#select-employees").append(newSelect);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="employees-div">
<label for="employees">Employee(s)</label>
<div class="select-wrapper" id="select-employees">
<select name="employees[]" >
<option value="" selected>- Select Employee -</option>
<option value="1"> Jason Bourne </option>
<option value="2"> James Bond </option>
<option value="3"> Ethan Hunt </option>
</select>
</div>
<button id=addMore>+ Employee</button>
Instead of using a name and increasing an integer on each "new employee", you could simply name your select to employees[]. That will send every employee in an array format to your server, allowing you to use an easy loop.
Your code as another problem though. ID should be unique, so every time you clone your select, you should change the ID.
I have the following drop down menu.
<select id="MySelectMenu">
<option value="#">-*-*- Main Accounts -*-*-</option>
<option value="http://www.google.com">Google</option>
<option value="http://www.yahoo.com">Yahoo</option>
<option value="http://www.example.com">Example</option>
</select>
Is it possible for me to add two text input fields where the visitor can populate the menu options themselves?
For example, in text field one they input the url for the option, and text field two, they input the name of the option.
So...
Text field one: http://www.randomwebsite.com
Text field two: Random Website
Then an 'Add' button, which would result in this...
<select id="MySelectMenu">
<option value="#">-*-*- Main Accounts -*-*-</option>
<option value="http://www.google.com">Google</option>
<option value="http://www.yahoo.com">Yahoo</option>
<option value="http://www.example.com">Example</option>
<option value="http://www.randomwebsite.com">Random Website</option>
</select>
This is the javascript for the current menu, if this helps.
<script type="text/javascript">
function newSrc() {
var e = document.getElementById("MySelectMenu");
var newSrc = e.options[e.selectedIndex].value;
document.getElementById("MyFrame").src=newSrc;
}
</script>
Thanks in advance.
Yes Create two textboxes and Add id's to them and also create a button with a onclick function "Add", Then use the following javascript which is nothing but creating the option and appending to selectbox
function Add()
{
var x = document.getElementById("MySelectMenu");
var opt = document.createElement("option");
opt.value= document.getElementById("url").value;
opt.innerHTML = document.getElementById("name").value; // whatever property it has
x.add(opt);
}
<select id="MySelectMenu">
<option value="#">-*-*- Main Accounts -*-*-</option>
<option value="http://www.google.com">Google</option>
<option value="http://www.yahoo.com">Yahoo</option>
<option value="http://www.example.com">Example</option>
</select>
<input type="text" name="name" id="name">
<input type="url" name="url" id="url">
<button onclick="Add()">ADD</button>
Try below code
var url=$("#txtUrl").val();
var textValue = $("#txtDisplay").val();
$('#MySelectMenu').append("<option value='"+url+"'>"+textValue+"</option>);
use this code on OnClick event of Add button.
I want to use this function to work on all my drop down lists. Problem: the first drop down works okay, but hen I try select any option in the 2nd drop down selections. It places the value from the first group in the span of the second group. I want the span to have the value from its own group. I would like to use this on multiple groups.
The code below does not work properly. the phone number display okay but when i try to select the parts, the value of the phone number is displayed, no matter what the selection is.
I want the phone number when i select phones, and parts when i select parts.
Thank you
<script>function displayResult(xspan,xselect)
{
var x=document.getElementById(xselect).selectedIndex;
alert(x);
var newTxt = document.getElementsByTagName("option")[x].value;
document.getElementById(xspan).innerHTML = newTxt;
//alert(document.getElementsByTagName("option").length);
}
</script>
<select id="myPhones" onchange="displayResult('ShowPhone','myPhones')">
<option value="">Phone Numbers</option>
<optgroup label="Shipping">
<option value=" - 800-463-3339">FedEx</option>
<option value=""></option>
</optgroup>
</select>
<span id="ShowPhone"></span>
<select id="myParts" onchange="displayResult('ShowParts','myParts')">
<option value="">Qik Parts list</option>
<optgroup label="BATT">
<option value="1">1</option>
<option value="2">1</option>
<option value="2">1</option>
<option value="2"><1/option>
</optgroup>
</select>
<span id="ShowParts"></span>
Mostly comments:
When you do:
var newTxt = document.getElementsByTagName("option")[x].value;
then document.getElementsByTagName("option") returns all the options in the document, you probably only want the ones for the select in question. But the options for a select are available as a collection, so you can do:
selectElement.options[x].value;
But that is unnecessary unless you are dealing with very old browsers or IE where there are no value attributes. Just use selectElement.value.
Where you have:
<select id="myPhones" onchange="displayResult('ShowPhone','myPhones')">
you can instead do:
<select id="myPhones" onchange="displayResult('ShowPhone', this.value)">
so that you pass the current value of the select directly to the function. Then the function can be:
function displayResult(id, value) {
document.getElementById(id).innerHTML = value;
}
This should work, though I haven't tested it.
function displayResult(spanId, selectId) {
document.getElementById(spanId).innerHTML = document.getElementById(selectId).value;
}
Having this fieldset:
<fieldset>
<legend>[*death]</legend>
<select name=death style="width: 120px">
<option value=Dead>[*died]
<option value=NotDead>[*alive]
<option value="" selected>-
</select>
</fieldset>
i want to set the [2].value to "-".
i have tried without any success:
document.getElementsByName('death')[2].checked = 'true';
document.getElementsByName('death')[2].value = '-';
Same kind of code works fine for radio boxes, checked boxes or other inputs in the form. How to do it with the option select (which is not an input)?
Thanks
[EDIT] of course, appropriate fieldset is:
<fieldset>
<legend>[*death]</legend>
<select name="death" style="width: 120px">
<option value="Dead">[*died]</option>
<option value="NotDead">[*alive]</option>
<option value="" selected>-</option>
</select>
</fieldset>
thanks.
It's a little bit unclear what you're asking. Are you simply asking to make the option at index 2 selected?
document.getElementsByName('death')[0].selectedIndex = 2;
Or, are you asking to change the value of option at index 2?
var d = document.getElementsByName('death')[0];
d.options[2].value = '-';
You need to manipulate the selected property of your select object, try
document.getElementsByName('death')[0].selectedIndex = 1;
In english, this reads "set the selected option to the second option in the first element in the document with name 'death'".
Fixing your HTML might make the results of your javascript more predictable. Close your tags, quote your attribute values, as follows:
<fieldset>
<legend>[*death]</legend>
<select name="death" style="width: 120px">
<option value="Dead">[*died]</option>
<option value="NotDead">[*alive]</option>
<option value="" selected>-</option>
</select>
</fieldset>
you can do this using jQuery... it's easy...
j("#death").val(2)
document.getElementsByName('death')[2] returns the third element named death - but you only have one element with that name. Instead, you want the first element named death (i.e. the one at index 0), and then you want its third option: document.getElementsByName('death')[0].options[2].value = ...
Here's an alert example of how to access your specific option values with getElementsByName
alert(document.getElementsByName('death')[0].options[0].value); // will return Dead
alert(document.getElementsByName('death')[0].options[1].value); // will return NotDead