Embedding values using for loop - javascript

As I m having incremental values of attributes so i am ´following this method as you can see I hardcoded my attributes butI want to embed them in a loop..please tell how can i do that.. I am not able to achieve that...Thank you..
I m getting values in my dropdown from a json file in which i m having 20 attributes...When i click on particular value from dropdown ...the attributes related to that value are shown inside a list box..
My html
form name="myform" id="myForm">
<select id="dropdown1"></select>
<select id="listbox"></select>
<!-- <input type="checkbox">-->
<br>
(document).ready(function() {
$.ajax({
url: "data.json",
dataType: "json",
success: function(obj) {
var jsObject = obj;
var usedNames = [];
$('<option>', {
text: 'Select your Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#dropdown1');
$.each(obj, function(key, value) {
if (usedNames.indexOf(value.name) == -1) {
$("#dropdown1").append("<option value=" + key + ">" + value.name + "</option>");
usedNames.push(value.name);
}
/* $('<option>', {
text: 'Select your Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#dropdown1');
*/
$.each(usedNames, function(index, value) {
$('<option>', {
text: value['name'],
value: index
}).appendTo('#dropdown1');
});
/* $('<option>', {
text: 'Select your List Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#listbox'); */
$('#dropdown1').change(function() {
$('#listbox').empty();
$('<option>', {
text: 'Select your List Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#listbox');
var selection = $('#dropdown1 :selected').text();
var selection = $('#dropdown1 :selected').text();
$.each(jsObject, function(index, value) {
if (value['name'] === selection) {
var optionHtml = '';
for (var i = 1; i <= 20; i++) {
var attr = 'attr' + ('000' + i).substr(-3);
optionHtml += '<option value="' + attr + '">' + value[attr] + '</option>';
}
$('#listbox').append(optionHtml);
}
});
});
});
}
});
});

You can use a for loop to generate the option elements as all the attributes are incremental. Try this:
var selection = $('#dropdown1 :selected').text();
$.each(jsObject, function(index, value) {
if (value['name'] === selection) {
var optionHtml = '';
for (var i = 1; i <= 20; i++) {
var attr = 'attr' + ('000' + i).substr(-3);
optionHtml += '<option value="' + attr + '">' + value[attr] + '</option>';
}
$('#listbox').append(optionHtml);
}
});
Working example
Note that this also builds the HTML as a single string and appends it to the DOM once for better performance.

Related

Cannot set property 'innerHTML' of null in javascript

guys i have a column which contains text and button and what i want is when click on the button the text changed .. here is my code
var count = 0;
$(document).ready(function() {
$("#jqGrid").jqGrid({
data: data.rows,
datatype: "local",
styleUI: "Bootstrap",
colModel: [
{
label: 'Customer ID',
name: 'CustomerID',
width: 180,
editable: true,
edittype: "custom",
id: "CustomerID",
editoptions: {
custom_element: function(value, options) {
var parts = value.split(' ');
var elemStr = '<div><input size="6" id="txt_"' + count + '" value="' + parts[0] +
'" /><input type="button" size="5" value="..." onclick="setText();"/></div>';
count++;
// return DOM element from jQuery object
return $(elemStr)[0];
},
custom_value: function(elem) {
var inputs = $("input", $(elem)[0]);
var first = inputs[0].value;
return first;
}
}
},
],
});
});
function setText() {
document.getElementById("txt_" + count).innerHTML = "hey";
}
so why it gives me that exception ? .. plz help .. btw i am beginner
the count inside setText is undefined.
1st change onclick function of button to pass the count variable
var elemStr = '<div><input size="6" id="txt_"' + count + '" value="' + parts[0] +
'" /><input type="button" size="5" value="..." onclick="setText(' + count + ');"/></div>';
then accept the count as parameter
function setText(count) {
document.getElementById("txt_" + count).innerHTML = "hey";
}
You can pass count to the function:
var count = 0;
$(document).ready(function() {
$("#jqGrid").jqGrid({
data: data.rows,
datatype: "local",
styleUI: "Bootstrap",
colModel: [
{
label: 'Customer ID',
name: 'CustomerID',
width: 180,
editable: true,
edittype: "custom",
id: "CustomerID",
editoptions: {
custom_element: function(value, options) {
var parts = value.split(' ');
var elemStr = '<div><input size="6" id="txt_"' + count + '" value="' + parts[0] +
'" /><input type="button" size="5" value="..." onclick="setText(' + count + ');"/></div>';
count++;
// return DOM element from jQuery object
return $(elemStr)[0];
},
custom_value: function(elem) {
var inputs = $("input", $(elem)[0]);
var first = inputs[0].value;
return first;
}
}
},
],
});
});
function setText(count) {
document.getElementById("txt_" + count).innerHTML = "hey";
}

Double click on the selected item in dropdown

I am having problem that as i select an item from drop-down the list box does not comes i need to click again on the selected item item in drop-down to get the list appear..that means i need a double click on the item in drop-down.
This is my html
<script>
function ShowHideListBox(e) {
e.stopPropagation()
e.preventDefault()
var IsOpen = $('#listbox').attr('IsOpen')
if (IsOpen == "false") {
ShowList(e)
}
else {
HideList(e)
}
}
function ShowList(elem) {
$('#listbox').attr('IsOpen', 'true')
$('#listbox').show()
}
function HideList(elem) {
$('#listbox').attr('IsOpen', 'false')
$('#listbox').hide()
}
</script>
<form name="myform" id="myForm">
<select id="dropdown1" onclick="return ShowHideListBox(event)"></select>
<select id="listbox" multiple style="display:none; cursor:default;" isopen="false"></select>
</form>
My js file
$(document).ready(function() {
$.ajax({
url: "data.json",
dataType: "json",
success: function(obj) {
var jsObject = obj;
var usedNames = [];
$('<option>', {
text: 'Select your Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#dropdown1');
$.each(obj, function(key, value) {
if (usedNames.indexOf(value.name) == -1) {
$("#dropdown1").append("<option value=" + key + ">" + value.name + "</option>");
usedNames.push(value.name);
}
/* $('<option>', {
text: 'Select your Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#dropdown1');
*/
//$.each(usedNames, function(index, value) {
// $('<option>', {
// text: value['name'],
// value: index
// }).appendTo('#dropdown1');
//});
/* $('<option>', {
text: 'Select your List Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#listbox'); */
$('#dropdown1').change(function() {
$('#listbox').empty();
$('<option>', {
text: 'Select your List Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#listbox');
var selection = $('#dropdown1 :selected').text();
// var selection = $('#dropdown1 :selected').text();
$.each(jsObject, function(index, value) {
if (value['name'] == selection) {
var optionHtml = '';
for (var i = 1; i <= 20; i++) {
var attr = 'attr' + ('000' + i).substr(-3);
optionHtml += '<option value="' + attr + '">' + value[attr] + '</option>';
}
$("#listbox").css("width","500px")
$("#listbox").css("height","300px")
$('#listbox').append(optionHtml); return false;
}
});
});
});
}
});
});
You are sending the event and passing it to the Showlist function
You need to send the target Also remove the e.stopPropagation(); e.preventDefault()
<script>
function ShowHideListBox(e) {
var IsOpen = $('#listbox').attr('IsOpen')
if (IsOpen == "false") {
ShowList(e.target)
}
else {
HideList(e.target)
}
}
function ShowList(elem) {
$('#listbox').attr('IsOpen', 'true')
$('#listbox').show()
}
function HideList(elem) {
$('#listbox').attr('IsOpen', 'false')
$('#listbox').hide()
}
</script>
<form name="myform" id="myForm">
<select id="dropdown1" onclick="return ShowHideListBox(event)"></select>
<select id="listbox" multiple style="display:none; cursor:default;" isopen="false"></select>
</form>

How to add HTML text field with value from select list via Javascript

I have select list like this:
$.fn.optionTest = function(opts) {
var option = $.extend({}, $.fn.optionTest.defaults, opts);
$(this).change(function() {
option.holderObject = $(this);
if (option.clearOnChange) {
$(option.actionId).empty();
}
var val = $(this).val();
if ($.fn.optionTest.isArray(val)) {
$.fn.optionTest.parseArray(val, option);
} else {
var label = $(this).children("option:selected").eq(0).text();
$.fn.optionTest.parseContent(val, option, label);
}
$('.' + option.removeLinkOptions.class).click(function(event) {
$.fn.optionTest.removeRow(this, option);
event.preventDefault();
});
$("[type=date]").datepicker({
monthNamesShort: $.datepicker.regional["en"].monthNames,
changeMonth: true,
changeYear: true,
dateFormat: 'yy-mm-dd',
yearRange: "-116:+10",
});
return this;
});
};
$.fn.optionTest.isArray = function(val) {
return Object.prototype.toString.call(val) === '[object Array]';
};
$.fn.optionTest.defaults = {
clearOnChange: false,
actionId: '#action',
indexOptions: {
class: 'field-style field-split25 align-left'
},
rowOptions: {
class: 'certificates',
type: 'text',
name: 'CertificateType[]',
tag: 'ul'
},
CertNoOptions: {
name: 'CertNo[]',
type: 'text',
placeholder: 'Cert No.',
size: 20,
class: 'field-style field-split25 align-left'
},
PlaceofIssueOptions: {
name: 'PlaceofIssueCert[]',
type: 'text',
placeholder: 'Place of Issue',
size: 20,
class: 'field-style field-split25 align-left'
},
fromOptions: {
name: 'FromCert[]',
type: 'date',
placeholder: 'Date of Issue',
size: 20,
class: 'field-style field-split25 align-left'
},
toOptions: {
name: 'ToCert[]',
type: 'date',
placeholder: 'Date of Expire',
size: 20,
class: 'field-style field-split25 align-left'
},
labelOptions: {
class: 'field-style field-split25 align-left',
type: 'text'
},
removeLinkOptions: {
class: 'removeRow',
href: 'javascript:;'
}
};
$.fn.optionTest.parseArray = function(vals, options) {
var selectedOptions = options.holderObject.children("option:selected");
console.log(selectedOptions.eq(0).html());
$.each(vals, function(key, val) {
$.fn.optionTest.parseContent(val, options, selectedOptions.eq(key).text());
});
};
$.fn.optionTest.removeRow = function(elem, options) {
var row = $(elem).closest(".certificates");
row.remove();
$.fn.optionTest.updateRowIndex(options);
};
$.fn.optionTest.updateRowIndex = function(options) {
$("." + options.rowOptions.class).each(function(key, value) {
var index = key + 1;
$(value).attr('rowdataid', index);
$(value).children("." + options.indexOptions.class).html(index);
});
};
$.fn.optionTest.createColumn = function(content) {
var li = $('<li>');
return li.append(content);
}
$.fn.optionTest.parseContent = function(val, options, label) {
var index = $('.' + options.rowOptions.class).length + 1;
var rowData = $.extend({}, options.rowOptions);
var indexData = $.extend({}, options.indexOptions);
rowData.rowDataId = index;
var CertNoData = $.extend({}, options.CertNoOptions);
CertNoData.name = CertNoData.name;
var PlaceofIssueData = $.extend({}, options.PlaceofIssueOptions);
PlaceofIssueData.name = PlaceofIssueData.name;
var DateofIssueData = $.extend({}, options.DateofIssueOptions);
DateofIssueData.name = DateofIssueData.name;
var DateofExpireData = $.extend({}, options.DateofExpireOptions);
DateofExpireData.name = DateofExpireData.name;
var fromData = $.extend({}, options.fromOptions);
fromData.name = fromData.name;
var toData = $.extend({}, options.toOptions);
toData.name = toData.name;
var start_by = "<li><ul class='column'><li>";
var end_by = "</li></ul></li>";
var labelData = $.extend({}, options.labelOptions);
if ($('#' + rowData.id).length == 0) {
var tag = "<" + rowData.tag + ">";
delete rowData['tag'];
var row = $(tag, rowData);
var id = $('<li>', indexData).html(index);
//var label = $('<li>', labelData).html(label);
var label = $.fn.optionTest.createColumn($("<input>", labelData));
label = $(start_by + $(label).html() + end_by);
var CertNo = $.fn.optionTest.createColumn($("<input>", CertNoData));
CertNo = $(start_by + $(CertNo).html() + end_by);
var PlaceofIssue = $.fn.optionTest.createColumn($("<input>", PlaceofIssueData));
PlaceofIssue = $(start_by + $(PlaceofIssue).html() + end_by);
var DateofIssue = $.fn.optionTest.createColumn($("<input>", DateofIssueData));
DateofIssue = $(start_by + $(DateofIssue).html() + end_by);
var DateofExpire = $.fn.optionTest.createColumn($("<input>", DateofExpireData));
DateofExpire = $(start_by + $(DateofExpire).html() + end_by);
var from = $.fn.optionTest.createColumn($("<input>", fromData));
from = $(start_by + $(from).html() + end_by);
var to = $.fn.optionTest.createColumn($("<input>", toData));
to = $(start_by + $(to).html() + end_by);
var removeRow = $.fn.optionTest.createColumn($("<button>", options.removeLinkOptions).text("X"));
removeRow = $($(removeRow).html());
// row.append(label).append(CertNo).append(PlaceofIssue).append(from).append(to).append(removeRow);
row.append('<input type="hidden" name="RowCertificateType[]" value="' + val + '" />').append(label).append(CertNo).append(PlaceofIssue).append(from).append(to).append(removeRow);
$(options.actionId).append(row);
}
};
$(document).ready(function() {
$('#options').optionTest({
actionId: '.action2',
clearOnChange: false
});
});
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<fieldset class="fieldset-borders">
<legend>6. Certificates</legend>
<ul class="header">
<li>
<select id='options' name="CertificateType[]" class="field-style div-format align-left">
<option selected disabled value="0">Select certificates</option>
<option value="1">Foo</option>
<option value="2">Bar</option>
<option value="3">OTHER</option>
</select>
</li>
</ul>
<div class="action2" ></div>
</fieldset>
As you see after selecting any option from list It adding some fields. I need to add text field label with value that selected from options.
As in example I have 3 options:
Foo
Bar
OTHER
If I select Foo It should add fields like:
Foo [ ] [ ] [ ] [ ]
If I select Bar It should add fields like:
Bar [ ] [ ] [ ] [ ]
If I select OTHER It should generate only blank fields without value:
[ ] [ ] [ ] [ ] [ ]
For now It adding all blank fields for any selected option.
If I use:
var label = $('<li>', labelData).html(label);
Instead of:
var label = $.fn.optionTest.createColumn($("<input>", labelData));
label = $(start_by + $(label).html() + end_by);
It adding label field with value, but not editable, It's not text field and after adding OTHER It can't be changed.
Have you ideas how can I achieve correct syntax with If? Something like:
If (option selected = 'OTHER') {
var label = $.fn.optionTest.createColumn($("<input>", labelData));
label = $(start_by + $(label).html() + end_by);
}
else {
var label = $('<li>', labelData).html(label);
}
I cannot be certain that I understand your question, but I think what you want is for the selected label to display as the value in the first input field, unless the selected label is "OTHER", in which case the field should have no value property.
If this is correct, we could achieve this by extending our labelData object:
var labelData = $.extend({}, options.labelOptions, {
value: ((label === 'OTHER') ? '' : label)
});

Dropdown selected default to be the blank option

Iam using MVC4, initially my dropdown displays the list of data,
My javascript looks like,
$.each(data, function (value, key) {
var opt = "<option value=\"" + key + "\">" + value + "</option>";
$("#OwnerAgency").append(opt);
});
How do i set the selected default to be the blank option.
html:
<div class="SmallTopSpace">
<span class="LabelNormal">Primary Case Agency</span>
#Html.DropDownListFor(m => m.Agencies.AgencyKey, new SelectList(""), "", new { #class = "ImportDropDownMax", #id = "OwnerAgency", #onchange = "OwnerAgencyFunction();" })
</div>
before the $.each just append at that start of the data array another empty element .
or in your html do :
<select>
<option disabled selected></option>
</select>
Can't you just insert an empty option at the top in your view/html?
<select id="OwnerAgency">
<option></option>
</select>
Or you can add it in javascript.
var emptyOption = true;
$.each(data, function (value, key) {
var opt;
if (emptyOption) {
opt = "<option></optino>";
$("#OwnerAgency").append(opt);
emptyOption = false;
}
opt = "<option value=\"" + key + "\">" + value + "</option>";
$("#OwnerAgency").append(opt);
});
<select id="mySelect">
</select>
script:
var myOptions = {
val1 : 'text1',
val2 : 'text2'
};
var mySelect = $('#mySelect');
$.each(myOptions, function(val, text) {
mySelect.append(
$('<option></option>').val(val).html(text)
);
});
mySelect.append('<option value=' + myOptions.length + ' selected>default</option>');
set your default select before or after select list generation http://jsfiddle.net/3ns3fj3t/
in your case:
$.each(data, function (value, key) {
var opt = "<option value=\"" + key + "\">" + value + "</option>";
$("#OwnerAgency").append(opt);
});
$("#OwnerAgency").append('<option value=' + data.length + ' selected>default</option>');
You could do it in your C# ViewModel by adding an empty element to SelectList object:
var selectList = new SelectList(....);
selectList.Items.Insert(0, new ListItem(String.Empty, String.Empty));
selectList.SelectedIndex = 0;

Adding a HREF to a JQuery Dynamically Populated Select

I have a form based menu which automatically populates the select options with the contents of a primary-nav UL. It wonderfully increments the with dashes reflecting the positions of the menu.
However, it doesn't populate the with the HREFs of the links within the ULs.
This is the code that I have:
<script>
$(function() {
var options = '<option selected></option>';
$('#primary-nav').find('a').each(function () {
var text = $(this).text(),
depth = $(this).parent().parents('ul').length,
depthChar = '',
i = 1;
for (i; i < depth; i++) { depthChar += '– ';
}
options += '<option>' + depthChar + text + '</option>';
});
$('<select id=\'mobile-menu\' />').append(options).appendTo('#mobile-nav');
$("#primary-nav select").change(function() {
window.location = $(this).find("option:selected").val();
});
});
</script>
I need to somehow add the below to the above so that when clicked the selected option goes to a url, and not a url based on the displayed value;
$("#primary-nav a").each(function() {
var el = $(this);
$("<option />", {
"value" : el.attr("href"),
"text" : el.text()
}).appendTo("#primary-nav select");
});
Can anyone advise me how I can do this?
Thank you.
You can just add the value attribute in your current code:
$('#primary-nav').find('a').each(function () {
var text = $(this).text(),
href = $(this).attr('href'),
depth = $(this).parent().parents('ul').length,
depthChar = '',
i = 1;
for (i; i < depth; i++) {
depthChar += '– ';
}
options += '<option value="'+href+'">' + depthChar + text + '</option>';
});
$('<select id=\'mobile-menu\' />').append(options).appendTo('#mobile-nav');

Categories

Resources