Jquery get selected option's value and custom attribute value - javascript

var x = document.getElementById("selectCity");
var options = ["Bangalore", "Pune", "Kolkata"];
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var element = document.createElement("option");
element.textContent = opt;
element.value = opt;
x.appendChild(element);
}
$('select[name="cityDropdown"]').change(function(){
cityName=$(this).val();
});
Now with each city i want to store my circle name. and save it as an attribute and pass when the city is selected

You can Hardcode a custom attribute to a select's option. For example,
<option circle="UP" value="Lucknow">Lucknow</option>
and get it's value with jquery like this,
var circle = $('option:selected', this).attr("circle");
HTML
<select name="cityDropdown">
<option circle="UP" value="Lucknow">Lucknow</option>
<option circle="Bihar" value="Patana">Patana</option>
<option circle="Punjab" value="Chandigarh">Chandigarh</option>
</select>
Javascript
$('select[name="cityDropdown"]').change(function(){
var cityName = $(this).val();
var circle = $('option:selected', this).attr("circle");
console.log(cityName + " : " + circle);
});
Note : You can also use other custom attribute (custom attribute city for example). But you just need to use city as value of the option.
Here is the fiddle.

make a proper selector ..try this ..
$('#selectCity').change(function(){
cityName = $(this).val();
console.log(cityName); // do something
});
HERE is the fiddle..

var x = document.getElementById("selectCity");
var options = ["Bangalore", "Pune", "Kolkata"];
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var element = document.createElement("option");
element.textContent = opt;
element.value = opt;
element.setAttribute('circle-name', 'your value'); // your attribute
x.appendChild(element);
}
$('select[name="cityDropdown"]').change(function(){
cityName=$(this).val();
});

var optionAttr = $('#cityDropdown option:selected').attr("circle");
var optionAttr1 = $(this).find('option:selected').attr("circle");

Related

Array displays words by each letter than than words. Javascript

