Disable select option based on innerhtml with pure JavaScript - javascript

Scenario: User votes via HTML form for a field trip to take on a bus. There are three options:
<select id="selectbox">
<option>Berlin</option>
<option>Munich</option>
<option>Cologne</option>
</select>
The free bus seats are stored in / read from a database: ($tour is our array keeping the free seats)
<table class="status">
<tr><td>Berlin: <span id="t1">available (<?php echo $tour[0]; ?> seats)</span></td></tr>
<tr><td>Munich: <span id="t2">available (<?php echo $tour[1]; ?> seats)</span></td></tr>
<tr><td>Cologne: <span id="t3">available (<?php echo $tour[2]; ?> seats)</span></td></tr>
</table>
If free seats are zero, we display a "sorry, booked out" info using vanilla JavaScript:
// get content of status table
var t1 = document.getElementById("t1").innerHTML;
var t2 = document.getElementById("t2").innerHTML;
var t3 = document.getElementById("t3").innerHTML;
var bookedout = "sorry, booked out!"
// check if condition is met
if (t1 == "available (0 seats)") {
document.getElementById("t1").innerHTML = bookedout;
}
if (t2 == "available (0 seats)") {
document.getElementById("t2").innerHTML = bookedout ;
}
if (t3 == "available (0 seats)") {
document.getElementById("t3").innerHTML = bookedout ;
}
Works fine. However, now comes the part I'm a bit lost. The above condition should also delete the respective option from #selectbox based on the option's innerHTML. In jQuery I'd go with something like #selectbox option:contains('stringhere').
However, I wanna do it in the purest of JavaScript. Any ideas?

It's fairly straight forward..
First in your html give vlaues to your options:
<select id="selectbox">
<option>Berlin</option>
<option>Munich</option>
<option>Cologne</option>
</select>
Then in js:
var mySelect = document.getElementById("selectbox");
//function to get option values as array
function getOptionsArr() {
var optionsArray =[],options = mySelect.options;
var i = 0, len = options.length;
// store the options value in an array
while (i < len)
{
optionsArray.push(options[i++].value);
}
return optionsArray;
}
var t1 = document.getElementById("t1").innerHTML;
var t2 = document.getElementById("t2").innerHTML;
var t3 = document.getElementById("t3").innerHTML;
var bookedout = "sorry, booked out!"
// check if condition is met
if (t1 == "available (0 seats)"){
document.getElementById("t1").innerHTML = bookedout;
//this will get the whole parent node and child node inner text we split at : and get the value
var textArr = document.getElementById("t1").parentElement.innerText.split(':');
// find the index of value from our array created above and remove that option from select
mySelect.remove(getOptionsArr().indexOf(textArr [0]))
}
//repeat the same for other
if (t2 == "available (0 seats)"){
document.getElementById("t2").innerHTML = bookedout ;
var textArr = document.getElementById("t2").parentElement.innerText.split(':');
mySelect.remove(getOptionsArr().indexOf(textArr [0]))
}
if (t3 == "available (0 seats)"){
document.getElementById("t3").innerHTML = bookedout ;
var textArr = document.getElementById("t3").parentElement.innerText.split(':');
mySelect.remove(getOptionsArr().indexOf(textArr [0]))
}
Aditionally you can refactor it by
var mySelect = document.getElementById("selectbox");
//function to get option values as array
function getOptionsArr() {
var optionsArray =[],options = mySelect.options;
var i = 0, len = options.length;
// store the options value in an array
while (i < len)
{
optionsArray.push(options[i++].value);
}
return optionsArray;
}
var t1 = document.getElementById("t1").innerHTML;
var t2 = document.getElementById("t2").innerHTML;
var t3 = document.getElementById("t3").innerHTML;
var bookedout = "sorry, booked out!"
// check if condition is met
if (t1 == "available (0 seats)"){
doUpdateDOM("t1")
}
if (t2 == "available (0 seats)"){
doUpdateDOM("t2")
}
if (t3 == "available (0 seats)"){
doUpdateDOM("t3")
}
function doUpdateDOM(nodeID){
document.getElementById(nodeID).innerHTML = bookedout;
var textArr = document.getElementById(nodeID).parentElement.innerText.split(':');
mySelect.remove(optionsArray.indexOf(textArr [0]))
}

