I've created a JSON file to call out the name of a list of beers to display ABV and country but I am unable to display the results on the webpage. I was able to get the select tag to drop down the list, but when selecting a beer, it will only show the selected results as "undefined."
Here is the JS code I have so far...
var $select = $("#beerListing");
var beer = Array();
var country = Array();
$.getJSON("data.json", function(data) {
$select.html('');
for (var i = 0; i < data['beer'].length; i++)
$select.append('<option id="' + data["beer"][i]['id'] + '">' + data["beer"][i]["beer_name"] + '</option>');
for (x in data) {
if (beer.indexOf(data[x].beer_name) < 0) {
var y = beer.length;
beer[y] = data[x].beer_name;
country[y] = data[x].brewery_country;
}
}
showBeerList();
});
function showBeerList() {
var select = document.getElementById('beerListing');
for (var i = 0; i < beer.length; i++) {
var obj = document.createElement("option");
obj.text = beer[i];
obj.value = i;
select.appendChild(obj);
}
}
function getBeerInfo(picked) {
if (picked == "Pick Your Poison...") {
location.reload();
} else {
document.getElementById("name").innerHTML = beer[picked];
document.getElementById("country").innerHTML = country[picked];
}
}
HTML:
<html>
<head></head>
<body>
<h1>LCBO API TESTING</h1>
<select name="beerlist" id="beerListing" class="form-control" onchange="getBeerInfo(this.value)">
</select>
<br>
<label>Name:</label>
<label id="name">--</label>
<br>
<label>Country:</label>
<label id="country">--</label>
<br>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="main.js"></script>
</body>
</html>
JSON List called data.json
{
"beer": [{
"beer_name": "Organic Devon Cider",
"brewery_name": "Luscombe Organic Drinks",
"beer_type": "Cider",
"beer_abv": "4.9",
"beer_ibu": "0",
"comment": "",
"venue_name": "The Anchor & Hope",
"venue_city": "London",
"venue_state": "Greater London",
"brewery_country": "England"
}, {
"beer_name": "Beer A",
"brewery_name": "Beer A",
"beer_type": "Cider",
"beer_abv": "4.9",
"beer_ibu": "0",
"comment": "",
"venue_name": "Beer",
"venue_city": "New York",
"venue_state": "New York",
"brewery_country": "USA"
}]
}
You seemed to be adding the options to the select element twice and using for-in which iterates properties, not entries in an array.
Below snippet will not work as requires external data source.
var $select = $("#beerListing") ;
var beer = Array();
var country = Array();
$.getJSON("data.json", function(data) {
$select.html('');
for (var i = 0; i < data.beer.length; i = i + 1) {
if (beer.indexOf(data.beer[i].beer_name) < 0) {
beer.push(data.beer[i].beer_name);
country.push(data.beer[i].brewery_country);
}
}
showBeerList();
}
function showBeerList() {
var select = document.getElementById('beerListing');
for (var i = 0; i < beer.length; i++) {
var obj = document.createElement("option");
obj.text = beer[i];
obj.value = i;
select.appendChild(obj);
}
}
function getBeerInfo(picked) {
if (picked == "Pick Your Poison...") {
location.reload();
}
else {
document.getElementById("name").innerHTML = beer[picked];
document.getElementById("country").innerHTML = country[picked];
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>LCBO API TESTING</h1>
<select name="beerlist" id="beerListing" class="form-control" onchange="getBeerInfo(this.value)">
</select>
<br>
<label>Name:</label>
<label id="name">--</label>
<br>
<label>Country:</label>
<label id="country">--</label>
<br>
I got it working here: https://jsfiddle.net/bu7pkb5f/1/
What are you doing with:
if (beer.indexOf(data[x].beer_name) < 0) {
var y = beer.length;
beer[y] = data[x].beer_name;
country[y] = data[x].brewery_country;
}
I don't understand it but it's creating a third item in the list after the two real beer entries are processed. I left it commented out in the fiddle so you can check it out for yourself.
Related
My goal for this experiment is to have 2 blocks of trials, both which flash 10 words and then the participants have to click yes or no if they saw the word or not (answer yes or no to 20 words). After the 2 blocks I would like the data to be displayed and the experiment to end, although right now the experiment is infinite and displays data after every block. I also need to know how to save the data with a "Save Data" button after presenting both of the blocks data at the end. Any and all help appreciated!
If anyone has any ideas about how to create two blocks, as I have tried to initiate by declaring blocks = 0 at the beginning it would be greatly appreciated!
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script src="342.js" type="text/javascript"></script>
<script type="text/javascript">
let index = 0, blocks=0;
let words = ["fox", "tree", "wheel", "pillow", "target", "wool", "bread", "sport", "dog", "straw", "state",
"mountain", "cot" , "green" , "napkin" , "grape" , "glass" , "drum" , "grass",];
let stimuli = [];
let N = words.length/2;
let t;
window.onload = initialize;
function initialize() {
for (let i = 0; i < words.length; i++) {
stimuli.push(new Stimulus(words[i]));
}
shuffle(stimuli);
for (let i = 0; i < words.length; i++) {
if (i < N) {
stimuli[i].presented = "1";
stimuli[i].presOrder = i;
}
else {
stimuli[i].presented = "0";
stimuli[i].presOrder = "-1"
}
}
}
function Stimulus(word) {
this.word = word;
}
Stimulus.prototype.toString = function () {
return "\t Order Presented: " + this.presOrder + "\t Order tested: " + this.testOrder + "\t Word Presented:" + this.word + "\t Response (0 or 1):"
+ this.resp + " \t Presented (0 or 1):" + this.presented;
};
function begin() {
document.getElementById("b").style.visibility = "hidden";
document.getElementById("word").innerHTML = "";
t = setInterval(nextWord, 250)
}
function nextWordTest() {
document.getElementById("word").innerHTML = stimuli[index].word;
stimuli[index].testOrder = index;
if (blocks=1)
{
document.getElementById("b2").style.visibility = "visible";
}
}
function nextWord()
{
if (index < N)
{
document.getElementById("word").innerHTML = stimuli[index].word;
stimuli[index].presOrder = index;
index++;
}
else
{
clearInterval(t);
document.getElementById("word").innerHTML = "Click yes if you saw the word and " +
"no if you did not see the word";
document.getElementById("yes").style.visibility = "visible";
document.getElementById("no").style.visibility = "visible";
document.getElementById("b2").style.visibility = "hidden";
index = 0;
N = words.length;
stimuli = shuffle(stimuli);
nextWordTest();
}
}
function record(resp) {
stimuli[index].resp = resp;
index++;
if (index < N) {
nextWordTest();
}
else {
if (blocks===0){
nextWordTest()
}
if (blocks===1)
{
document.getElementById("word").innerHTML = "finished";
data = "";
for (let i = 0; i < stimuli.length; i++)
{
data += stimuli[i] + "\n";
}
console.log(data);
document.getElementById("word").innerText = data;
}
}
}
</script>
</head>
<body>
<h1> Attentional Blink Experiment </h1>
<p id="word">Push button to begin.</p>
<button type="button" id="yes" onclick="record(1)" style="visibility: hidden">yes</button>
<button type="button" id="no" onclick="record(0)" style="visibility: hidden">no</button>
<button type="button" id="b" onclick="begin()">Begin</button>
<button type="button" id="b2" onclick="begin()" style="visibility: hidden">Continue</button>
</body>
</html>
I'm practicing javascript and learning on my own. I am creating a game where you enter a text coordinates and the game tells you whether you dug something up or not. But I am trying to implement a text box so you can play out of a browser instead of the command prompt, but I'm having trouble getting the game to take the text and then run the code using it when you click on the button.
Here is the HTML for the game.
<head>
<meta charset="UTF-8">
<title>Game Board</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript" src="board.js"></script>
<script type="text/javascript" src="game.js"></script>
</head>
<body>
<center>
<h1>Archaeology Board</h1>
Palace = 5 Spaces </br>
Temple = 4 Spaces </br>
Forum = 4 Spaces </br>
House = 3 Spaces </br>
Hut = 2 Spaces </br>
<h3>
<table id="board">
</table>
</h3>
<p>
<label for="DigBox">Enter dig coordinates:</label>
<input type="text" id="DigBox" size="3" value="" />
<input type="button" value="Dig" id="run" />
</p>
<p><input type="button" value="Restart Game" id="restart" /></p>
</center>
</body>
</html>
This is the js file to create the board.
function GameBoard()
{
this.ruins = [
{
name: "Palace",
size: 5,
successes: 0
},
{
name: "Temple",
size: 4,
successes: 0
},
{
name: "Forum",
size: 4,
successes: 0
},
{
name: "House",
size: 3,
successes: 0
},
{
name: "Hut",
size: 2,
successes: 0
}
];
this.rows = ["a", "b", "c", "d", "e", "f", "g", "h"];
this.columns = ["1", "2", "3", "4", "5", "6", "7", "8"];
this.cellMarker = 'X';
}
GameBoard.prototype.setBoard = function ()
{
var i, j, boardTags;
boardTags = "";
// build the first row of column labels
boardTags += "<tr><th> </th>";
for (j = 0; j < this.columns.length; j++) {
boardTags += "<th>" + this.columns[j] + "</th>";
}
boardTags += "</tr>";
// build the table with HTML tags
for (i = 0; i < this.rows.length; i++) {
boardTags += "<tr>";
boardTags += "<th>" + this.rows[i] + "</th>"; // row labels
for (j = 0; j < this.columns.length; j++) {
boardTags += "<td class='square' id='cell" +
this.rows[i] + this.columns[j] + "'>" + this.cellMarker + "</ td>";
}
boardTags += "</tr>";
}
$("#board").html(boardTags);
for (i = 0; i < this.ruins.length; i++) {
this.setRuin(this.ruins[i]);
}
}
GameBoard.prototype.dig = function(square, processResult)
{
var target, targetObj;
target = $("#cell"+square).attr('ruin');
if (target) {
targetObj = this.getRuin(target);
if (! $("#cell"+square).attr('dug')) {
$("#cell"+square).attr('dug', 'yes');
targetObj.successes++;
}
return targetObj;
}
else {
return undefined;
}
}
GameBoard.prototype.getRuin = function(ruinName)
{
for (var i = 0; i < this.ruins.length; i++) {
if (ruinName === this.ruins[i].name) {
return this.ruins[i];
}
}
return undefined;
}
GameBoard.prototype.randomSquare = function()
{
var colIndex = Math.floor(Math.random() * this.columns.length);
var rowIndex = Math.floor(Math.random() * this.rows.length);
return this.rows[rowIndex] + this.columns[colIndex];
}
GameBoard.prototype.setRuin = function(ruin)
{
// keeps randomly trying to place a ruin until it fits on the board
var candidateSquare = this.randomSquare();
var across = Math.random() < 0.5;
var success = this.tryPlacement(ruin, candidateSquare, across, ruin.size);
while (! success) {
candidateSquare = this.randomSquare();
across = Math.random() < 0.5;
success = this.tryPlacement(ruin, candidateSquare, across, ruin.size);
}
}
GameBoard.prototype.tryPlacement = function(ruin, square, across, size) {
var nextSquare;
if (size === 0) {
// ruin fits!
return true;
}
else if (! square) {
// invalid square
return false;
}
if (! $("#cell" + square).attr('ruin')) {
$("#cell" + square).attr('ruin', ruin.name);
// see if the rest of the ruin fits
if (this.tryPlacement(ruin, this.increment(square, across), across, size - 1)) {
// ruin fits!
return true;
}
else {
// ruin didn't fit --- undo occupied square and return false
$("#cell" + square).removeAttr('ruin');
return false
}
}
}
GameBoard.prototype.increment = function(square, across)
{
if (across) {
// need to increment the column dimension if possible
var colIndex = this.columns.indexOf(square.charAt(1));
colIndex++;
if (colIndex === this.columns.length) {
return undefined;
}
else {
return square.charAt(0) + this.columns[colIndex];
}
}
else {
// need to increment the row dimension if possible
var rowIndex = this.rows.indexOf(square.charAt(0));
rowIndex++;
if (rowIndex === this.rows.length) {
return undefined;
}
else {
return this.rows[rowIndex] + square.charAt(1);
}
}
}
This is the code I'm trying to implement in
$(function () {
tryDig = function(targetCell)
{
var targetObj = board.dig(targetCell);
if (targetObj) {
alert('Success finding the ' + targetObj.name);
$("#cell"+targetCell).html('#');
$("#cell"+targetCell).css('color', 'blue');
}
else {
alert('Failure!');
$("#cell"+targetCell).html('*').css('color', 'red');
}
}
board = new GameBoard();
board.setBoard();
});
initialize = function() {
$("#run").click(tryDig);
}
initialize = function() {
$("#restart").click(GameBoard.prototype.setBoard);
}
$(initialize);
I want to make it so whatever is in the text box, the game uses that as the coordinates to dig up in the board.
I want to make a live search and then select those suggestions for further implementation!But it doesn't put values in the select field.In other words,option tag is not working!!!
here is the code!!!
//index.php
<html lang="en"><head>
<meta charset="utf-8">
<title>Live Search</title>
</head>
<body>
<div id="searcharea">
<label for="search">live search</label>
<p>Enter the name</p>
<input type="search" name="search" id="search" placeholder="name or info">
</div>
<div>
<div id="top"></div>
<div id="center"></div>
<div id="bottom"></div>
</div>
<script src="jquery-1.12.2.min.js"></script>
<script src="basic.js"></script>
</body>
</html>
//location.json
[
{
"name":"Barot Bellingham",
},
{
"name":"Jonathan G. Ferrar II",
},
{
"name":"Hillary Hewitt Goldwynn-Post",
},
{
"name":"Hassum Harrod",
},
{
"name":"Jennifer Jerome",
},
{
"name":"LaVonne L. LaRue",
},
{
"name":"Constance Olivia Smith",
},
{
"name":"Riley Rudolph Rewington",
},
{
"name":"Xhou Ta",
}
]
//basic.js
$('#search').keyup(function()
{
var searchField=$('#search').val();
var myExp=new RegExp(searchField,"i");
var slct_start='<select>';
$('#top').html(slct_start);
$.getJSON('location.json',function(data)
{
var output='<ul class="searchresults">';
$.each(data,function(key,val){
if(val.name.search(myExp)!=-1)
{
output='<option '+'value='+val.name+'>'+val.name+'</option>';
}
});
$('#center').html(output);
});//get json
var slct_end='</select>';
$('#bottom').html(slct_end);
});
Instead of this KeyUp function,
You can use the Jquery AutoComplete functionality for easy search.
Try that one.
Refer this AutoComplete search in Jquery
I found that your location.json's data is not standard, it should like this:
[
{
"name":"Barot Bellingham"
},
{
"name":"Jonathan G. Ferrar II"
},
{
"name":"Hillary Hewitt Goldwynn-Post"
},
{
"name":"Hassum Harrod"
},
{
"name":"Jennifer Jerome"
},
{
"name":"LaVonne L. LaRue"
},
{
"name":"Constance Olivia Smith"
},
{
"name":"Riley Rudolph Rewington"
},
{
"name":"Xhou Ta"
}
]
first we put a html file as index.html
<div class="container">
<h4 class="publish-work" >PUBLISHED WORKS AVAILABLE</h4>
<br>
<input type="search" class="search" name="search" >
<br>
<br>
<table id="datalist" class="table table-bordered" style="height: 400px; overflow-y: auto;">
<thead>
<th>S.no</th>
<th>Name</th>
<th>Price</th>
</thead>
<tbody>
</tbody>
</table>
then add a script.js file
$(document).ready(function()
{
var table_object = [];
for(var i=0; i<1500; i++)
{
var object1 = [''];
object1[0] = randomString() ;
object1[1] = i+1;
object1[2] = i*10/2;
table_object.push( object1 );
}
console.log( table_object );
function render ( arraylist ) {
var html = '';
for(var i=0;i<arraylist.length;i++)
{
//var html = '';
html += '<tr>';
html += '<td>'+arraylist[i][0]+'</td>';
html += '<td>'+arraylist[i][1]+'</td>';
html += '<td>'+arraylist[i][2]+'</td>';
html += '</tr>';
//html1 += html;
//console.log(html);
}
console.log(html);
$("#datalist tbody").html(html);
}
render( table_object );
$(".search").on("keyup", function() {
var value = $(this).val();
var anotherval = [''];
var dummyarray = [];
for ( i=0; i<table_object.length; i++ )
{
if ( table_object[i]["name"].indexOf(value) != -1 )
{
dummyarray.push(table_object[i]);
}
}
render(dummyarray);
});
function randomString ()
{
var randomStringArray = [];
var stringSet = "abcdefghijklmnopqrstuvwxyz";
for (var i = 0; i < 100; i++) {
var maxLength = Math.floor(Math.random() * (10 - 5 + 1)) + 5;
var String = "";
for (var j = 0; j < maxLength; j++) {
String += stringSet[Math.floor(Math.random() * stringSet.length)];
}
randomStringArray.push(String);
}
return String;
}
});
thats it..
I make a drop down on pop up screen. I am able to make that drop down using jQuery mobile. I used dform plugin. Everything is working fine. But I have one issue my first character display in capital letter when I added bootstrap.min.css - why?
When I run my program without bootstrap.min.css, it works fine. But when I run with bootstrap.css, it give first letter capital after . . As I written in small. This problem is only in chrome browser. When I run in firefox it works perfectly.
Can you please explain why it is occurring?
Here is my code.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<link href=" https://dl.dropboxusercontent.com/s/bbvcx2zc4ocuqzt/bootstrap.min.css?m=" rel="stylesheet" type="text/css" />
<link href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css" rel="stylesheet" type="text/css" />
<link href=" https://dl.dropboxusercontent.com/s/hg36tk1m7rc4gnj/style.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
<script src="https://rawgit.com/daffl/jquery.dform/master/dist/jquery.dform-1.1.0.js"></script>
</head>
<body>
<button id="test">test</button>
<div data-role="popup" data-dismissible='false' data-transition="flip" id="tabbedPopup" data-theme="a"><a href="#"
data-rel="back"
data-role="button"
data-theme="a"
data-icon="delete"
data-iconpos="notext"
class="ui-btn-right cross-border cross-border closePopUp_h button circleClass" >Close</a>
<div id="commandInfo"></div>
<div id="commandInfoheader" class="comandinfoheader"></div>
<div data-role="collapsible-set" data-theme="b" data-content-theme="b" id="tabbedSet" data-iconpos="left">
</div>
</div>
</body>
<script type="text/javascript">
$(function () {
$('#test').click(function(){
createCommandPopUpTabs("tc_2-cmd_1_VoiceCallAudioMosMO");
$("#tabbedPopup").popup("open");
})
});
function createCommandPopUpTabs(id) {
var tabsHeader = ["InputParameter"];
var header = "<h3 >hh</h3>";
var commmand = "VoiceCallAudioMosMO";
var button = '<button onclick="return submitCommand("' + id
+ '")" style="" class="donebtn common-button1">Save</button>';
//$("#commandInfo").append(header);
$("#commandInfo").append(button);
$("#commandInfoheader").html(header);
for ( var i = 0; i < tabsHeader.length; i++) {
var headerId = tabsHeader[i] + "_tab" + commmand;
var header = "<div data-role='collapsible' data-collapsed='false' id='"
+ headerId + "'><h3>hhh</h3></div>";
var content = generateCommandTabContent(tabsHeader[i], id);
$("#tabbedSet").append(header);
$("#tabbedSet").find("#" + headerId).append(content);
$("#tabbedSet").collapsibleset("refresh");
$('input[name=direction]').parent().addClass('cleassr')
$("#tabbedSet").children(":first").collapsible( "expand" );
}
}
function generateCommandTabContent(name, id) {
var commandName = "VoiceCallAudioMosMO";
if (name == "InputParameter") {
var object = new window[commandName]();
var map = object.generateInputRequirment();
var formData = generateInputParamForm(map, id, status);
var form = $("<form />");
var dform = form.dform(formData);
return dform;
}
return null;
}
function VoiceCallAudioMosMO() {
COMMAND_NAME = "VoiceCallMos";
COMMAND_DISPLAY_NAME = "VoiceCallMOS";
this.map = {};
}
VoiceCallAudioMosMO.prototype.generateInputRequirment = function () {
if(typeof VoiceCallAudioMosMO.JSON!="undefined") {
var inputs = VoiceCallAudioMosMO.JSON.input;
for (var key in inputs) {
var inputField = inputs[key];
var inputParameterInfo = new InputParameterInfo();
for (var inputKey in inputField) {
inputParameterInfo[inputKey] = inputField[inputKey];
}
this.map[inputParameterInfo.name] = inputParameterInfo;
}
return this.map;
}
};
function InputParameterInfo() {
}
VoiceCallAudioMosMO.JSON = {
"commandName": "VoiceCallAudioMosMO",
"input": {
"refFileName": {
"displayDetail": "The reference file name to play in case of uplink channel",
"displayName": "Ref File Name",
"inputType": "SWITCH",
"name": "refFileName",
"inputValues": {
"USAReference.wav": "USAReference.wav",
"Reference.wav": "Reference.wav"
},
"value": "",
"unit": "NONE",
"required": false,
"visible": true
}
}
};
function generateInputParamForm(map, id, status) {
var formId = "form_" + id;
var formdata = {
elements : []
};
formdata.id = formId;
formdata.name = formId;
formdata.method = "post";
var div = {
html : []
};
div.type = "div";
div.class = "inputDiv";
div.caption = "<h3>Input Parameters</h3>";
var tabIndex = 1;
var arr = id.split("-");
var data = null;
for ( var key in map) {
var inputObj = map[key];
if (inputObj.visible==false && inputObj.required==false) {
continue;
}else {
var obj = createFormObject(inputObj);
}
//var obj = createFormObject(inputObj);
if(typeof data=="undefined"){
obj.value = inputObj["value"];
}else if (data != undefined && data.hasOwnProperty(inputObj["name"])) {
obj.value = data[inputObj["name"]];
}
/*if (data != undefined && data.hasOwnProperty(inputObj["name"])) {
obj.value = data[inputObj["name"]];
} else if (inputObj.hasOwnProperty("value")) {
obj.value = inputObj["value"];
}*/
if (status == "view") {
obj.readonly = "true";
obj.disabled = "disabled";
}
obj.tabindex = tabIndex;
var objName = "VoiceCallAudioMosMO";
obj.onblur = "validateElement('" + objName + "', '" + formId + "','"
+ obj.name + "')";
var unit = {};
var fieldset = {
html : []
};
fieldset.type = "fieldset";
fieldset.caption = inputObj["displayName"];
fieldset.html.push(obj);
$("div > fieldset legend:contains('*')").each(function () {
$(this).html($(this).html().replace("*", "<span class='red'>*</span>"));
});
div.html.push(fieldset);
tabIndex++;
}
formdata.elements.push(div);
return formdata;
}
function createFormObject(inputObj) {
var obj = {};
if (inputObj.hasOwnProperty("inputType")) {
if (inputObj["inputType"] == "LIST") {
var list = inputObj["inputValues"];
obj.type = "select";
obj.options = list;
} else if (inputObj["inputType"] == "NUMBER") {
obj.type = "text";
} else if (inputObj["inputType"] == "SWITCH") {
var list = inputObj["inputValues"];
obj.type = "select";
obj.options = list;
} else {
obj.type = "text";
}
} else {
obj.type = "text";
}
if (!inputObj.hasOwnProperty("displayName")) {
obj.type = "hidden";
}
obj.id = inputObj["name"];
obj.name = inputObj["name"];
obj.required = inputObj["required"];
obj.placeholder = inputObj["placeholder"];
obj.classes = inputObj["class"];
obj.className = inputObj["class"];
obj.class = inputObj["class"];
obj.title= inputObj["displayDetail"];
return obj;
}
</script>
</html>
It display a drop down when you click button.Drop down Value USAReference.wav.here I written "w" in small but it display in capital.but when I remove this css
https://dl.dropboxusercontent.com/s/bbvcx2zc4ocuqzt/bootstrap.min.css?m=" rel="stylesheet" type="text/css" />
it show in small letter ? why ?
After a long research I found the solution own .there is a property
text-transform: capitalize written on 247 line Number bootstrap.css file.I remove that property.I am able to solve my problem
I need to display the selected sub-categories (multi) in the below div and also in some situations I need to close the div elements that are selected wrongly from the select box, so that I can add and delete elements to the div (by the above selectbox).
Even I made the similar code, but its not working for multi selection.
Briefly, I need the selected categories (multi) with close buttons in the below div.
<script type="text/javascript">
function selectlist() {
checkboxhome = document.getElementById("check");
catogery = document.getElementById("cat");
value = catogery.options[catogery.selectedIndex].value;
checkboxhome.innerHTML = "<br/> <p>" + value + "</p>";
}
</script>
<body>
<form action="#" enctype="multipart/form-data">
<select name="cat" id="cat" onchange="selectlist();" multiple="multiple">
<option>Select subcatogery</option>
<option value="fashion">Fashion</option>
<option value="jewelry">Jewelry</option>
<option value="dresses">dresses</option>
<option value="shirts">Shirts</option>
<option value="diamonds">Diamonds</option>
</select>
<div id="check">
</div></form>
</body>
</html>
Loop over the options and check if they are selected, something like this:
function selectlist() {
var checkboxhome = document.getElementById("check");
var category = document.getElementById("cat");
checkboxhome.innerHTML = '';
for (var i = 0; i < category.options.length; i++) {
if (category[i].selected) {
checkboxhome.innerHTML += "<p>" + category.options[i].value + "</p>";
}
}
}
Here is a fiddle of what could work for you: http://jsfiddle.net/maniator/W6gnX/
Javascript:
function selectlist() {
checkboxhome = document.getElementById("check");
catogery = document.getElementById("cat");
value = getMultiple(catogery);
checkboxhome.innerHTML = "<br/> <p>" + value + "</p>";
}
function getMultiple(ob)
{
var arSelected = new Array(), length = ob.length, i = 0, indexes = [];
while (ob.selectedIndex != -1 && i < length)
{
if (ob.selectedIndex != 0 && !in_array(ob.selectedIndex, indexes)) {
indexes.push(ob.selectedIndex)
arSelected.push(ob.options[ob.selectedIndex].value);
}
ob.options[ob.selectedIndex].selected = false;
i++;
}
var count = 0;
while(count < indexes.length){
ob.options[indexes[count]].selected = true;
count ++;
}
return arSelected;
}
function in_array(needle, haystack)
{
for(var key in haystack)
{
if(needle === haystack[key])
{
return true;
}
}
return false;
}