I am new in Json and javascript . What I want is a select tag with option, thus by selecting the options - that particular object will be fetched from JSON and will be displayed , I have used Nested JSON .
data.json:
var data = {
"abc":{
"color":["rgb(4,45,97)","rgb(255,122,0)"],
"font":"Interface Thin",
"logo":"<img src='logo.png' width='200' height='150'>"
}
}
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="data.json"></script>
</head>
<body>
<!--document.getElementById('color').innerHTML += '<div style="border:1px solid black;padding:2px;width:100px;background-color:'+data.AllenandHanburys[j]+';height:100px"></div>'-->
<p id="demo"></p>
<p id="color"></p>
<p id="logo"></p>
<select id="brand" onChange="run()">
<option>Select Option</option>
<option value="abc">abc</option>
</select>
</body>
<script>
var i;
function run() {
var brand_name=document.getElementById('brand').value;//
for(x in data)
{
if(x==brand_name)
{
for(j in data.brand_name)
{
document.getElementById('demo').innerHTML +=j+":"+data.abc[j]+"<br>";
if(j=='color')
{
for(i=0;i<data.abc.color.length;i++)
{
document.getElementById('color').innerHTML +='<div style="border:1px solid black;padding:2px;width:100px;background-color:'+data.abc.color[i]+';height:100px"></div>'+"<br>";
}
}
}
}
}
}
</script>
</html>
this line is wrong,
for(j in data.brand_name) //because `brand_name` property is not exist in the object
change it to
for(j in data[brand_name]) //data[brand_name] will parsed as data['abc'] which is same as data.abc
Here's the demo
var data = {
"abc":{
"color":["rgb(4,45,97)","rgb(255,122,0)"],
"font":"Interface Thin",
"logo":"<img src='logo.png' width='200' height='150'>"
}
}
var i;
function run() {
var brand_name=document.getElementById('brand').value;//
for(x in data)
{
if(x==brand_name)
{
for(j in data[brand_name])
{
document.getElementById('demo').innerHTML +=j+":"+data.abc[j]+"<br>";
if(j=='color')
{
for(i=0;i<data.abc.color.length;i++)
{
document.getElementById('color').innerHTML +='<div style="border:1px solid black;padding:2px;width:100px;background-color:'+data.abc.color[i]+';height:100px"></div>'+"<br>";
}
}
}
}
}
}
<p id="demo"></p>
<p id="color"></p>
<p id="logo"></p>
<select id="brand" onChange="run()">
<option>Select Option</option>
<option value="abc">abc</option>
</select>
I have to make a div triangle like this, with looping in JavaScript. Anyone know how to make this?
*Input using <select> tag. Thanks!
Check this
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(document).ready(function () {
var container = $("#html2");
$("#CreateDiv").change(function () {
$('#html2').html('');
var strBlocksHTML = '';
var selectedvalue = $("#CreateDiv option:selected").val();
for (var i = 0; i <= selectedvalue; i++) {
for (var n = 0; n < i ; n++) {
strBlocksHTML += '<div id="pdfDiv" style=" background-color:red; display:inline-block; width:50px; height:50px; margin:2px 5px; border:2px solid #ccc;"> </div>';
}
strBlocksHTML += '<div></div>';
}
$('#html2').append(strBlocksHTML);
})
});
</script>
</head>
<body style="text-align:center">
<div>
<select id="CreateDiv">
<option value="0"> Select</option>
<option value="1"> One</option>
<option value="2"> Two</option>
<option value="3"> There</option>
<option value="4"> Four</option>
<option value="5"> Five</option>
</select>
</div>
<br />
<br />
<div id="html2" style="text-align:center">
</div>
</body>
</html>
Simple double loop. First loop for rows, second for single div.
var levels = 5;
var output = '';
for (var row = 1; row <= levels; row++) {
output += '<div class="row">';
for (var i = 0; i < row; i++) {
output += '<div class="item"></div>'
}
output += '</div>';
}
document.write(output);
.row {
text-align: center;
}
.item {
display: inline-block;
width: 40px;
height: 40px;
border: 1px solid green;
background: gray;
}
I have to create table by clicking button where as table contains columns and rows specified by user. After that,we have to fill each table cell by performing onclick with the color listed in the drop down list menu.
The below code snippet is to create table with user's input. I don't know to proceed further. How to perform this ?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style>
.highlighted {
background: red;
}
table{
width:500px;
height:500px;
}
table td{
padding:10px;
margin:10px;
border:1px solid #ccc;
}
table tr{
height:100px;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function createTable(){
mytable = $('<table></table>').attr({ id: "basicTable" });
var rows = new Number($("#rows").val());
var cols = new Number($("#columns").val());
var tr = [];
for (var i = 0; i < rows; i++) {
var row = $('<tr></tr>').attr({ class: ["class1", "class2", "class3"].join(' ') }).appendTo(mytable);
for (var j = 0; j < cols; j++) {
$('<td></td>').text("").appendTo(row);
}
}
console.log("TTTTT:"+mytable.html());
mytable.appendTo("#matrixTableId");
}
</script>
</head>
<body>
Enter Rows <input type='text' id='rows'><br>
Enter Cols <input type='text' id='columns'><br>
<input type="button" onclick="createTable();" name="save" value="Form Matrix" /><br>
Choose Color: <select id="dropDown">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="yellow">Yellow</option>
</select>
<br><br>
<div id="matrixTableId">
</div>
</body>
</html>
Try this : You can add a click event handler for all td and set background-color as a value from dropDown.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style>
.highlighted {
background: red;
}
table{
width:500px;
height:500px;
}
table td{
padding:10px;
margin:10px;
border:1px solid #ccc;
}
table tr{
height:100px;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function createTable(){
mytable = $('<table></table>').attr({ id: "basicTable" });
var rows = new Number($("#rows").val());
var cols = new Number($("#columns").val());
var tr = [];
for (var i = 0; i < rows; i++) {
var row = $('<tr></tr>').attr({ class: ["class1", "class2", "class3"].join(' ') }).appendTo(mytable);
for (var j = 0; j < cols; j++) {
$('<td></td>').text("").appendTo(row);
}
}
console.log("TTTTT:"+mytable.html());
mytable.appendTo("#matrixTableId");
}
$(function(){
$(document).on("click","table tr td", function(){
var color = $('#dropDown').val();
$(this).css('background-color', color);
});
});
</script>
</head>
<body>
Enter Rows <input type='text' id='rows'><br>
Enter Cols <input type='text' id='columns'><br>
<input type="button" onclick="createTable();" name="save" value="Form Matrix" /><br>
Choose Color: <select id="dropDown">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="yellow">Yellow</option>
</select>
<br><br>
<div id="matrixTableId">
</div>
</body>
</html>
You should handle onclick event of td and set background of clicked td to select value
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style>
.highlighted {
background: red;
}
table{
width:500px;
height:500px;
}
table td{
padding:10px;
margin:10px;
border:1px solid #ccc;
}
table tr{
height:100px;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function createTable(){
mytable = $('<table></table>').attr({ id: "basicTable" });
var rows = new Number($("#rows").val());
var cols = new Number($("#columns").val());
var tr = [];
for (var i = 0; i < rows; i++) {
var row = $('<tr></tr>').attr({ class: ["class1", "class2", "class3"].join(' ') }).appendTo(mytable);
for (var j = 0; j < cols; j++) {
var $td = $('<td></td>');
$td.text("").appendTo(row);
$td.click(function(){
$(this).css('background',$('#dropDown').val());
});
}
}
console.log("TTTTT:"+mytable.html());
mytable.appendTo("#matrixTableId");
}
</script>
</head>
<body>
Enter Rows <input type='text' id='rows'><br>
Enter Cols <input type='text' id='columns'><br>
<input type="button" onclick="createTable();" name="save" value="Form Matrix" /><br>
Choose Color: <select id="dropDown">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="yellow">Yellow</option>
</select>
<br><br>
<div id="matrixTableId">
</div>
</body>
</html>
I made a way to add and remove fields using the input[type"number"]. I use jquery to do this but the way I did is not perfect. If there's a value in the field, the value will get erase if the number value is change because of using .remove(). Is there a better way to doing this?
<body>
<input type="number" id="num" min="0" max="20" required/>
<div class="dynamicInput"></div>
</body>
<script>
$('#num').bind('keyup mouseup', function () {
$('.dynamicInput .row').remove();
$('.dynamicInput h4').remove();
if ($(this).val() > 0) {
$('.dynamicInput').append('<h4>Please fill in the name and email of each extra attendees</h4>');
var num = $(this).val();
for (var i = 0; i < num; i++) {
$('.dynamicInput').append('<div class="row"><div class="col1"><input type="text" name="attendeesName' + i + '" placeholder="Name" required /></div><div class="col2"><input type="text" name="attendeesEmail' + i + '" placeholder="Email" required /></div></div>');
}
}
});
</script>
My Fiddle
Try something like this. Instead of removing all of the inputs every time, this just removes the ones on the end, or adds more to the end.
The main difference between this one and yours is that I added var totNum = 0; to keep track of the current number of input there are. I then used that to determine how many to add/remove.
var totNum = 0;
$(document).on('keyup mouseup', '#num', function(){
var num = $(this).val();
if (num != "")
{
if (totNum == 0)
$('.dynamicInput').append('<h4>Please fill in the name and email of each extra attendees</h4>');
for (var i = num; i < totNum; i++)
{
$('.dynamicInput .row:last-child').remove();
}
for (var i = totNum; i < num; i++)
{
$('.dynamicInput').append('<div class="row"><div class="col1"><input type="text" name="attendeesName' + i + '" placeholder="Name" required /></div><div class="col2"><input type="text" name="attendeesEmail' + i + '" placeholder="Email" required /></div></div>');
}
totNum = num;
if (totNum == 0)
{
$('.dynamicInput h4').remove();
$('.dynamicInput .row').remove();
}
}
});
input[type="number"] {
width: 200px;
height: 30px;
font-family: Arial, sans-serif;
font-size: 20px;
}
.row {
display: block;
margin-bottom: 15px;
}
body {
width: 100%;
padding: 40px;
}
input[type="text"] {
width: 100%;
}
.col1,
.col2 {
width: 45%;
display: inline-block;
margin-right: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<body>
<input type="number" id="num" min="0" max="20" required/>
<div class="dynamicInput"></div>
</body>
It's easier and less likely to fail using a data structure as a skeleton upon which you can build the view. Note that this technique requires an extra computation in order to save user inputs, this is the reason why I've added the "change" event.
In the following code snippet, I've made two panels side by side. The left one is a list of inputs, very close to yours, easy to adapt to your needs, while the right one allows to see the evolution of the "data" array according to user actions.
Both panels rely on the "data" array, in other words, as soon as new items are added to or removed from "data", or a single item is updated, both panels are fully rebuilt. Note that the "change" event takes advantage of event delegation in order to deal with newly added inputs.
Finally, the "update" functions update the entire data source or a single item of the data source when the corresponding input changes, while the "render" functions draw on the data source to keep the panels in sync with the data. By the way, the right panel is rendered once at starting.
$(function () {
var data = []; // data source
var $num = $('#num'); // input for number of rows
var $left = $('#left'); // left panel
var $right = $('#right'); // right panel
// render the right panel at starting
renderRightPanel();
// when the number of rows changes:
// - rebuild the left panel entirely
// - keep the data list up to date
// - print the array to the right panel
$num.on('keyup mouseup', function () {
renderLeftPanel($(this).val());
updateList();
renderRightPanel();
});
// when a value changes:
// - keep the data item up to date
// - print the array to the right panel
$left.on('change', 'input', function () {
var i = $left.find('input').index(this);
updateItem(i, $(this).val());
renderRightPanel();
});
// updates the data list
function updateList () {
data = $left.find('input').map(function () {
return $(this).val();
}).get();
}
// updates a single data item
function updateItem (index, value) {
data[index] = value;
}
// refreshes the DOM of the right panel
function renderRightPanel () {
$right.html('<pre>data = ' + (
JSON.stringify(data, 0, 4)
) + '</pre>');
}
// refreshes the DOM of the left panel
function renderLeftPanel (nLines) {
var i;
var html = '';
if (nLines > 0) {
html = '<h4>Heading</h4>';
for (i = 0; i < nLines; i++) {
html += '<div><input value="' + (data[i] || '') + '" /></div>';
}
}
$left.html(html);
}
});
body * {
padding: 0;
margin: 0;
}
h4, input {
margin-bottom: .5em;
}
#panels {
border: 1px solid black;
}
#panels > div {
display: table-cell;
padding: 1em;
}
#right {
border-left: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Number of inputs: <input id="num" type="number" value="0" /></div>
<div id="panels">
<div id="left"></div
><div id="right"></div>
</div>
Disable and hide extra elements instead of removing them. That will prevent them from getting posted, and also retain the previous value of all values that have been entered. See fiddle
One last point, if you don't want to retain values of hidden elements, change .hide() to .hide().val("")
<body>
<input type="number" id="num" min="0" max="20" required/>
<div class="dynamicInput">
<h4>Please fill in the name and email of each extra attendees</h4>
</div>
</body>
<style>
.col1, .col2 { display: inline; width: 48%; margin-right: 2%; }
.row { padding: 5px; }
</style>
<script>
for (var i = 0; i < 20; i++) {
$('.dynamicInput').append('<div class="row"><div class="col1"><input type="text" name="attendeesName' + i + '" placeholder="Name" required /></div><div class="col2"><input type="text" name="attendeesEmail' + i + '" placeholder="Email" required /></div></div>');
}
$('#num').bind('keyup mouseup', function () {
var num = parseInt($(this).val());
$('.dynamicInput .row')
.slice(num)
.hide()
.attr('disabled','disabled');
if ( num > 0) {
$('.dynamicInput .row')
.slice(0,num).show()
.removeAttr('disabled');
$('.dynamicInput h4').show();
} else {
$('.dynamicInput h4').hide();
}
}).trigger('keyup');
</script>
Off-hand, you could cache the values within javascript to resist losing them between #num changes. e.g.
(function($){
var $num = $('#num'),
$dynamic = $('.dynamicInput');
cache = {};
$dynamic.on('change', 'input', function(e){
cache[$(this).prop('name')] = $(this).val();
});
$num.on('change keyup mouseup', function(e){
$dynamic.empty();
var val = parseInt($(this).val(), 10);
if (!isNaN(val) && val > 0){
$('<h4>')
.text('Please fill in the name and email of each extra attendees')
.appendTo($dynamic);
for (var i = 0; i < val; i++){
var nameName = 'attendeesName' + i,
emailName = 'attendeesEmail' + i;
var $row = $('<div>',{'class':'row'}),
$col1 = $('<div>',{'class':'col1'}).appendTo($row),
$col2 = $('<div>',{'class':'col2'}).appendTo($row);
$('<input>',{
'type': 'text',
'name': nameName,
'placeholder': 'Name',
'required': 'true'
}).val(cache[nameName] || '').appendTo($col1);
$('<input>',{
'type': 'email',
'name': emailName,
'placeholder': 'Email',
'required': 'true'
}).val(cache[emailName] || '').appendTo($col2);
$row.appendTo($dynamic);
}
}
});
})(jQuery);
input[type="number"] {
width:200px;
height:30px;
font-family:Arial, sans-serif;
font-size:20px;
}
.row {
display:block;
margin-bottom:15px;
}
body{
width:100%;
padding:40px;
}
input[type="text"]{
width:100%;
}
.col1, .col2{
width:45%;
display:inline-block;
margin-right:10px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" id="num" min="0" max="20" required/>
<div class="dynamicInput"></div>
Here is an attempt to improve the accepted answer:
$(function () {
var $num = $('#num');
var $panel = $('#panel');
var h4 = '<h4>Heading</h4>';
var row = '<div><input /></div>';
$num.on('mouseup keyup', function () {
var n, $inputs;
var value = $(this).val();
if (value <= 0) {
$panel.empty();
}
else {
$inputs = $panel.find('input');
// get the number of inputs already added
n = $inputs.size();
// add your heading if there is no input
if (n === 0) {
$panel.append(h4);
}
// the user wants less inputs
if (value < n) {
$inputs.slice(value).remove();
}
// the user wants more inputs
else if (value > n) {
$panel.append(
// a little trick, see below
new Array(value - n + 1).join(row)
);
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Number of inputs: <input id="num" type="number" value="0" /></div>
<div id="panel"></div>
A word on the "array join trick":
var a = [1, 2, 3, 4];
console.log(a.join('+'));
// prints "1+2+3+4"
var b = new Array(4); // an array of 4 undefined items
console.log(b.join('+'));
// prints "+++"
var c = new Array(3);
console.log('<ul>' + c.join('<li>item</li>') + '</ul>');
// prints "<ul><li>item</li><li>item</li></ul>"
This is what exactly you are looking for,
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#num").keyup(function(){
$('.dynamicInput .row').remove();
$('.dynamicInput h4').remove();
if ($(this).val() > 0) {
$('.dynamicInput').append('<h4>Please fill in the name and email of each extra attendees</h4>');
var num = $(this).val();
for (var i = 0; i < num; i++) {
$('.dynamicInput').append('<div class="row"><div class="col1"><input type="text" name="attendeesName' + i + '" placeholder="Name" required /></div><div class="col2"><input type="text" name="attendeesEmail' + i + '" placeholder="Email" required /></div></div>');
}
}
});
});
</script>
</head>
<body>
<input type="number" id="num" min="0" max="20" required/>
<div class="dynamicInput"></div>
</body>
</html>
Here is my code i tried to print the selected value from selected box.But its printing only the first value of selected item.I don't know how to get the length of selected value.any one help me for this problem
<html>
<head>
<title>jQuery Dropdown CheckList</title>
<link rel="stylesheet" type="text/css" href="jquery-ui-1.8.13.custom.css">
<link rel="stylesheet" type="text/css" href="ui.dropdownchecklist.themeroller.css">
<style>
table td { vertical-align: top }
dd { padding-bottom: 15px }
</style>
<script type="text/javascript" src="jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.8.13.custom.min.js"></script>
<script type="text/javascript" src="ui.dropdownchecklist-1.4-min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#s10").dropdownchecklist( { forceMultiple: true
, onComplete: function(selector) {
var values = "";
for( i=0; i < selector.options.length; i++ )
{
if (selector.options[i].selected && (selector.options[i].value != ""))
{
if ( values != "" )
values += ";";
values += selector.options[i].value;
}
}
alert(values);
}
, onItemClick: function(checkbox, selector)
{
var justChecked = checkbox.prop("checked");
var checkCount = (justChecked) ? 1 : -1;
for( i = 0; i < selector.options.length; i++ ){
if (selector.options[i].selected )
checkCount += 1;
}
}
});
});
</script>
</head>
<body>
<div id="content">
<table>
<tr>
<td>
<select id="s10">
<option value=""></option>
<option value='a'>Alice</option>
<option value='b'>Bob</option>
<option value='c'>Christian</option>
<option value='d'>Daniel</option>
<option value='e'>Elizabeth</option>
</select>
</td>
</tr>
</table>
</div>
</body>
</html>
for taking the length of checkbox selected item I did this but i don't know it only giving 1 as alert message
onItemClick: function (checkbox, selector)
{
$("input:checked").each(function()
{
alert($(this).val().length);
});
} });
Try this, Hope it will work
<select id="s10" multiple="multiple">
<script type="text/javascript">
$(document).ready(function() {
var foo = [];
$('#s10:selected').each(function(i, selected){
foo[i] = $(selected).text();
});
});
</script>
get the selected option with :selected:
$('#s10 option:selected').val();
What i meant to say is this: http://jsfiddle.net/T4UDu/
$('#s10').change(function(){
alert($('option:selected',this).val());
});
$('#checkboxId').change(function(){
alert($('option:selected',this).val());
});