Assuming that the order of the options inside the select correspond to the order inside the table element you could simply do something like this.
var select = document.getElementById('selectbox');
var table = document.getElementsByClassName('status').item(0);
var rows = table.rows;
var bookedout = " sorry, booked out!";
// check whether an option is bookedout
// and save its state to a new array.
var bookedOutState = [].slice.call(rows).map(function(row) {
var match = row.children[0].textContent.match(/\d/);
if (+match[0] === 0) {
row.children[0].textContent = match['input'].substr(0, match['input'].indexOf(':') + 1) + bookedout;
return false;
}
return true;
})
// go over the new created array and remove
// options from select according to the saved state.
bookedOutState.forEach(function(state, idx) {
if (!state) {
select.removeChild(select.children[idx])
}
})
<select id="selectbox">
<option>Berlin</option>
<option>Munich</option>
<option>Cologne</option>
</select>
<table class="status">
<tr><td>Berlin: <span id="t1">available 0 seats</span></td></tr>
<tr><td>Munich: <span id="t2">available 1 seats</span></td></tr>
<tr><td>Cologne: <span id="t3">available 2 seats</span></td></tr>
</table>

Related

The sum cannot show although i click on the button

What I want is, after the user enters the number of subjects, the system will show the number of input box according to the number of subjects entered, then when the user clicks on the button, it should show the sum. I tried many ways, but I failed to show the sum, anyone knows what is the mistake I made?
Below is my code:
function select() {
var x = parseInt(document.getElementById('1').value);
if (document.getElementById('1').value == "") {
alert("Please fill up number of subject");
} else if (isNaN(x) == true) {
alert("Please fill up number of subject with number");
} else {
var subject = parseInt(document.getElementById('1').value);
var sum = 0;
for (var num = 1; num <= subject; num++) {
document.write("Enter the mark for subject " + num + " : ");
var value = parseFloat(document.write("<input/><br>"));
sum += value;
}
var calc = document.write("<button>Next</button><br>");
calc.onclick = function() {
next()
};
function next() {
document.write("Total marks: " + sum + "%");
}
}
}
<html>
<body>
Enter the number of subject: <input type="text" onkeypress="return/[0-9]/i.test(event.key)" id="1" value=""><br>
<button onclick="select()">Check</button><br>
</body>
</html>
That's how I have rewritten a big part of your code. I have place inline comments to explain what I do.
function select() {
var x = parseInt(document.getElementById('1').value, 10);
// Getting the div that wraps the initial form.
var formWrapper = document.querySelector('.formWrapper');
// Getting the div, that is going to display the new fields and the results.
var results = document.querySelector('.results');
// I have switch your statement from x == '' to '' === x as it
// consists a good practice
if ( '' === x ) {
alert("Please fill up number of subject");
// I have remove the isNaN(x) == true, because the isNan will
// be either true or false.
} else if ( isNaN(x) ) {
alert("Please fill up number of subject with number");
} else {
// Using parseInt(x, 10) to set the base.
var subject = parseInt(x, 10);
// In this array, I store the auto-generated fields.
var fieldsList = [];
// Removing the first div from the DOM
formWrapper.parentElement.removeChild(formWrapper);
for ( var num = 1; num <= subject; num++ ) {
// I am creating a new field
var newField = document.createElement('input');
// I push the field into the array I made for the fields.
fieldsList.push(newField);
// I append the field in the HTML
results.appendChild(newField);
// I create a <br> tag
var br = document.createElement('br');
// And I append the tag in the DOM
results.appendChild(br);
}
// I create the button that is going to handle the Next functionality
var nextButton = document.createElement('button');
// I set the button text
nextButton.innerText = 'Next';
// I add an Event Listener for the click event.
nextButton.addEventListener(
'click',
function() {
// I reset the sum to 0
var sum = 0;
// I itterate the fields auto-generated and saved in the array
fieldsList.forEach(
function(field) {
// I get the value
sum += parseInt(field.value, 10);
}
);
// I create the field that is going to display the output
let resultText = document.createElement('div');
// I set the text based on the sum
resultText.innerText = "Total marks: " + sum + "%";
// I append the text message to the DOM
results.appendChild(resultText);
}
);
// I append the button to the DOM
results.appendChild(nextButton);
}
}
<html>
<body>
<div class="formWrapper">
Enter the number of subject: <input type="text" onkeypress="return/[0-9]/i.test(event.key)" id="1" value=""><br>
<button onclick="select()">Check</button><br>
</div>
<div class="results"></div>
</body>
</html>

