onClick copy text field value to drop down field - javascript

I have been researching how to copy a a text field value into a drop down menu and have only been seeing how to accomplish the opposite. Can somebody help me tweak this code so it will copy the shipping city value (text field) into the billing city (drop down)?
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<P>
<script type="text/javascript">
<!--
function FillBilling(f) {
if(f.billingtoo.checked == true) {
f.billingname.value = f.shippingname.value;
f.billingcity.value = f.shippingcity.value;
}
}
// -->
</script>
<TABLE BORDER=1><TR><TD BGCOLOR="eeeeee">
<b>Mailing Address</b>
<br><br>
<form>
Name:
<input type="text" name="shippingname">
<br>
City:
<input type="text" name="shippingcity">
<br>
<input type="checkbox" name="billingtoo" onclick="FillBilling(this.form)">
<em>Check this box if Billing Address and Mailing Address are the same.</em>
<P>
<b>Billing Address</b>
<br><br>
Name:
<input type="text" name="billingname">
<br>
City:
<select name="billingcity">
<option value="City 1">City 1</option>
<option value="City 2">City 2</option>
<option value="City 3">City 3</option>
</select>
</form>
</TD></TR></TABLE>
</body>
</html>

It's a little messy, but here's my attempt at what you seem to want:
function FillBilling(f) {
if (f.billingtoo.checked === true && f.shippingcity.value) {
f.billingname.value = f.shippingname.value;
var found = false;
for (var i = 0; i < f.billingcity.options.length; i++) {
if (f.billingcity.options[i].value.toLowerCase() === f.shippingcity.value.toLowerCase()) {
f.billingcity.selectedIndex = i;
found = true;
break;
}
}
if (!found) {
var extraOption = f.billingcity.getAttribute("data-extra-option");
if (extraOption) {
f.billingcity.options[f.billingcity.options.length - 1].text = f.shippingcity.value;
f.billingcity.options[f.billingcity.options.length - 1].value = f.shippingcity.value;
} else {
var newOption = new Option(f.shippingcity.value, f.shippingcity.value);
f.billingcity.setAttribute("data-extra-option", "true");
f.billingcity.appendChild(newOption);
f.billingcity.selectedIndex = f.billingcity.options.length - 1;
}
} else {
if (f.billingcity.getAttribute("data-extra-option")) {
f.billingcity.removeChild(f.billingcity.options[f.billingcity.options.length - 1]);
f.billingcity.selectedIndex = 0;
}
}
} else {
if (f.billingcity.getAttribute("data-extra-option")) {
f.billingcity.removeChild(f.billingcity.options[f.billingcity.options.length - 1]);
f.billingcity.selectedIndex = 0;
}
}
}
DEMO: http://jsfiddle.net/J8YrU/1/
This function is now called both for the checkbox being clicked and the Shipping City textbox value being changed.
What this function does is this:
If the text that's typed in the textbox matches an existing dropdown option, it selects that value
If the text that's typed in the textbox doesn't match an existing dropdown option, it will append a new option to the end with the user's input, and select it
If the text that's typed in the textbox doesn't match an existing dropdown option but there's already a new, custom option added in (from the last bullet), it just updates its text/value.
So test it, try these things:
Type in "City 3" in the textbox
Type in "asdf" in the textbox
Type in "asdf3" in the textbox
Type in "City 2" in the textbox
You can check the state of the dropdown after each thing you try and see what's happening to it. Also, you can toggle the checkbox at any point to test as well.

To add a value to a select element, you need to add an option element with appropriate text and value properties. So you might do:
var select = f.billingcity;
// Create a new option element, passing values for the text and value proprties
var option = new Option(f.shippingcity.value, f.shippingcity.value);
// Append the option to the select
select.appendChild(option);
// Make the new option the selected option
option.selected = true;