I'm new to JS and I'm trying to populate a dropdown menu with items from an array but every time I loop through the array it displays letter after letter rather than the full string. Please let me know what am I doing wrong. Thank you
JS:
var ProjectNames = [];
ProjectNames = CProject;
var select = document.getElementById("ProjectList");
for (var i = 0; i < ProjectNames.length; i++) {
var el = document.createElement("option");
console.log(ProjectNames[i]);
var opt = ProjectNames[i];
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
HTML:
<select id="ProjectList" onchange="AddHoursForm()">
<option> --Choose Project-- </option>
</select>
Data in array is coming from Firebase. If I print console.log(ProjectNames) it gives the array objects but if I do console.log(ProjectNames[i]) it prints it letter by letter.
It seems to be working for me. Make sure you are working with an array.
var ProjectNames = [];
ProjectNames = ["hello", "world"];
console.log(ProjectNames) // <--- check this is this array?
var select = document.getElementById("ProjectList");
for (var i = 0; i < ProjectNames.length; i++) {
var el = document.createElement("option");
console.log(ProjectNames[i]);
var opt = ProjectNames[i];
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
<select id="ProjectList" onchange="AddHoursForm()">
<option> --Choose Project-- </option>
</select>
You killed the contents of ProjectNames setting it equal to CProject.
If you want to add itemns to ProjectNames use push or ProjectNames[ProjectNames.length]=... as below: The rest is ok.
var CProject="four";
var ProjectNames = ["one","two","three"];
ProjectNames[ProjectNames.length]=CProject;
ProjectNames.push("five");
var select = document.getElementById("ProjectList");
for (var i = 0; i < ProjectNames.length; i++) {
var el = document.createElement("option");
console.log(ProjectNames[i]);
var opt = ProjectNames[i];
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
It would be really easy for you if you use template strings or template literals for achieving this.
Just get data, create element, append it upon your ease.
// selecting div ith id = "main"
const main = document.querySelector("#main");
// you data from firebase or any other data source
let data = ["option1", "option2"];
// creating an element using tamplate string
const mySelectElement = `
<select>
<option value="" disabled selected>Choose a option</option>
${data.map(option => `<option value="${option}">${option}</option>`).join('')}
</select>
`;
//appeding element
main.innerHTML = mySelectElement;
<div id="main">
</div>

Concatenating text to options with a certain data attribute value

I have a select element:
function find() {
var schoolList = document.getElementByID("schoolList");
if (schoolList.hasAttributes("[data attribute value]") {
//modify text in found option
};
};
find();
<div id="SelectWrapper" class="menu">
<form>
<select id="schoolList">
<option value='student' data-tier="student" data->Student 1</option>
<option value="teacher" data-tier="faculty" data->Teacher</option>
</form>
</div>
Using pure Javascript, I want to create an if statement within a function that checks to see if an option has an appropriate data attribute value (for instance, "student" or "faculty") and then adds to or modifies the existing innerHTML/text.
You can use querySelectorAll() to find all the options with a particular data value, then loop over them.
function find() {
var options = document.querySelectorAll("#schoolList option[data-tier=student]");
for (var i = 0; i < options.length; i++) {
options[i].innerHTML += " (something)";
}
}
The example for you
function find() {
var schoolList = document.getElementById("schoolList");
if (schoolList.hasAttributes("[data attribute value]")) {
var opts = schoolList.getElementsByTagName("option");
for (var i = 0, len = opts.length; i < len; i++) {
var option = opts[i];
// modify
if (option["data-tier"] === "student") {
option.text = "new text content"
}
}
// add new
for (var i =0; i < 5; i++) {
var opt = document.createElement("option");
opt.value = i;
opt.innerHTML = "Option " + i;
schoolList.appendChild(opt);
}
};
};
find();

variable=getDocumentById("something").value losing half my data?

I am using javascript to autopopulate a select box on focus, then clear the innerHTML (except for the selected value) on blur (to keep the list from getting bigger and bigger).
Everything works as expected unless the value selected is two words... eg:"Bath Bombs". If I click the select box again, and select the same option (now at the top of the list) it drops the word "bombs" from the field???
(also, with the code as I have it, is there any way to keep the field from shrinking?)
Can someone please tell me where I have gone wrong?
(btw: I know very little javascript or html - I have been teaching this to myself over the last few days)
<script>
function prodType(id){
var targetId = id;
var select = document.getElementById(targetId);
var options = [ "", "Candles", "Tarts", "Bath Salts", "Bath Bombs", "Glycerin Soaps", "Salt Scrubs", "Sugar Scrubs", "Shower Gel", "Lotions"];
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
}
function clearAll(id) {
var targetId = id;
var select = document.getElementById(targetId);
var svalue = select.value;
select.innerHTML = "<option value="+svalue+">"+svalue+"</option>";
}
</script>
<select style="width:150" id="selectNumber" onfocus="prodType(this.id)" onblur="clearAll(this.id)">
<option value="" hidden>Product Type</option>
</select>
If you run this code... select a "two word" option, click off the select box, then select the same option again, this time from ~~THE TOP~~ of the list.
When you click off you will see what's happening.
Thanks!
The problem is that when you are updating the option value, you aren't including the quotes so it's essentially being set as value=bath bombs. The bombs gets ignored and you just end up with value=bath. Add some quotes (value='bath bombs') and it will work as expected.
function prodType(id){
var targetId = id;
var select = document.getElementById(targetId);
var options = [ "", "Candles", "Tarts", "Bath Salts", "Bath Bombs", "Glycerin Soaps", "Salt Scrubs", "Sugar Scrubs", "Shower Gel", "Lotions"];
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
}
function clearAll(id) {
var targetId = id;
var select = document.getElementById(targetId);
var svalue = select.value;
select.innerHTML = "<option value='"+svalue+"'>"+svalue+"</option>";
}
<select style="width:150" id="selectNumber" onfocus="prodType(this.id)" onblur="clearAll(this.id)">
<option value="" hidden>Product Type</option>
</select>
You can use such variant with single quotes:
select.innerHTML = "<option value='"+svalue+"'>"+svalue+"</option>";

Perfoming formulas/calculations based off of selections on a dropdown menu?

var stocks = [
['Apple',100,8998,723,7212],
['Microsoft',928,1992,821,2381]
];
var select = document.getElementById("selectStock");
for(var i = 0; i < stocks.length; i++) {
var opt = stocks[i][0];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
<select id="selectStock">
<option>Choose a stock</option>
</select>
I have multiple Javascript arrays of data (pulled from Excel) and have different functions that basically make calculations based on the row of the array. For example:
var stocks = [['Apple',100,8998,723,7212]['Microsoft,928,1992,821,2381]]
What I need to do is make a dropdown menu that will allow a user to select an option (Microsoft or Apple) and then based on this selection, will pull this value into the formula to make the calculations
document.write(Math.round(stocks[i][1] * 100)/100 + " dollars per share");
where i is the variable based off dropdown menu selection. Does this make sense? I'm not sure how to approach this, it's for a personal project. Thanks for the help!
https://jsfiddle.net/b22y3v85/
var select = document.getElementById("selectStock");
select.onchange = (e) => {
let index = stocks.indexOf(stocks.find(a => a.indexOf(e.target.value) > -1));
document.write(Math.round(stocks[index][1] * 100)/100 + " dollars per share");
};
Here is a working example, although you'll probably want to do something other than document.write the result.
var stocks = [
['Apple',100,8998,723,7212],
['Microsoft',928,1992,821,2381]
];
var select = document.getElementById("selectStock");
for(var i = 0; i < stocks.length; i++) {
var opt = stocks[i][0];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
function getPrice(stock) {
var price = false;
for (var a = 0; a < stocks.length; a++) {
if (stocks[a][0] == stock) {
price = stocks[a][1];
break;
}
}
if (!price) { alert("Incorrect choice."); return; }
document.getElementById("result").innerText = stock + " is currently " + (Math.round(price * 100)/100 + " dollars per share");
}
<select id="selectStock" onchange="getPrice(this.value);">
<option>Choose a stock</option>
</select>
<br><br>
<div id="result"></div>
EDIT: Shows result in a div on the page, instead of overwriting the page with document.write().
<select id="selectStock"></select>
<script type="text/javascript">
var stocks = [
['Apple',100,8998,723,7212],
['Microsoft',928,1992,821,2381]
];
var select = document.getElementById("selectStock");
for(var i = 0; i < stocks.length; i++) {
var opt = stocks[i][0];
var el = document.createElement("option");
el.innerHTML = opt;
el.value =stocks[i]+'';
select.appendChild(el);
}
select.addEventListener('change', function(e){
var val = e.currentTarget.value;
val = val.split(',');
val.shift();
callYourMethod(val);
});
</script>

How to display JSON objects as options of a dropdown in HTML, using a common JavaScript funciton for all objects

I have two sets of data in a JSON file (ACodes and BCodes), which I want to read and display as the options of two different dropdowns in an HTML file. I want to have one common JavaScript function that I can use to get along with the same (shown below) but I am not getting the desired output.
Help about where I am going wrong is much appreciated!
HTML
<script>
var select, option, arr, i;
function loadJSON(var x){
if(x.match == "A"){
array = JSON.parse(ACodes);
select = document.getElementById('dd1');
for (i = 0; i < array.length; i++) {
option = document.createElement('option');
option.text = array[i]["Code"];
select.add(option);
}
}
else if(x.match == "B"){
array = JSON.parse(BCodes);
select = document.getElementById('dd2');
for (i = 0; i < array.length; i++) {
option = document.createElement('option');
option.text = array[i]["Curr"];
select.add(option);
}
}
}
</script>
<body onload="loadJSON('A');laodJSON('B')">
<select id="dd1"></select>
<select id="dd2"></select>
</body>
JSON
ACodes = '[{"Code":"BHAT"}, {"Code":"MALY"}]';
BCodes = '[{"Curr":"CAC"},{"Curr":"CAD"}]';
remove var at loadJSON(var x) => loadJSON(x)
remove .match at x.match == "A", you seems to want to compare x with specific value, not testing it as regexp, so change to x === "A"
laodJSON('B'); at body onload is typo.
There's some reusable codes, you can attract the value depends on x and make the code shorter. This step is not a must do, as it won't cause your origin code unable to work.
<body onload=" loadJSON('A');loadJSON('B');">
<select id="dd1"></select>
<select id="dd2"></select>
<script>
var select, option, arr, i;
var ACodes = '[{"Code":"BHAT"}, {"Code":"MALY"}]';
var BCodes = '[{"Curr":"CAC"},{"Curr":"CAD"}]';
function loadJSON(x){
var array, select, target;
if (x === 'A') {
array = JSON.parse(ACodes);
select = document.getElementById('dd1');
target = 'Code';
} else if (x === 'B') {
array = JSON.parse(BCodes);
select = document.getElementById('dd2');
target = 'Curr';
}
for (i = 0; i < array.length; i++) {
option = document.createElement('option');
option.text = array[i][target];
select.add(option);
}
}
</script>
</body>
Edit: to create it more dynamically, you can make the function accept more params, so you can have more control over it. Demo is on jsfiddle.
// Append options to exist select
function loadJSON(jsonObj, key, selectId) {
var arr = JSON.parse(jsonObj);
// Get by Id
var select = document.querySelector('select#' + selectId);
// Loop through array
arr.forEach(function(item) {
var option = document.createElement('option');
option.text = item[key];
select.add(option);
});
}
// Append select with id to target.
function loadJSON2(jsonObj, key, selectId, appendTarget) {
// Get the target to append
appendTarget = appendTarget ? document.querySelector(appendTarget) : document.body;
var arr = JSON.parse(jsonObj);
// Create select and set id.
var select = document.createElement('select');
if (selectId != null) {
select.id = selectId;
}
// Loop through array
arr.forEach(function(item) {
var option = document.createElement('option');
option.text = item[key];
select.add(option);
});
appendTarget.appendChild(select);
}
<script>
var select, option, arr, i;
var ACodes = '[{"Code":"BHAT"}, {"Code":"MALY"}]';
var BCodes = '[{"Curr":"CAC"},{"Curr":"CAD"}]';
function loadJSON(x){
if(x == "A"){
array = JSON.parse(ACodes);
select = document.getElementById('dd1');
for (i = 0; i < array.length; i++) {
option = document.createElement('option');
option.text = array[i]["Code"];
select.add(option);
}
}
else if(x == "B"){
array = JSON.parse(BCodes);
select = document.getElementById('dd2');
for (i = 0; i < array.length; i++) {
option = document.createElement('option');
option.text = array[i]["Curr"];
select.add(option);
}
}
}
</script>
<body onload='loadJSON("A");loadJSON("B")'>
<select id="dd1"></select>
<select id="dd2"></select>
</body>
Now this code will work.
The match() method searches a string for a match against a regular expression. So match() function will not work here. You have to use equal operator for get this done.
I hope, This will help you.
You were well on your way, you just need to make it more dynamic :)
function loadOptions(json) {
json = JSON.parse(json);
var select = document.createElement('select'), option;
for (var i = 0; i < json.length; i++) {
for (var u in json[i]) {
if (json[i].hasOwnProperty(u)) {
option = document.createElement('option');
option.text = json[i][u];
select.add(option);
break;
}
}
}
return select;
}
And to use it:
document.body.appendChild(loadOptions(ACodes));
document.body.appendChild(loadOptions(BCodes));
FIDDLE
http://jsfiddle.net/owgt1v2w/
The answers above will help you, but im strongly recommend you to check some javascript's frameworks that can help you with that kind of situation.. The one im using is knockout.js (http://knockoutjs.com/)
Take a look in the documentation, also there a lot of topics related in stackoverflow http://knockoutjs.com/documentation/options-binding.html
Regards!

Categories