Hi I am trying to populate country and state dropdown list in dropdowns using jquery.
My json looks like this
Blockquote
var myjson = [{"countryName":"Afghanistan","countryCode":"AF"},{"countryName":"United States","countryCode":"US" ,"state":["Alabama","Alaska","Arizona","Arkansas","California","Colorado","Connecticut","Delaware","Florida","Georgia","Hawaii","Idaho","Illinois","Indiana","Iowa","Kansas","Kentucky","Louisiana","Maine","Maryland","Massachusetts","Michigan","Minnesota","Mississippi","Missouri","Montana","Nebraska","Nevada","New Hampshire","New Jersey","New Mexico","New York","North Carolina","North Dakota","Ohio","Oklahoma","Oregon","Pennsylvania","Rhode Island","South Carolina","South Dakota","Tennessee","Texas","Utah","Vermont","Virginia","Washington","West Virginia","Wisconsin","Wyoming"]},
{"countryName":"United States Minor Outlying Islands","countryCode":"UM"},
{"countryName":"Uruguay","countryCode":"UY","state":["abc","edf"]}];
My html
<body>
<select id = "country" name = "country" onchange= "getvalue()"></select>
<select id = "state" name = "state" onchage="getstate()"></select>
</body>
My javascript
<script>
function getvalue(){
var country = document.getElementById("country").value;
var divtemp = document.getElementById("test");
for (var i = 0; i < myjson.length; i++ ) {
if(myjson[i].state != null )
{
if(myjson[i].state.length==0){
$("#state").empty();
}
else
{
for(var j = 0 ; j< myjson[i].state.length;j++)
{
if(country === myjson[i].countryName)
{
//alert(country);
//alert(myjson[i].countryName);
//divtemp.innerHTML= myjson[i].state[j] + "<br>"+divtemp.innerHTML;
$("#state").append(
$("<option></option>")
.text(myjson[i].state[j])
);
}
}
}
}
}
</script>
This script function is populating states but when I select a another country the sates are appending to the earlier states list. I am not able to make out the changes required for my condition. I dont want to use Ajax to do this.
Try this.
In the head do this...
<script>
$(document).ready(
//when the document is loaded, initialize my selectors
function initCountries(){
//put all countries into the country selector
for (cix in myjson){
var options='<option value="'+cix+'">'+myjson[cix].countryName+'</option>';
$("#country").append(options);
}
//listen for the change event when the user chooses a country
$("#country").change(function fillStates(){
//find the country the user chose, then fill the states selector
var cix=$(this).val();
var states=myjson[cix].state;
$("#state").empty();
for (six in states){
var options='<option value="'+states[six]+'">'+states[six]+'</option>';
$("#state").append(options);
}
});
//listen for the change event when the user chooses a state
$("#state").change(function stateSelected(){
//show the state the user chose
var six=$(this).val();
alert(six);
});
});
</script>
and in your body change the selectors like this...
<select id = "country"></select>
<select id = "state"></select>
Clear state combobox on change of country..
document.getElementById('state').innerHTML = "";
Related
I am trying to have a dependent Dropdown list, Districts based on the value of selected State. But my code is rendering only the first element of the dynamic dropdown list.
<div class="input-field col s3">
<select id="nativeDistr">
<option value="" disabled selected>
Native District
</option>
</select>
<label>Destination District</label>
;
Appscript Code Snippet.
function getDistricts(state) {
Logger.log("Selected State=" + state);
var fileName = "states-and-districts.json";
var files = DriveApp.getFilesByName(fileName);
try {
if (files.hasNext()) {
var file = files.next();
var content = file.getBlob().getDataAsString();
var json = JSON.parse(content).states_districts;
for (var i = 0; i < json.length; i++) {
if (json[i]["state"] === state) {
var districts = json[i]["districts"];
}
}
}
var optList = generateOptions(districts);
Logger.log(optList);
return optList;
} catch (err) {
return "Error getting data";
}
}
Javascript code
<script>
document.getElementById("nativeState").addEventListener("change", getDistr);
function getDistr() {
var state = document.getElementById("nativeState").value;
console.log("state scriptt:" + state);
google.script.run.withSuccessHandler(updatedistricts).getDistricts(state);
}
function updatedistricts(districts) {
console.log("From districts:" + districts);
var nativeDistr = document.getElementById("nativeDistr");
nativeDistr.innerHTML = districts;
M.updateTextFields();
} // When user selects the state the valuee off the state should get registered for district search
Blockquote
Durin execution I am getting the complete list of dynamic dropdown but while rendering the page only the first element is getting displayed.
Blockquote
M.updateTextFields() do not update dynamic dropdown, it updates the text fields. So there is a need to store a global reference to materialize select box to initialize it, post that there is a need to destroy that instance, and then reinitialize the select box again.
<script>
document.addEventListener("DOMContentLoaded", function () {
var elems = document.querySelectorAll("select");
var instances = M.FormSelect.init(elems);
});
document.getElementById("nativeState").addEventListener("change", getDistr);
function getDistr() {
var state = document.getElementById("nativeState").value;
google.script.run.withSuccessHandler(updatedistricts).getDistricts(state);
}
function updatedistricts(distrList){
nativeDistr.innerHTML = distrList;
var subcatSelectElem = document.querySelectorAll("select");
var subcatSelectInstance = M.FormSelect.init(subcatSelectElem, {});
}
Credit for soln.: Chicago Computer Classes
Need to send dynamic (not hardcode) data to a select element.
This code works great in one of my sheets but doesn't work in the other sheet.
The "select" element doesn't get updated with the options I send..
I don't get an error message either.
I've spent a lot of time twitching it and trying to find why but still don't see what's wrong.
p.s. I used a dummy object to send the data for testing purpose.
The html (used MaterializeCss framework)
<select class="icons browser-default" id="selName" onChange ="getNameText();">
<option value="" disabled selected>Choose week</option>
<div id = "err"></div>
//select element initialization in framework
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('select');
var options = handlers()
var instances = M.FormSelect.init(elems);
});
function handlers() {
var success = google.script.run.withSuccessHandler(addOptions).getNamesForDropdown()
var failure = google.script.run.withFailureHandler(showError).getNamesForDropdown()
return;
}
function addOptions(names) {
var selectTag = document.getElementById("selName") //select tag
for (var k in names) {
var thisID = k;
var thisText = names[k];
var option = document.createElement("option"); //creating option
option.text = thisText
option.value = thisID;
selectTag.add(option);
}
}
function showError() {
var err = document.getElementById("err").innerHTML = "There was an error."
}
//get the text of selected option
function getNameText() {
var sel = document.getElementById("selName")
var nameText = sel.options[sel.selectedIndex].text;
return nameText;
}
Dummy object I send:
function getNamesForDropdown() {
var namesObj = {
one: "blah",
two: "blahblah"
}
return namesObj;
}
Here's the result what I get (on the screen you there's only hardcoded option):
I handled it. I added a class "browser-default" to the select and the options got updated. This class comes from MaterializeCss Framework.
I am using an onchange function for my select tag to filter a list of items based on the select option value.
The code I have currently have only works for a single select tag but I want it to be able to work for multiple select tags, which would require each select option value to cooperate.
For example, if I have "Departments" and "Locations" as tags for each item in the list and I choose Department -> IT and Location -> New York in the select tags, I only want to see a list of IT departments in New York.
I am having a hard time understanding how I would do this properly. I would assume some sort of for loop to get each select tag and then get the value of the current option in each select tag and only show the list items if they meet the select option value criteria.
I would appreciate any help of how I could achieve this!
HTML:
<select class="filterTags" id="filterDepartment">
<option>All</option>
<option>IT</option>
<option>Marketing</option>
</select>
<select class="filterTags" id="filterLocation">
<option>All</option>
<option>New York</option>
<option>Washington</option>
</select>
<div class="tags-container">
<div class="tags tags-departments">
<span class="department tag">IT</span>
<span class="department tag">Marketing</span>
</div>
<div class="tags tags-locations">
<span class="location tag">New York</span>
<span class="location tag">Washington</span>
</div>
</div>
JavaScript:
var selectClass = document.getElementsByClassName("filterTags")
selectClass = selectClass[0]
selectClass.onchange= function() {
var filterOptions, tags, i, span;
filterOptions = this.options[this.selectedIndex].value
tags = document.getElementsByClassName("tags-departments")
span = document.querySelectorAll(".department")
for (i = 0; i < tags.length; i++) {
if (span) {
if (span[i].innerHTML.indexOf(filterOptions) > -1) {
span[i].parentNode.parentNode.parentNode.style.display = ""
} else {
span[i].parentNode.parentNode.parentNode.style.display = "none"
}
if(filterOptions == "All") {
span[i].parentNode.parentNode.parentNode.style.display = ""
}
}
}
}
Well, I would suggest the following logic, add a function to the onchange event of both selection elements, the function would:
Detect the ID of the selection element that triggered the event.
Based on the selection element that triggered the change, loop over the corresponding span elements.
For each span, based on the selected value in the selection, check if it should be displayed or not.
Here is a fully working code and a working example with it:
//Iterate the selection elements and add the function to the 'change' event
sels = document.getElementsByTagName('select');
for(i=0; i<sels.length; i++)
{
sels[i].addEventListener('change', function() {
//get the selection id of the selected that was change - this returns the selection element
selectionID = this.id;
if(selectionID === "filterDepartment")
{
//the value of the selected department
var selectedDepartment = document.getElementById("filterDepartment").value
//we will iterate the departments spans and check their text value agains the selected department value (or if the value is 'All' we dont need to check//
var spans = document.getElementsByClassName('tags tags-departments')[0].getElementsByTagName('span');
for(var i = 0; i < spans.length; i++)
{
if(selectedDepartment == "All" || spans[i].innerText == selectedDepartment)
{
spans[i].style.display = "block";
}
else
{
spans[i].style.display = "none";
}
}
}
if(selectionID === "filterLocation")
{
var selectedLocation = document.getElementById("filterLocation").value;
var spans = document.getElementsByClassName('tags tags-locations')[0].getElementsByTagName('span');
for(var i = 0; i < spans.length; i++)
{
if(selectedLocation == "All" || spans[i].innerText == selectedLocation)
{
spans[i].style.display = "block";
}
else
{
spans[i].style.display = "none";
}
}
}
}, false);}
I am trying to create an online form using Netsuite.
We have a set for predefined fields like firstname, lastname, etc.
In the same we have a
NLSUBSCRIPTIONS
tag but the field type by default is drop down with multiple select option.
How can I change this drop down to a checkbox?
If you use a custom template you can hide the drop-down and iterate its options to create your own checkboxes.
e.g.
<div class="regFieldWrap">
<span class='cbExpand hideNsLabel'><NLCUSTENTITY_LIST_FIELD></span><input class="otherShadow valid" type="text" name="custentity_list_field_other"><span class="multiProto cbHolder"><input type="radio" name="custentity_list_field"><label class="cbLabel"></label></span>
</div>
and then
<script>
jQuery(function($){
// convert multi select to checkbox
$("span.multiProto").each(function(){
var proto = this;
var selName = $(proto).find("input").attr("name");
var otherCB = null;
$("select[name='"+selName+"']").css({display:'none'}).each(function(){
var sel = $(this);
var isReq = sel.hasClass('inputreq');
if(isReq) sel.removeClass('inputreq');
sel.find("option").each(function(){
if(!this.value) return;
var newby = $(proto.cloneNode(true));
var cb = newby.find("input").val(this.value);
if(isReq) cb.addClass('cb_selectone');
newby.find("label.cbLabel").text(this.text);
$(newby).removeClass('multiProto');
if((/\bother\b/i).test(this.text)){
var otherField = $("input.otherShadow[name='"+ selName+"_other']").each(function(){
var newOther = this.cloneNode(true); // strange but it gets around an IE issue
$(this).remove();
$(newby).find("input").data("conditionalOther", newOther);
newby.get(0).appendChild(newOther);
});
otherCB = newby;
} else proto.parentNode.insertBefore(newby.get(0), proto);
});
sel.get(0).options.length = 0;
});
if(otherCB) proto.parentNode.insertBefore(otherCB.get(0), proto); // make sure this is the end element
});
});
I am trying to get the custom attribute values from the select box. It is triggered by a checkbox click which I already have working. I can get the name and value pairs just fine. I want get the custom attributes (therapy) (strength) (weight) and (obstacle) from the option value lines. is this possible?
select box
<option value="2220" therapy="1" strength="1" weight="0" obstacle="0">Supine Calf/Hamstring Stretch</option>
<option value="1415" therapy="0" strength="0" weight="0" obstacle="0">Sitting Chair Twist</option>
<option value="1412" therapy="0" strength="0" weight="0" obstacle="0">Static Abductor Presses</option>
jQuery
// exercise list filter category
jQuery.fn.filterByCategory = function(checkbox) {
return this.each(function() {
var select = this;
var optioner = [];
$(checkbox).bind('click', function() {
var optioner = $(select).empty().scrollTop(0).data('options');
var index=0;
$.each(optioner, function(i) {
var option = optioner[i];
var option_text = option.text;
var option_value = parseInt(option.value);
$(select).append(
$('<option>').text(option.text).val(option.value)
);
index++;
});
});
});
};
You need to find the selected , like this:
var $select = $('#mySelectBox');
var option = $('option:selected', $select).attr('mytag');
That is how to get selected option attribute:
$('select').find(':selected').attr('weight')
Get selected option and use attr function to get the attribute:
$("select").find(":selected").attr("therapy")
JSFIDDLE