Dropdown selection value doesn't become a real value and work in JavaScript

I have a language dropdown and I try to alert the user to have to choose one language before doing anything further like languageOption can become a string and go into array. But it's not working and I don't understand why. I tried:
alert("You didn't choose any language.");
console.alert("You didn't choose any language.");
console.log("You didn't choose any language.");
But they all don't work.
And I thought another way to solve this, which I make
<option value="1" selected>English (American)</option>
but then the value = "1" doesn't become the a value for variable 'languageOption'. So the arrays don't respond and don't know what to do when I see in console. I don't understand why the array is not responding.
Any help I would appreciate.
Below is my code:
<select id="languageSelection" style=display:none>
<option value="">Choose a language</option>
<option value="1">English (American)</option>
<option value="2">Chinese (Mandarin)</option>
<option value="3">Japanese</option>
</select>
var audioSrc = "sound/"
var audioType = ".wav";
// default number of random question, if user this used the dropdown
var default_numFollowUp = 4;
// default delai (seconds) between random questions, if user this used the dropdown
var default_secFollowUp = 10;
// Create the audio element
var audioElement = document.createElement('audio');
var endingArr = [];
var runThroughArr = [];
var randomArr = [];
var languageOption = parseInt($("#languageSelection").val() );
$("#languageSelection").on("change", function(){
languageOption = $(this).val(); // Make languageOption value be string
//if(languageOption.length==0){languageOption=1;}
console.log("langugeOption is " + languageOption);
console.log("Language changed to: "+ $(this).find("option").eq( $(this)[0].selectedIndex ).text() + " (Index: "+languageOption+")" );
console.log(typeof(languageOption)); // Outputs string
endingArr = [];
runThroughArr = [];
randomArr = [];
if(languageOption === ""){
alert("You didn't choose any language.");
console.alert("You didn't choose any language.");
console.log("You didn't choose any language.");
}
else if(languageOption === "1"){
console.log("English");
for(i = 0; i < intro_playList.length; i++){
if(intro_playList[i].stage === "ending"){ endingArr.push(i); }
if(intro_playList[i].runThrough){ runThroughArr.push(i); }
if(intro_playList[i].random){ randomArr.push(i); }
}
}
else if (languageOption === "2"){
console.log("Chinese");
for(i = 0; i < intro_playList_chi.length; i++){
if(intro_playList_chi[i].stage === "ending"){ endingArr.push(i); }
if(intro_playList_chi[i].runThrough){ runThroughArr.push(i); }
if(intro_playList_chi[i].random){ randomArr.push(i); }
}
}
});
You need to assign the onchange function after loading the document. With jQuery, you can do it like this
var languageOption;
$(document).on("ready", function() {
languageOption = $("#languageSelection").val();
$("#languageSelection").on("change", function() {
your code here ...
}
}

"Check All" checkbox shows ambiguous behaviour with pagination

thanks for being so supportive to the topics asked. I have a built a 'User Approval' system wherein the admin gets list of registered users and approves them by using checkboxes for each and 'Check all' that selects all users. Table has pagination of 10 users at once. My issue here is when I 'check all' on the second page with 10 users, the table automatically selects and displays the first 10 users also i.e. the first page with 10 users. How can I stop the page to second list only when "check all" is implemented on second list of 10 candidates. I am confused on where it has gone wrong and getting no clue . Any help or advice will be appreciated and helpful. Here is the code for javascript that I have used,
<script type="text/javascript">
var select_all = document.getElementById("select_all"); //select all checkbox
var checkboxes = document.getElementsByClassName("checkbox"); //checkbox items
//select all checkboxes
select_all.addEventListener("change", function(e){
for (i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = select_all.checked;
}
});
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('change', function(e){ //".checkbox" change
//uncheck "select all", if one of the listed checkbox item is unchecked
if(this.checked == false){
select_all.checked = false;
}
//check "select all" if all checkbox items are checked
if(document.querySelectorAll('.checkbox:checked').length == checkboxes.length){
select_all.checked = true;
}
});
}
</script>
And the php+html for the table header "Check all"
<input type="checkbox" id="select_all" name="all_check[]" <?php echo $disabled ;?> class="checkbox" value= "<?php //echo $row['id']; ?>"> </th>
And my pagination class,
<?php
class pagination
{
var $page = 1; // Current Page
var $perPage = 10; // Items on each page, defaulted to 10
var $showFirstAndLast = false; // if you would like the first and last page options.
function generate($array, $perPage = 10)
{
// Assign the items per page variable
if (!empty($perPage))
$this->perPage = $perPage;
// Assign the page variable
if (!empty($_GET['page'])) {
$this->page = $_GET['page']; // using the get method
} else {
$this->page = 1; // if we don't have a page number then assume we are on the first page
}
// Take the length of the array
$this->length = count($array);
// Get the number of pages
$this->pages = ceil($this->length / $this->perPage);
// Calculate the starting point
$this->start = ceil(($this->page - 1) * $this->perPage);
// Return the part of the array we have requested
return array_slice($array, $this->start, $this->perPage);
}
function links()
{
// Initiate the links array
$plinks = array();
$links = array();
$slinks = array();
// Concatenate the get variables to add to the page numbering string
if (count($_GET)) {
$queryURL = '';
foreach ($_GET as $key => $value) {
if ($key != 'page') {
$queryURL .= '&'.$key.'='.$value;
}
}
}
// If we have more then one pages
if (($this->pages) > 1)
{
// Assign the 'previous page' link into the array if we are not on the first page
if ($this->page != 1) {
if ($this->showFirstAndLast) {
$plinks[] = ' «« First ';
}
$plinks[] = ' « Prev ';
}
// Assign all the page numbers & links to the array
for ($j = 1; $j < ($this->pages + 1); $j++) {
if ($this->page == $j) {
$links[] = ' <a style="font-weight: bold;">'.$j.'</a> '; // If we are on the same page as the current item
} else {
$links[] = ' '.$j.' '; // add the link to the array
}
}
// Assign the 'next page' if we are not on the last page
if ($this->page < $this->pages) {
$slinks[] = ' Next » ';
if ($this->showFirstAndLast) {
$slinks[] = ' Last »» ';
}
}
// Push the array into a string using any some glue
return implode(' ', $plinks).implode($this->implodeBy, $links).implode(' ', $slinks);
}
return;
}
}
?>

How can I refresh second select option when first select option is changed?

How can I refresh second select option when first select option is changed?
I am generating the array here for patient_code2:
//GENERATE NUMBERS FOR CYCLE
function patsient(selector) {
var i;
for (i = 1; i <= 99; i++) {
var text = '0' + i;
selector.options[i - 1] = new Option(text.substr(text.length - 2, 2));
}
}
patsient(document.getElementById("patient_code2"));
I am generating the array for patient_code here:
function myFunction(selector) {
var i;
for (i = 1; i <= 999; i++) {
var text = '00' + i;
selector.options[i - 1] = new Option(text.substr(text.length - 3, 3));
}
}
//usage:
myFunction(document.getElementById("patient_code"));
Here I am inserting the last value from database to the field:
//INSERT THE VALUE FROM DATABASE
var tsykkel_id = '<?php foreach ($tsykkel_id as $row){echo $row['patsiendi_tsykkel'];}?>';
$('#patient_code2')[0].options[parseInt(tsykkel_id)].selected = true;
$(document).ready().on('change', '#patient_code2', function () {
var index = $('option:selected', $(this)).index();
$('option', $(this)).each(function (i, x) {
if (i < index) { $(this).remove(); }
});
});
HTML
<select name="patient_code" data-placeholder="" id="patient_code" class="chosen-select form-control" tabindex="2">
</select>
<label class="control-label">Tsükkel:</label>
<select name="patient_code2" data-placeholder="" id="patient_code2" class="chosen-select form-control" tabindex="2">
</select>
So lets say that person chooses 002 from the first then the second should start from 01 again.
try this then. Code is tested.
$(document).ready().on('change','#patient_code2',function(){
var index = $('option:selected',$(this)).index();
$('option',$(this)).each(function(i,x){
if(i<index){$(this).remove();}
});
$('select#patient_code').prop('selectedIndex', 0);
});
fiddle : http://jsfiddle.net/roullie666/69j94ro6/2/
You can just start printing after the match has been found. I am writing both ways since you asked?
For javascript version use roullie's no point duplicating.
<?php
$flag = false;
foreach ($tsykkel_id as $row) {
if ($selected) {
$flag = true;
}
if ($flag) {
$row['patsiendi_tsykkel'];
}
}?>

How to add an option to a dropdown menu created by JavaScript

Hi I am 15 and just starting to learn HTML CSS and JavaScript.
I am trying to edit a drop down menu for listing all 50 states on a checkout page, by default it is blank when the page loads and i want it to say "State". I am trying to make one more option that says "State" with a attribute of selected and disabled. I have no clue on how to do this because it is all JavaScript and i have looked online and have found nothing.
So i need some help on how to do this, i have no idea how to do it in JavaScript
I didn't write any of this code and i don't know what most of it even does, that is why i gave you the whole document, i am just trying to edit it.
Here is the JavaScript/PHP i am trying to edit.
// If you have PHP you can set the post values like this
//var postState = '<?= $_POST["state"] ?>';
//var postCountry = '<?= $_POST["country"] ?>';
var postState = 'US';
var postCountry = 'FL';
// State table
//
// To edit the list, just delete a line or add a line. Order is important.
// The order displayed here is the order it appears on the drop down.
//
var stateList = '\
US:AL:Alabama|\
US:AK:Alaska|\
CA:AB:Alberta|\
US:AZ:Arizona|\
US:AR:Arkansas|\
CA:BC:British Columbia|\
US:CA:California|\
US:CO:Colorado|\
US:CT:Connecticut|\
US:DE:Delaware|\
US:DC:District of Columbia|\
US:FL:Florida|\
US:GA:Georgia|\
US:HI:Hawaii|\
US:ID:Idaho|\
US:IL:Illinois|\
US:IN:Indiana|\
US:IA:Iowa|\
US:KS:Kansas|\
US:KY:Kentucky|\
US:LA:Louisiana|\
US:ME:Maine|\
CA:MB:Manitoba|\
US:MD:Maryland|\
US:MA:Massachusetts|\
US:MI:Michigan|\
US:MN:Minnesota|\
US:MS:Mississippi|\
US:MO:Missouri|\
US:MT:Montana|\
US:NE:Nebraska|\
US:NV:Nevada|\
CA:NB:New Brunswick|\
US:NH:New Hampshire|\
US:NJ:New Jersey|\
US:NM:New Mexico|\
US:NY:New York|\
CA:NL:Newfoundland and Labrador|\
US:NC:North Carolina|\
US:ND:North Dakota|\
CA:NT:Northwest Territories|\
CA:NS:Nova Scotia|\
CA:NU:Nunavut|\
US:OH:Ohio|\
US:OK:Oklahoma|\
CA:ON:Ontario|\
US:OR:Oregon|\
US:PA:Pennsylvania|\
CA:PE:Prince Edward Island|\
US:PR:Puerto Rico|\
CA:QC:Quebec|\
US:RI:Rhode Island|\
CA:SK:Saskatchewan|\
US:SC:South Carolina|\
US:SD:South Dakota|\
US:TN:Tennessee|\
US:TX:Texas|\
US:UT:Utah|\
US:VT:Vermont|\
US:VI:Virgin Islands|\
US:VA:Virginia|\
US:WA:Washington|\
US:WV:West Virginia|\
US:WI:Wisconsin|\
US:WY:Wyoming|\
CA:YT:Yukon Territory|\
';
// Country data table
//
// To edit the list, just delete a line or add a line. Order is important.
// The order displayed here is the order it appears on the drop down.
//
var country = '\
AF:Afghanistan|\
AX:Aland Islands|\
AL:Albania|\
DZ:Algeria|\
AS:American Samoa|\
AD:Andorra|\
AO:Angola|\
AI:Anguilla|\
AQ:Antarctica|\
AG:Antigua & Barbuda|\
AR:Argentina|\
AM:Armenia|\
AW:Aruba|\
AU:Australia|\
AT:Austria|\
AZ:Azerbaijan|\
AP:Azores|\
BS:Bahamas|\
BH:Bahrain|\
BD:Bangladesh|\
BB:Barbados|\
BY:Belarus|\
BE:Belgium|\
BZ:Belize|\
BJ:Benin|\
BM:Bermuda|\
BT:Bhutan|\
BO:Bolivia|\
BL:Bonaire|\
BA:Bosnia|\
BW:Botswana|\
BV:Bouvet Island|\
BR:Brazil|\
VG:British Virgin Islands|\
BN:Brunei|\
BG:Bulgaria|\
BF:Burkina Faso|\
BI:Burundi|\
KH:Cambodia|\
CM:Cameroon|\
CA:Canada|\
IC:Canary Islands|\
CV:Cape Verde Islands|\
KY:Cayman Islands|\
CF:Central African Republic|\
TD:Chad|\
CD:Channel Islands|\
CL:Chile|\
CN:China|\
CX:Christmas Island|\
CC:Cocos (keeling) Islands|\
CO:Colombia|\
CG:Congo|\
CK:Cook Islands|\
CR:Costa Rica|\
CI:Cote Divoire|\
HR:Croatia|\
CB:Curacao|\
CY:Cyprus|\
CZ:Czech Republic|\
DK:Denmark|\
DJ:Djibouti|\
DM:Dominica|\
DO:Dominican Republic|\
EC:Ecuador|\
EG:Egypt|\
SV:El Salvador|\
EN:England|\
GQ:Equitorial Guinea|\
ER:Eritrea|\
EE:Estonia|\
ET:Ethiopia|\
FO:Faeroe Islands|\
FK:Falkland Islands (Malvinas)|\
FJ:Fiji|\
FI:Finland|\
FR:France|\
GF:French Guiana|\
PF:French Polynesia|\
TF:French Southern Territories|\
GA:Gabon|\
GM:Gambia|\
GE:Georgia|\
DE:Germany|\
GH:Ghana|\
GI:Gibraltar|\
GR:Greece|\
GL:Greenland|\
GD:Grenada|\
GP:Guadeloupe|\
GU:Guam|\
GT:Guatemala|\
GG:Guernsey|\
GN:Guinea|\
GW:Guinea-Bissau|\
GY:Guyana|\
HT:Haiti|\
HM:Heard Island and Mcdonald Islands|\
HO:Holland|\
VA:Holy See (Vatican City State)|\
HN:Honduras|\
HK:Hong Kong|\
HU:Hungary|\
IS:Iceland|\
IN:India|\
ID:Indonesia|\
IR:Iran|\
IQ:Iraq|\
IE:Ireland|\
IM:Isle of Man|\
IL:Israel|\
IT:Italy|\
JM:Jamaica|\
JP:Japan|\
JE:Jersey|\
JO:Jordan|\
KZ:Kazakhstan|\
KE:Kenya|\
KI:Kiribati|\
KP:Korea, Democratic People\'s Republic of|\
KR:Korea, Republic of|\
KO:Kosrae|\
KW:Kuwait|\
KG:Kyrgyzstan|\
LA:Laos|\
LV:Latvia|\
LB:Lebanon|\
LS:Lesotho|\
LR:Liberia|\
LY:Libyan Arab Jamahiriya|\
LI:Liechtenstein|\
LT:Lithuania|\
LU:Luxembourg|\
MO:Macau|\
MK:Macedonia, Republic of|\
MG:Madagascar|\
MW:Malawi|\
MY:Malaysia|\
MV:Maldives|\
ML:Mali|\
MT:Malta|\
MH:Marshall Islands|\
MQ:Martinique|\
MR:Mauritania|\
MU:Mauritius|\
YT:Mayotte|\
MX:Mexico|\
FM:Micronesia, Federated States of|\
MD:Moldova|\
MC:Monaco|\
MN:Mongolia|\
ME:Montenegro, Republic of|\
MS:Montserrat|\
MA:Morocco|\
MZ:Mozambique|\
MM:Myanmar|\
NA:Namibia|\
NR:Nauru|\
NP:Nepal|\
NL:Netherlands|\
AN:Netherlands Antilles|\
NC:New Caledonia|\
NZ:New Zealand|\
NI:Nicaragua|\
NE:Niger|\
NG:Nigeria|\
NU:Niue|\
NF:Norfolk Island|\
NB:Northern Ireland|\
MP:Northern Mariana Islands|\
NO:Norway|\
OM:Oman|\
PK:Pakistan|\
PW:Palau|\
PS:Palestinian Territory, Occupied|\
PA:Panama|\
PG:Papua New Guinea|\
PY:Paraguay|\
PE:Peru|\
PH:Philippines|\
PN:Pitcairn Island|\
PL:Poland|\
PO:Ponape|\
PT:Portugal|\
PR:Puerto Rico|\
QA:Qatar|\
RE:Reunion|\
RO:Romania|\
RT:Rota|\
RU:Russia|\
RW:Rwanda|\
SS:Saba|\
SP:Saipan|\
SM:San Marino|\
ST:Sao Tome and Principe|\
SA:Saudi Arabia|\
SF:Scotland|\
SN:Senegal|\
RS:Serbia, Republic of|\
SC:Seychelles|\
SL:Sierra Leone|\
SG:Singapore|\
SK:Slovakia|\
SI:Slovenia|\
SB:Solomon Islands|\
SO:Somalia|\
ZA:South Africa|\
ES:Spain|\
LK:Sri Lanka|\
NT:St. Barthelemy|\
SW:St. Christopher|\
SX:St. Croix|\
EU:St. Eustatius|\
UV:St. John|\
KN:St. Kitts & Nevis|\
LC:St. Lucia|\
MB:St. Maarten|\
TB:St. Martin|\
VL:St. Thomas|\
VC:St. Vincent & the Grenadines|\
SD:Sudan|\
SR:Suriname|\
SZ:Swaziland|\
SE:Sweden|\
CH:Switzerland|\
SY:Syrian Arab Republic|\
TA:Tahiti|\
TW:Taiwan|\
TJ:Tajikistan|\
TZ:Tanzania|\
TH:Thailand|\
TL:Timor-Leste|\
TI:Tinian|\
TG:Togo|\
TO:Tonga|\
TT:Trinidad and Tobago|\
TU:Truk|\
TN:Tunisia|\
TR:Turkey|\
TM:Turkmenistan|\
TC:Turks & Caicos Islands|\
TV:Tuvalu|\
UG:Uganda|\
UA:Ukraine|\
UI:Union Island|\
AE:United Arab Emirates|\
GB:United Kingdom|\
US:United States|\
UY:Uruguay|\
VI:US Virgin Islands|\
UZ:Uzbekistan|\
VU:Vanuatu|\
VE:Venezuela|\
VN:Vietnam|\
VR:Virgin Gorda|\
WK:Wake Island|\
WL:Wales|\
WF:Wallis and Futuna|\
EH:Western Sahara|\
WS:Western Samoa|\
YA:Yap|\
YE:Yemen|\
ZR:Zaire|\
ZM:Zambia|\
ZW:Zimbabwe|\
';
country = country.substring(0, country.length-1) // Deleting the last "|" character
function get_Element(i)
{
return document.getElementById(i) || document.getElementsByName(i).item(0);
}
function TrimString(sInString) {
if ( sInString ) {
sInString = sInString.replace( /^\s+/g, "" );// strip leading
return sInString.replace( /\s+$/g, "" );// strip trailing
}
}
// Populates the country selected with the counties from the country list
function populateCountry(defaultCountry,countryfieldname) {
if (defaultCountry=="") {defaultCountry="US"}
var countryLineArray = country.split('|'); // Split into lines
var selObj = get_Element(countryfieldname);
if (!selObj) return;
selObj.options[0] = new Option('','');
selObj.selectedIndex = 0;
for (var loop = 0; loop < countryLineArray.length; loop++) {
lineArray = countryLineArray[loop].split(':');
countryCode = TrimString(lineArray[0]);
countryName = TrimString(lineArray[1]);
if ( countryCode != '' ) { selObj.options[loop] = new Option(countryName, countryCode); }
if ( defaultCountry == countryCode ) { selObj.selectedIndex = loop; }
}
}
function populateState(statefieldname,countryfieldname,state1,optionalCreateTextField) {
//optionalCreateTextField = optional parameter, true/false. When a country doesn't have state, it'll determine if the code creates a text field for the state or just let the dropdown empty.
var isOpera = false, isIE = false;
var strClassName;
var originalTabIndex;
if(typeof(window.opera) != 'undefined')
{isOpera = true;}
if(!isOpera && (navigator.userAgent.indexOf('Internet Explorer') > 0 || navigator.userAgent.indexOf('MSIE') > 0) && navigator.userAgent.indexOf('MSIE 9') < 0 && navigator.userAgent.indexOf('MSIE 10') < 0)
{isIE = true;}
if (state1==undefined) {state1='';}
postCountry=get_Element(countryfieldname);
if (!postCountry) return;
postCountry=postCountry.value;
var selObj = get_Element(statefieldname);
if (!selObj) return;
var foundState = false;
originalTabIndex = selObj.getAttribute("tabindex");
// Empty options just in case new drop down is shorter
if ( selObj.type == 'select-one' ) {
selObj.options.length = 0;
// selObj.options[0] = new Option('Select State','');
// selObj.selectedIndex = 0;
}
// Populate the drop down with states from the selected country
//
var stateLineArray = stateList.split("|"); // Split into lines
var optionCntr = 0;
for (var loop = 0; loop < stateLineArray.length; loop++) {
lineArray = stateLineArray[loop].split(":");
countryCode = TrimString(lineArray[0]);
stateCode = TrimString(lineArray[1]);
stateName = TrimString(lineArray[2]);
if ( get_Element(countryfieldname).value == countryCode && countryCode != '' ) {
// If it's a input element, change it to a select
//
if ( selObj.type == 'text' ) {
strClassName = selObj.className;
parentObj = get_Element(statefieldname).parentNode;
// Create the Input Field
if(!isIE){
var inputSel = document.createElement("SELECT");
inputSel.setAttribute("name", statefieldname);
if (strClassName != 'undefined' && strClassName != '')
inputSel.setAttribute("class",strClassName);
else
inputSel.setAttribute("class","txtBoxStyle");
inputSel.setAttribute("id", statefieldname);
}
else
{
var inputSel = document.createElement("<select name="+statefieldname+" id="+statefieldname+">");
if (strClassName != 'undefined' && strClassName != '')
inputSel.setAttribute("className",strClassName);
else
inputSel.setAttribute("className","txtBoxStyle");
}
inputSel.setAttribute("tabindex", originalTabIndex);
parentObj.insertBefore(inputSel, selObj.nextSibling);
parentObj.removeChild(selObj);
selObj = get_Element(statefieldname);
}
if (optionCntr==0)
{
selObj.options[optionCntr] = new Option('','');
selObj.selectedIndex = optionCntr;
optionCntr++;
}
if ( stateCode != '' ) {
selObj.options[optionCntr] = new Option(stateName, stateCode);
}
// See if it's selected from a previous post
//
if ( stateCode == state1 && countryCode == postCountry ) {
selObj.selectedIndex = optionCntr;
}
foundState = true;
optionCntr++
}
}
// If the country has no states, change the select to a text box
//
if ( ! foundState ) {
if (postCountry == 'ALL')
{
//var selObj = get_Element(statefieldname);
selObj.options.length = 0;
selObj.options[0] = new Option('ALL','ALL');
selObj.selectedIndex = 0;
}
else
{
if (optionalCreateTextField == undefined)
var createText = true;
else
var createText = optionalCreateTextField;
if (createText)
{
strClassName = selObj.className;
parentObj = get_Element(statefieldname).parentNode;
// Create the Input Field
if(!isIE){
var inputEl = document.createElement("input");
inputEl.setAttribute("name", statefieldname);
if (strClassName != 'undefined' && strClassName != '')
inputEl.setAttribute("class",strClassName);
else
inputEl.setAttribute("class","txtBoxStyle");
inputEl.setAttribute("id", statefieldname);
}
else
{
var inputEl = document.createElement("<input name=\""+statefieldname+"\" id=\""+statefieldname+"\" />");
if (strClassName != 'undefined' && strClassName != '')
inputEl.setAttribute("className",strClassName);
else
inputEl.setAttribute("className","txtBoxStyle");
}
inputEl.setAttribute("tabindex", originalTabIndex);
inputEl.setAttribute("type", "text");
inputEl.setAttribute("size", 20);
inputEl.setAttribute("value", state1);
parentObj.insertBefore(inputEl, selObj.nextSibling);
parentObj.removeChild(selObj);
}
}
}
}
function insertCountry(strCountryName,countryfieldname) {
var selObj = get_Element(countryfieldname);
if (!selObj) return;
selObj.options[selObj.options.length] = new Option('ALL','ALL');
selObj.selectedIndex = selObj.options.length-1;
}
function initCountry(country,state1,statefieldname,countryfieldname) {
populateCountry(country,countryfieldname);
populateState(statefieldname,countryfieldname,state1);
}
function GetValue(formx,name1) {
//alert(name1);
var i;
for(i=0;i<formx.elements.length;i++) {
if(formx.elements[i].name==name1) {
return formx.elements[i].value;
}
}
}
And Here is the HTML
<div class="chkField">
<label for="billing_state">[CustomerInfo_state]</label>
<select id="billing_state" onchange="this.form.billing_zip.value='';check_address('billing');" name="billing_state" tabindex="9" class="txtBoxStyle">
</select>
I don't know how to edit JavaScript very well but it seems to be creating HTML options on the web page and i dont know how to create another one that says "States", any help would be much appreciated.
Thanks,
Andrew
try to use append() function of jquery
like if your html is like
<html>
<select id="temp"></select>
</html>
$("#temp").append("<option>Your Value</option>")

Categories

Resources