You need to make use of ID, and document.getElementById effectively in order to get the proper form elements and re-assign the values in the dropbox/select when the button is clicked.
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<P>
<script type="text/javascript">
<!--
function FillBilling(f) {
if(f.billingtoo.checked == true) {
document.getElementById("billingname").value = document.getElementById("shippingname").value;
var optn = document.createElement("OPTION");
optn.text = document.getElementById("shippingcity").value;;
optn.value = document.getElementById("shippingcity").value;;;
document.getElementById("billingcity").options.add(optn);
}
}
// -->
</script>
<TABLE BORDER=1><TR><TD BGCOLOR="eeeeee">
<b>Mailing Address</b>
<br><br>
<form>
Name:
<input type="text" name="shippingname" id="shippingname">
<br>
City:
<input type="text" name="shippingcity" id="shippingcity">
<br>
<input type="checkbox" name="billingtoo" onclick="FillBilling(this.form)">
<em>Check this box if Billing Address and Mailing Address are the same.</em>
<P>
<b>Billing Address</b>
<br><br>
Name:
<input type="text" name="billingname" id="billingname">
<br>
City:
<select id="billingcity" name="billingcity">
<option value="City 1">City 1</option>
<option value="City 2">City 2</option>
<option value="City 3">City 3</option>
</select>
</form>
</TD></TR></TABLE>
</body>
</html>
In order to change the select value as opposed to adding, you would use:
document.getElementById("billingcity").value=document.getElementById("shippingcity").value;

