I have a combo box with one option hard coded.
I will add the remaining options dynamically
Combo box with hard coded option:
<select id="connectionname" class="connectionname" onchange="display();"><option>---Select---</option></select>
Javascript function to create combo box options dynamically:
function showDbDlg(){
var newar=new Array();
try{
var xhrArgs = {
url: "./ReadDBDetails",
content: {MODE:"DBNAMES"},
handleAs: "text",
load: function(response) {
var dbNames = response.trim();
dbNames=dbNames.substring(0,dbNames.length-1);
dbArray=dbNames.split(",");
/*var selectValue = document.getElementById("connectionname").value;
alert(selectValue);*/
document.getElementById("connectionname").options.length = 0;
for(var i=0;i<dbArray.length;i++){
var newValue = document.getElementById("connectionname").appendChild(document.createElement('option'));
newValue.text = dbArray[i];
}
formDialog.show();
},
error: function(error) {
alert("An unexpected error occurred: " + error);
}
};
var deferred = dojo.xhrPost(xhrArgs);
}catch(e){alert(e);}
}
Before creating options dynamically, every time am using the below line to clear the existing options.
document.getElementById("connectionname").options.length = 0;
Its clearing the hard coded option as well.
My need is, i want to clear the dynamically created options alone.. not the hard coded one.
Have you tried this?
document.getElementById("connectionname").options.length = 1;
Related
I am using MVC.
I am having two drop down and one change of 'primaryspec' the 'primarysubspec' should get loaded.
Everything is working fine for passing values to controller and it got saved to DB.
When I am trying to retrieve the saved details,'primarysubspec' saved values are not getting displayed.
But displaying save data for 'primarySpec'.
Here is my .cshtml code:
#Html.DropDownListFor(m => m.PSpec, Model.PSpec, new { id = "ddUserSpec", style = "width:245px;height:25px;", data_bind = "event: {change: primaryChanged}" }, Model.IsReadOnly)
#Html.DropDownListFor(m => m.PSubspec, Model.PSubspec, new { id = "ddUserSubSpec", style = "width:245px;height:25px;", data_bind = "options: primarySubSpec,optionsText: 'Name',optionsValue: 'Id'" }, Model.IsReadOnly)
Here is my JS Code to retrieve the values for :
this.primarySubSpec = ko.observableArray([]);
this.primarySpecChanged = function () {
var val = $("#ddetailsPrimarySpec").val();
primarySubStartIndex = 0;
primarySubSpecialityUrl = '/PlatformUser/GetSpecandSubSpec?primarySpe=' + val+//model.primarySpecID() +'&secondarySpec=';
loadPrimarySubSpec();
};
function loadPrimarySubSpec() {
$.ajax({
type: 'GET',
url: primarySubSpecUrl,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
processdata: false,
cache: false,
success: function (data) {
primarySubSpec = [];
model.primarySubspec('0');
try {
if (data.length == 0) {
primarySubSpeacId.empty();
}
model.primarySubSpec(data);
},
error: function (request, status, error) {
primarySubSpeacId.prop("disabled", true);
}
});
}
Everything is working fine,but facing issue only while displaying the saved values from the DB.
Showing fine for 'primarySpec'
The values showing empty for 'PrimarySubSpec' instead of saved values in dropdown.
Please let me know what is the issue how can i show the saved value as selected value in 'primarySubSpec'dropdown.
The Problem:
when you load the page to view saved values, the change event is never called.
Why:
When your page is loaded with saved values, the select box has the saved value selected before knockout knows anything about it. Hens the change event isn't called.
Simplest solution:
change the primarySpecilaityChanged as follows
this.primarySpecilaityChanged = function () {
var val = $("#ddUserDetailsPrimarySpeciality").val();
if(val){
primarySubStartIndex = 0;
primarySubSpecialityUrl = '/' + NMCApp.getVirtualDirectoryName() + '/PlatformUser/GetSpecialitiesandSubSpecilaities?primarySpeciality=' + val+//model.primarySpecialityUID() +'&secondarySpeciality=';
loadPrimarySubSpecilaities();
}
};
then call primarySpecilaityChanged function after you call ko.applyBindings.
var viewModel = new YourViewModel();
ko.applyBindings(viewModel);
viewModel.primarySpecilaityChanged();
I am trying to parse a dynamically inserted form to add the jQuery unobtrusive validation.
I have the following AJAX function which is executed when the user is searching:
function search(el)
{
var $this = $(el);
var $form = $this.closest("form");
var url = $form.attr("action");
$results = $("#pnlSearchResults");
$.ajax({
type: "POST",
url: url,
data: $form.serialize()
})
.done(function(data){
$results.html('');
$results.html(data);
var $editForm = $results.find("form.edit-form");
$editForm.removeData("validator");
$editForm.removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse($editForm);
});
}
This inserts an editable form for the returned entity into a <div> on the page which looks like this. I have two fields which are required, but when I remove the values from those fields the "Required" validation does not fire. It only seems to occur when:
I delete the values.
Take the cursor away from the field.
Enter a new value.
Take the cursor away.
Then delete the new value.
How can I solve this so that the validation occurs when I delete the value the first time?
I found this question, which led me to an answer on this page.
(function ($) {
$.validator.unobtrusive.parseDynamicContent = function (selector) {
//use the normal unobstrusive.parse method
$.validator.unobtrusive.parse(selector);
//get the relevant form
var form = $(selector).first().closest('form');
//get the collections of unobstrusive validators, and jquery validators
//and compare the two
var unobtrusiveValidation = form.data('unobtrusiveValidation');
var validator = form.validate();
$.each(unobtrusiveValidation.options.rules, function (elname, elrules) {
if (validator.settings.rules[elname] == undefined) {
var args = {};
$.extend(args, elrules);
args.messages = unobtrusiveValidation.options.messages[elname];
//edit:use quoted strings for the name selector
$("[name='" + elname + "']").rules("add", args);
} else {
$.each(elrules, function (rulename, data) {
if (validator.settings.rules[elname][rulename] == undefined) {
var args = {};
args[rulename] = data;
args.messages = unobtrusiveValidation.options.messages[elname][rulename];
//edit:use quoted strings for the name selector
$("[name='" + elname + "']").rules("add", args);
}
});
}
});
}
})($);
Usage:
var html = "<input data-val='true' "+
"data-val-required='This field is required' " +
"name='inputFieldName' id='inputFieldId' type='text'/>";
$("form").append(html);
$.validator.unobtrusive.parseDynamicContent('form input:last');
I design a datalist on web page. And I want to fill this datalist using JQuery. Controller execute a query and get a list of facilities. Then pass this list to client side. This datalist can show all the facilities. When user click this textbox, the facilities will be listed in drop down list. But when user click more than once, there will be duplicates in datalist. That means, if you click twice, the result will be shown twice in datalist.
Here is code in MVC view
datalist:
<input type="text" list="facility" autocomplete="on" name="Facility" id="facilities" />
<datalist id="facility"></datalist>
JQuery Code:
$(document).ready(function () {
$('#facilities').click(function () {
//alert("Clicked");
var postData = $('#clientTxt').val();
$.ajax({
type: "POST",
url: '#Url.Action("FacilityCheck", "PCA")',
data: { clientTxt: postData },
success: function (result) {
//successful
for (var i = 0; i < result.facilities.length; i++) {
//alert(JSON.stringify(result.facilities[i]));
var option = "<option value ='" + result.facilities[i] + "'>" + result.facilities[i] + "</option>";
//I want to add an if judgement to avoid duplicates here
//Like contains() method in JAVA.
$('#facility').append(option);
}
},
error: function (result) {
alert('Oh no :(');
}
});
});
});
The duplicates image after clicking many times:
So please give me some advice. Thanks a lot!
It is because you are using the jQuery append() method and not replacing the HTML. Right now, you're just adding (appending) to it every time you iterate through your loop of result.facilities[i] instead of replacing the content.
Your best bet would be to add all of that source to a string and replace the $('#facility')'s innerHTML with the new content. You can use $('#facility').html(yourContentString); to do so.
Hope this helps!
For example...
success: function (result) {
var options = "";
//successful
for (var i = 0; i < result.facilities.length; i++) {
var option = "<option value ='" + result.facilities[i] + "'>" + result.facilities[i] + "</option>";
options = options + option;
} //end of loop
$('#facility').html(options); // replace the innerHTML of #facility with your new options string
},
Simply modify your success like this :
$('#facility').html('');
$('#facility').append(option);
Remove the items before appending them.
You can also use empty :
$('#facility').empty();
I want replace the select box inside of the div
<div class="models">
<select disabled="disable">
<option>Model Name</option>
</select>
</div>
I'm trying to target the div and load the select box like this
jQuery('.models select').change(function() {
var model = jQuery('.models option:selected').text();
I'm not getting any action on change though
http://jsfiddle.net/HNgKt/
Simple change: bind your change event handler to the container div (which should be present when this executes) and get the text value from that:
jQuery('.models').on('change','select',function() {
var model = jQuery(':selected',this).text();
var modelValue = jQuery(':selected',this).val();
});
Note: your fiddle and markup has it diabled, of course it would need to be enabled first, something like:
jQuery('.models>select').prop('disabled',false);
EDIT: Using your fiddle, I mashed around, commented out your load - as it does not work there and the cleanstring, not present, and this works:
jQuery('.brands').change(function () {
alert('here');
var brand = jQuery('.brands option:selected').text();
// brand = cleanString(brand);
//jQuery('.models').load('/pf-models #' + brand);
jQuery('.models>select').append('<option >She is a classic</option>').prop('disabled', false);
});
alert(jQuery('.models>select').prop('disabled'));
jQuery('.models').on('change', 'select', function () {
var model = jQuery(":selected", this).text();
alert(model);
model = cleanString(model);
jQuery('#show-models').load('/pf-urls #' + model);
});
updated fiddle: http://jsfiddle.net/HNgKt/6/
EDIT Further detailed example, still based on the valid markup assumptions coming back from the load on the first part which I have substituted for a html replace since we have not access to that part:
jQuery('.brands').change(function () {
var brand = jQuery('.brands option:selected').text();
$('.models').html('<select class="models"><option >' + brand + ' She is a classic</option><option>clunker</option></select>');
});
jQuery('.models').on('change', 'select', function () {
var model = jQuery(":selected", this).text();
alert('model:' + model);
});
Fiddle for that: http://jsfiddle.net/HNgKt/7/
Alerts the model if you choose a brand, then a model.
Try following steps,
on change of brands list make an ajax call and make sure in result you recieve the new list options or you can dynamically prepare the options list in jquery also.
And on success of call repopulate new list with the received data.
jQuery('.brands').change(function() {
var brand = jQuery('.brands option:selected').text();
brand = JSON.stringify(cleanString(brand));
$.ajax({
type: "GET", //GET or POST or PUT or DELETE verb
url: ajaxUrl, // Location of the service
data: brand , //Data sent to server
contentType: "", // content type sent to server
dataType: "json", //Expected data format from server
processdata: true, //True or False
success: function (data) {//On Successful service call
var $newList = $(".models select'").empty();
$newList.append(data);
},
error: function(){} // When Service call fails
});
});
Try the following:
/* using delegate version of .on */
jQuery(document).on('change', '.brands', function() {
var brand = jQuery('.brands option:selected').text();
brand = cleanString(brand);
jQuery('.models').load('/pf-models #' + brand);
});
jQuery(document).on('change', '.models select', function() {
var model = jQuery('.models option:selected').text();
model = cleanString(model);
jQuery('#show-models').load('/pf-urls #' + model);
});
For dealing with "dynamic" elements, you want to use delegate to assign action. This basically reserves a method to be assigned to all elements who match the description.
See also:
http://api.jquery.com/delegate/
http://api.jquery.com/on/#direct-and-delegated-events
Hi I am Working On a Web Form..
I Have A combo Box for holding all The Units.
I Have Taken All The units from the Database Using JSON,now i need to Bind All these Units To the drop down List
How can I Do this...?
function getUnitFamily(pack_detl_ID,select) {
//***********************************//
PageMethods.getUnitFamily(pack_detl_ID,
function(result) {
if (result != null) {
custinfo = eval(result);
if (custinfo != null) {
$('#<%=drpUnit.ClientID%> option').remove();
var objSub = document.getElementById('<%=drpUnit.ClientID%>');
$.each(custinfo, function(i, item) {
listOpt = document.createElement("option");
listOpt.value = item[0];
listOpt.text = item[1];
objSub.add(listOpt);
});
alert(select);
document.getElementById('<%= drpUnit.ClientID %>').value = select;
}
}
}, pageMethodError);
With An example can any one explain
A combobox sounds like you are using an ASP.NET control. Of course, you can bind your items to that control in the code behind. If you are doing some AJAX stuff and have a dropdown ( element>) in your page which you want to populate at client side, you might want to take a look at what jQuery has to offer. For example use the AJAX api to retrieve your data and push that data into your dropdown like so:
var options = $("#options");
$.each(result, function() {
options.append($("<option />").val("sometext").text("sometext"));
});
In the past I have used a plugin when working with dropdowns.
http://www.texotela.co.uk/code/jquery/select
Request the JSON data:
//Get the JSON Data
$.getJSON(url, function(json) {
PopulateDropDownFromJson(json, "#element");
});
and then just pass the JSON into a function that uses the plugin above
function PopulateDropDownFromJson(json, element){
$.each(json, function() {
$(element).addOption(this[valueText], this[displayText], false);
});
}