I would recommend including jquery
and then doing something like this:
function FillBilling(f) {
if(f.billingtoo.checked == true) {
var $firstCity = $('select option:first-child');
$firstCity.attr('text', f.shippingcity.value);
$firstCity.attr('value', f.shippingcity.value);
}
This should update the first option of select to the city user enters
Also as another user suggested it'd be better practice to give the select some id (for example selectIdentificator), and then update the above code like this
var $firstCity = $('#selectIdentificator option:first-child');

Related

Loop through select from fields and validate

Im trying to loop through multiple text and select boxes in a form and validate they have been answered.
I have used the following code to loop through the text boxes but can work out how to do something similar on the select boxes.
<form name="Form1"></form>
<label>Question 1</lable>
<input type="text" class="required" name="question1">
<label>Question 2</lable>
<select class="required" name="question3">
<option value="0">a</option>
<option value="1">b</option>
<option value="2">c</option>
<option value="3">d</option>
</select>
<button role="button"id="Go">Go</button>';
</form>
<script>
(function (){
$('#Go').on('click', function(e){
e.preventDefault();
genericValidationText('form[name="Form1"]');
genericValidationSelect('form[name="Form1"]');
});
}());
function genericValidationText (formName) {
document.forms.noValidate = true;
var notValid;
// PERFORM GENERIC CHECKS
// INPUT form fields
$(formName + ' *').filter(':input').each(function(){
var formElement = formName + ' input[name="'+ (this.name) + '"]' ;
performValidation(formElement);
});
function performValidation(formElement){
if ($(formElement).hasClass('required')) {
notValid = false;
if (!($.trim($(formElement).val()))){
notValid = true;
};
if (notValid === true) {
showErrorMessage(formElement);
};
};
}
}
function genericValidationSelect (formName) {
?????
}
</script>
You can validate <select> elements in much that same way as <input /> elements, by examining the result of the select element's .val().
Something to keep in mind is that the <select> will have a value by default (that corresponds to the <option> that is initially visible to the user in the browser). This will in effect cause validation on the <select> to pass (even when a selection option hasn't been explicitly picked by the user).
To address this, consider adding a default <option> to the <select> like this:
<option selected disabled>Please select something</option>
Adding this option means that validation on the <select> will fail until the user has actually engaged with the <select> by picking a valid option (after which, validation on the select will pass):
(function() {
/* Consider using submit on form, rather than a click event
listener on the Go button */
$('form[name="Form1"]').submit(function(e) {
e.preventDefault();
/* Exclude call to genericValidationText() for
this snippet to simplify it
genericValidationText('form[name="Form1"]');
*/
genericValidationSelect('form[name="Form1"]');
});
}());
function genericValidationSelect(formName) {
let notValid = false;
/* Iterate each select in the form */
$('select', formName).each(function() {
/* Check value in similar way. If null value,
then consider the select invalid */
var selectedOption = $(this).val();
if (selectedOption === null) {
notValid = true;
}
});
if(notValid) {
alert('Please select an option');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<!-- Fixed : remove closing form tag -->
<form name="Form1">
<!-- Fixed : typo -->
<label>Question 1</label>
<input type="text" class="required" name="question1">
<label>Question 2</lable>
<select class="required" name="question3">
<!-- Added default "no value option" to demonstrate validation -->
<option selected disabled>Please select something</option>
<option value="0">a</option>
<option value="1">b</option>
<option value="2">c</option>
<option value="3">d</option>
</select>
<button role="button"id="Go">Go</button>
</form>
Hope this helps!
The following should work:
const changeEventHandler = e => {
const value = e.target.options[e.target.selectedIndex].value;
console.log(value); //Validate value...
}
const select = document.querySelector('select[name=question3]').onchange = changeEventHandler;

Textbox value to check multiselect parameter based on values JS

Trying to assign ticks to a checkbox and have options selected if the value matches the values in the textbox. This a multi-select parameter.
E.g. if the textbox contains 1,2 when the page refreshes I want to ensure Cheese and Tomatoes is selected. If the textbox contains 1,5,6 then I want to ensure Cheese, Pepperoni and Onions are selected. If the textbox contains 1,2,3,4,5,6 then I want to ensure all checkboxes are selected.
Trying to write some javascript to do this. I tried to use local storage but can't get it working. See code example: https://www.codeply.com/go/rupzwTzBMY
ASPX:
<input type="text" runat="server" id="txt1" visible="true" value="" />
<div class="container">
<select id="basic" multiple="multiple">
<option value="1">Cheese</option>
<option value="2">Tomatoes</option>
<option value="3">Mozzarella</option>
<option value="4">Mushrooms</option>
<option value="5">Pepperoni</option>
<option value="6">Onions</option>
</select>
</div>
Currently when the page refreshes, even if the textbox has values assigned - the checkboxes clear and nothing is selected.
I am trying to ensure when users select items from the multi-parameter when the page refreshes those values are not gone and still remain on the page.
Javascript functionality that works so far. This puts values in a textbox when you select items from the drop-down. However, when the page refreshes the text box keeps these selected values but the multi-select parameter doesn't:
$('#basic').multiselect({
onChange: function () {
var selectedOptions = $('#basic').val();
document.getElementById("txt1").value = selectedOptions;
},
});
Firstly, you must reload the select once after populating default values as below
$('#basic').multiselect('refresh')
Secondly, try to use onInitialized method as described here
Finally, You're trying to assign back values from TextBox to Dropdown as below, where you're trying to assign the value as such with a comma 1,2 which actually doesn't exist as a value in dropdown.
External Fiddle
$('#basic').children("option[value=" +
document.getElementById("txt1").value + "]").prop("selected", true);
Split the values as 1 and 2 and then assign and it works.
$(document).ready(function () {
document.getElementById("txt1").value = "1,2,3"
$('#basic').multiselect({
includeSelectAllOption: true,
numberDisplayed: 5,
onInitialized: function(select, container) {
console.log("Init");
selectListValues();
}
});
$("#basic").multiselect('refresh');
});
function selectListValues()
{
var txtValue = document.getElementById("txt1").value;
var selectedValues = txtValue.split(",");
for(var i = 0; i < selectedValues.length; i++)
{
var val = selectedValues[i];
if (val == null || val == "") continue;
$('#basic').children("option[value=" + val + "]").prop("selected", "selected");
}
}
<html>
<head>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/css/bootstrap-multiselect.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
</head>
<body>
<input type="text" runat="server" id="txt1" visible="true" value="" onchange="selectListValues()" />
<div class="container">
<select id="basic" multiple="multiple">
<option value="1">Cheese</option>
<option value="2">Tomatoes</option>
<option value="3">Mozzarella</option>
<option value="4">Mushrooms</option>
<option value="5">Pepperoni</option>
<option value="6">Onions</option>
</select>
</div>
</body>
</html>
You can get and populate the value using local storage and split the item.
Note
I had to comment out the local storage so the demo code will work as local storage won't work cross domain. You will need to test this locally.
$(function() {
//$("#txt1").val(localStorage.getItem('topping'));
var str = $("#txt1").val().split(",");
$('#basic').val(str);
$('#basic').on('change', function(){
var list = $("#txt1").val($(this).val());
//localStorage.setItem('topping', list);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" runat="server" id="txt1" visible="true" value="1,2,4" />
<select id="basic" multiple="multiple">
<option value="1">Cheese</option>
<option value="2">Tomatoes</option>
<option value="3">Mozzarella</option>
<option value="4">Mushrooms</option>
<option value="5">Pepperoni</option>
<option value="6">Onions</option>
</select>
you can store input value in local storage, then get inputvalue from local storage then iterate on option set and set selected attribute to true of option if value is present in localstorage.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
<input type="text" runat="server" id="txt1" visible="true" value="" />
<div class="container">
<select id="basic" multiple>
<option value="1">Cheese</option>
<option value="2">Tomatoes</option>
<option value="3">Mozzarella</option>
<option value="4">Mushrooms</option>
<option value="5">Pepperoni</option>
<option value="6">Onions</option>
</select>
</div>
<script>
$(document).ready(function () {
$('#basic').multiselect({
onChange: function () {
var selectedOptions = $('#basic').val();
console.log(selectedOptions);
setInputAndLocatStorage();
}
});
function onLoad() {
if(!localStorage.getItem('selectedItems')) return false;
var selItems = localStorage.getItem('selectedItems').split(',');
document.getElementById('txt1').value = selItems.join(',');
$('#basic').multiselect('select',selItems);
}
function setInputAndLocatStorage() {
var selItems = $('#basic').val();
var val = selItems == null ? '': selItems.join(',');
document.getElementById('txt1').value = val;
localStorage.setItem('selectedItems', val);
}
onLoad();
});
</script>

JavaScript Validation for Listbox when mulitple values are selected

I want to do JavaScript validation for listbox
If Value from Lisbox is not selected, it should get alert "Please Select Your Skill"
But if user select 3 Skill from 6 Skill. I need that 3 skiils should get alert using JavaScript.
Here is my Code...
call script on submit button..
<html>
<head>
<script></script>
</head>
<body>
<form name="registration" id="registration_form_id" action="" method="post">
<select id="skillid1" name="skill[]" multiple="multiple" size="3" >
<option value="html">HTML</option>
<option value="css">CSS</option>
<option value="javascript">JAVASCRIPT</option>
<option value="php">PHP</option>
<option value="mysql">MY-SQL</option>
<option value="jquery">JQUERY</option>
</select>
<button type="submit" onClick="myFunction()">Submit</button>
</form>
</body>
</html>
Thank you
Rahul
First of all use onsubmit form event instead of button click. In this case you return false when the form should not be submitted. Here is an example:
function myFunction(form) {
var select = form['skill[]'];
// Check if skill is selected
if (select.selectedIndex === -1) {
alert("Please Select Your Skill");
return false;
}
// Check if selected 3 skills out of 6
if (select.selectedOptions.length) {
var options = [].map.call(select.selectedOptions, function(option) {
return option.text;
}).join('\n');
alert("You selected: \n" + options);
return true;
}
return false;
}
<form name="registration" id="registration_form_id" action="" method="post" onsubmit="return myFunction(this)">
<select id="skillid1" name="skill[]" multiple="multiple" size="3">
<option value="html">HTML</option>
<option value="css">CSS</option>
<option value="javascript">JAVASCRIPT</option>
<option value="php">PHP</option>
<option value="mysql">MY-SQL</option>
<option value="jquery">JQUERY</option>
</select>
<button type="submit">Submit</button>
</form>
Note that returning true from event handler will submit the form (in above demo submission is suppressed).
Here is JSFiddle demo.
To get the selected options from a multiple select, you should iterate over the options collection and collect the ones that are selected.
There is also the selectedOptions collection (per dfsq's answer), but support is patchy across browsers.
The looping method is made easier with a simple toArray function:
// Return an array of list members in numeric index order
// Respect sparse lists.
function toArray(list) {
var array = [];
// Use for loop for maximum compatibility
for (var i=0, iLen=list.length; i<iLen; i++) {
// Respect sparse lists
if (list.hasOwnProperty(i)) {
array[i] = list[i];
}
}
return array;
}
So if you have a reference to the select element, you can get the selected options using:
var selectedOptions = toArray(select.options).filter(function(option) {
return option.selected;
});
Now you can show the displayed text of each option in an alert using:
alert(selectedOptions.map(function(option){return option.text}).join('\n'));

Having a input text appear when chosen option in a double drop down select option

Say I want to create a double drop down select options where the second drop down list changes according to which the first drop down option is selected. I've already figured out how to do this. BUT one of my first drop option is "Others" and I want an input textbox to appear if I select "others" in the first dropdown list instead of having a second drop down option list. So far, I've been able to get the input textbox to appear, but the second drop down option list also appears (as undefined). How do I make the second drop down option list disappear?? Also, if one of the options in the first dropdown list doesn't need or have a second drop down option list, how do I code this?
This is an example of my script (I only changed the names of the categories):
<form name="search" method="get">
<select name="cat" id="cat" size="1" onChange="redirect(this.options.selectedIndex)">
<option selected disabled>Category</option>
<option value="fruit">Fruit</option>
<option value="music">Music</option>
<option value="vegetable">Vegetable</option>
<option value="book">Book</option>
<option value="other">Other</option>
</select>
<input type='text' id="other" class="hidden" />
<select name="cat2" size="1">
<option selected disabled>Sub-category</option>
</select>
<input type="button" name="Search" value="Search" onClick="go()" /
</form>
This is my javascript:
$('#cat').change(function(){
var selected_item = $(this).val()
if(selected_item == "other"){
$('#other').val("").removeClass('hidden');
}else{
$('#other').val(selected_item).addClass('hidden');
}
});
var groups=document.search.cat.options.length
var group=new Array(groups)
for (i=0; i<groups; i++)
group[i]=new Array()
group[0][0]=0
group[1][0]=new Option("Moodle")
group[1][1]=new Option("Ultranet")
group[1][2]=new Option("Private School")
group[2][0]=new Option("Gmail")
group[2][1]=new Option("Windows Live")
group[2][2]=new Option("Office 365")
group[3][0]=0 //has no second dropdown option, how do I make it disappear?
group[4][0]=new Option("Kamar")
group[4][1]=new Option("Musac")
group[5][0]=new Option("Windows")
group[5][1]=new Option("Mac")
group[5][2]=new Option("Novell")
group[5][3]=new Option("Linux")
group[6][0]=new Option("Ruckus Wireless")
group[6][1]=new Option("Aerohive Networks")
group[6][2]=new Option("Aruba Networks")
group[7][0]=new Option("Pre-Trial")
group[7][1]=new Option("Implementation")
group[7][2]=new Option("Full Trial")
group[8][0]=0 //The 'others', I don't know what to put here to make this disappear
var temp=document.search.cat2
function redirect(x){
for (m=temp.options.length-1;m>0;m--)
temp.options[m]=null
for (i=0;i<group[x].length;i++){
temp.options[i]=new Option(group[x][i].text,group[x][i].value)
}
temp.options[0].selected=true
}
function go(){
location=temp.options[temp.selectedIndex].value
}
You need to add 2 new lines to the .change function, from:
$('#cat').change(function(){
var selected_item = $(this).val()
if(selected_item == "other"){
$('#other').val("").removeClass('hidden');
}else{
$('#other').val(selected_item).addClass('hidden');
}
});
Change it to
$('#cat').change(function(){
var selected_item = $(this).val()
if(selected_item == "other"){
$('#other').val("").removeClass('hidden');
$("select[name=cat2]").addClass('hidden');
}else{
$('#other').val(selected_item).addClass('hidden');
$("select[name=cat2]").removeClass('hidden');
}
});
So when you remove hidden class from the input you have to add it to the select with name "cat2", and vice-versa. Hope this helps you.

JavaScript not showing text area on change of select

function otherShow() {
var textarea = document.getElementById("hideme");
var x = document.forms.myForm.other_trade.value;
if (x == "other") {
textarea.style.display = 'block';
}else {
textarea.style.display = 'none';
}
}
This is my JavaScript code that is supposed to hide the text area that holds the ID=hideme and the action is triggered onchange="otherShow();"
<select name="trade" required="required" class="inputbox" id="trade" onchange="otherShow();">
<option value="" selected="selected"> Select one... </option>
<option value="" disabled="disabled"> ---------------------- </option>
<option value="General Labourer">Option1</option>
.......
</select>
The above is the Select and below is the Textarea
<textarea cols="36" rows="6" class="inputbox" id="hideme" name="other_trade"></textarea>
In the end of the Select i have a
<option value="Other"> Other </other>
I want to show the Text area when the Other is selected. Please help I think the loginc is correct but it just do not work when I change it to some value it hides the text area, but do not change it...
the name of the select box is trade not other_trade:
var x = document.forms.myForm.trade.value;
or :
var x = this.value;
instead of :
var x = document.forms.myForm.other_trade.value;
Here is how I would do it
window.onload=function() {
document.getElementById("trade").onchange=function() {
var textarea = this.form.other_trade;
textarea.style.display=(this.value=="Other")?"block":"none";
}
}
Replace other to Other in your javascript show/hide condition, because it's compare case sensative

Categories

Resources