I'm trying to dynamically populate a dropdown when a user is trying to add a new record in a detail jqGrid. Here's what I have so far. It's pulling in the data fine but it just won't set the value to the dropdown. Any help would be greatly appreciated.
beforeShowForm: function(formid) {
var sr = $("#list").jqGrid('selrow');
if (sr) {
// get data from master
var UserID = $("#list").getGridParam('selrow');
var roles = $.ajax({ type: "POST",
url: '<%= ResolveUrl("~/Admin/GetRoles/") %>' + UserID,
dataType: "json",
async: false,
success: function(data) {
}
}).responseText;
// set the field in detail with the value of mnaster
$("#UserID", formid).val(UserID);
// try and populate dropdown
$('#detail').setColProp('Description', { editoptions: { value: roles} });
} else {
// close the add dialog
alert("no row is selected");
}
}
In your first question I explained you how to use dataUrl to generate the contain of the dropdown list dynamically. If you use form editing to modify the grid data you can use beforeInitData instead of beforeShowForm to modify the dataUrl to '<%= ResolveUrl("~/Admin/GetRoles/") %>' + $("#list").jqGrid('selrow') before the form will be filled. In the way you can simplify your code, make the ajax request asynchronous and the question with setting the values to the dropdown control will be solved automatically.
Related
I have an AJAX call, as below. This posts data from a form to JSON. I then take the values and put them back into the div called response so as to not refresh the page.
$("form").on("submit", function(event) { $targetElement = $('#response'); event.preventDefault(); // Perform ajax call // console.log("Sending data: " + $(this).serialize()); $.ajax({
url: '/OAH',
data: $('form').serialize(),
datatype: 'json',
type: 'POST',
success: function(response) {
// Success handler
var TableTing = response["table"];
$("#RearPillarNS").empty();
$("#RearPillarNS").append("Rear Pillar Assembly Part No: " + response["RearPillarNS"]);
$("#TableThing").empty();
$("#TableThing").append(TableTing);
for (key in response) {
if (key == 'myList') {
// Add the new elements from 'myList' to the form
$targetElement.empty();
select = $('<select id="mySelect" class="form-control" onchange="myFunction()"></select>');
response[key].forEach(function(item) {
select.append($('<option>').text(item));
});
$targetElement.html(select);
} else {
// Update existing controls to those of the response.
$(':input[name="' + key + '"]').val(response[key]);
}
}
return myFunction()
// End handler
}
// Proceed with normal submission or new ajax call }) });
This generates a new <select id="mySelect">
I need to now extract the value that has been selected by the newly generated select and amend my JSON array. Again, without refreshing the page.
I was thinking of doing this via a button called CreateDrawing
The JS function for this would be:
> $(function() {
$('a#CreateDrawing').bind('click', function() {
$.getJSON('/Printit',
function(data) {
//do nothing
});
return false;
});
});
This is because I will be using the data from the JSON array in a Python function, via Flask that'll be using the value from the select.
My question is, what is the best way (if someone could do a working example too that'd help me A LOT) to get the value from the select as above, and bring into Python Flask/JSON.
Am using array helpers if data exists i want to select the value...here product category master id is a foreign key in product master table.
A modal gets called on edit button and it uses the same modal as create button
but the fields are populated using hidden input field.
I want to select the already set value from the database.
$("#productmaster-product_category_master_id").val(data.product_category_master_id);
The above code is not working.
<?= $product_form->field($form_product_model, 'product_category_master_id')->dropDownList(
ArrayHelper::map(ProductCategoryMaster::find()->all(),'id','category'),['prompt'=>'','class'=>'form-control select2','style' => 'width:100%;height:80% !important']
);?>
function editProduct(id) {
console.log(id);
$.ajax
({
type:"GET",
url: "<?= Yii::getAlias('#web')?>/product-category-master/product?id="+id,
cache: false,
dataType:"json",
success: function(data)
{
console.log(data);
$('#sourceproduct').click();
$("#newid").val(data.id);
$("#productmaster-product_category_master_id").val(data.product_category_master_id);
//document.getElementById("editbutton").showModal();
//var myArr = JSON.parse(data);
return false;
}
});
}
Found the solution i just had to put
$('#productmaster-product_category_master_id').val(data.product_category_master_id).trigger('change');
instead of
$('#productmaster-product_category_master_id').val(data.product_category_master_id);
I have a problem I have bee struggling over all morning so I felt it was time to get some help! I have a javascript function which gets the value entered by a user into an autocomplete box, uses AJAX to send that value to a php script which queries the database and then populates the following box with the possible options. The problem is this all works fine when I hard-code in the selected option as so:
var selected="Ed Clancy";
but not when it pulls it from the box, as so:
var selected = this.getValue();
I have tried debugging this using an alert box and both boxes come up with the same string in them so I am completely puzzled! Any ideas? Full code below:
$(riderSelected).on('selectionchange', function(event){
var selected = this.getValue();
//var selected="Ed Clancy";
alert(selected);
$('#nap4').removeAttr('disabled');
$('#nap4').empty();
$('#nap4').append($("<option>-select-</option>"));
$.ajax({
type: "GET",
url: 'getbiketype.php',
data: { name: selected },
success: function(data) {
console.log(data);
$('#nap4').append(data);
}
});
});
Based on magicsuggest documentation - http://nicolasbize.com/magicsuggest/doc.html , you probably could do this
var selected = this.getValue()[0];
IF you do not allow multiple selection
Change your code as I have written below for you .
Code
$(riderSelected).on('change', function (event) {
var selected = this.value;
alert(selected);
$('#nap4').removeAttr('disabled');
$('#nap4').empty();
$('#nap4').append($("<option>-select-</option>"));
$.ajax({
type: "GET",
url: 'getbiketype.php',
data: {name: selected},
success: function (data) {
console.log(data);
$('#nap4').append(data);
}
});
});
please pardon my noobness, but I'm new to working with Telerik controls. I have seen many examples of this but they haven't been able to solve my problem. I have a Kendo UI multiselect widget which contains some items and a button which, on clicking, would fill the multiselect widget partially with some items. These items are obtained as JSON from a controller method (ASP.NET MVC). So, the button click actually fires an ajax request and on successfully firing up, it calls a javascript function to fill the multiselect widget up. As of now, the ajax gets fired successfully and the data that I want is coming back successfully, just that the multiselect is not displaying the values.
My javascript/AJAX methods:
function addItems(items) {
var values = new Array();
for (var i = 0; i < items.length; i++) {
values[i] = items[i].Item.ID;
// gets values back correctly
console.log(values[i]);
}
// print values
$('#items').data("kendoMultiSelect").value(['"' + values + '"']);
};
// success
$(document).on("click", "#add-items-button", function () {
var myUrl = $('#MyURL').val();
$.ajax({
url: myUrl, // get URL from view
method: 'GET',
dataType: 'json',
success: function (data) {
addItems(data);
},
error: function (xhr, status, error) {
console.log(error);
}
});
});
My multiselect widget is a partial view so:
#using Kendo.Mvc.UI
#(Html.Kendo().MultiSelect()
.Name("items") // Name of the widget should be the same as the name of the property
.DataValueField("ID")
.DataTextField("Name")
.BindTo((System.Collections.IEnumerable)ViewData["items"])
.Placeholder("Add Items")
)
Am I missing something very obvious? Am I writing the data back in an incorrect format to the multiselect widget? Please help.
You need to add items to the data source of the multiselect.
$('#items').data("kendoMultiSelect").dataSource.add( { ID: 1, Name: "Name" });
Here is a live demo: http://jsbin.com/eseYidIt/1/edit
It might help to others
var multiSelect = $('#mymultiSelect').data('kendoMultiSelect');
var val = multiSelect.value().slice();
$.merge(val, "anil.singh#hotmail.com");
multiSelect.value(val);
multiSelect.refresh();
OR
$('#mymultiSelect').data("kendoMultiSelect").dataSource.add({Id:"EMP100XYZ",
EmailId: "ayz#gmail.com" });
I'm hoping someone can help, I'm a relative newbie to javascript and have the following issue. I have a select box with id "mySelect"
that is populated with the following code -
$(document).ready(function(artists){
$.ajax({
type: "GET",
url: "bookinglist.xml",
dataType: "xml",
success: function(artists_list) {
var select = $('#mySelect');
var artistsArr = [];
$(artists_list).find('vw_ADM_BookingListNull[strArtistName]').each(function(){
var artists = $(this).attr('strArtistName');
if ($.inArray(artists, artistsArr) == -1) {
select.append('<option value="'+artists+'">'+artists+'</option>');
artistsArr.push(artists);
}
});
select.children(":first").text("please make a selection").attr("selected",true);
}
});
});
I need to use the selected value as a variable to insert into another piece of code. How do I make a variable from this?
The variable will be used in place of
'vw_ADM_BookingListNull[strArtistName="James Zabiela"]'
in the following code which populates a table from an xml list.
$(document).ready(function(unavailable){
$.ajax({
type: "GET",
url: "bookinglist.xml",
dataType: "xml",
success:(function(unavail){
$(unavail).find('vw_ADM_BookingListNull[strArtistName="James Zabiela"]').each(function() {
var venue = $(this).attr('strVenueName');
var artist = $(this).attr('strArtistName');
var booking_date = $(this).attr('dteEventDate').substr(0,10); //subtr strips date down
if(!(booking_date >= $nowformat && booking_date <= $advformat)){
$('<tr style="display:none;"></tr>')
}
else {
$('<tr></tr>').html('<th>'+booking_date+'</th><td>'+artist+'</td>').appendTo('#unavail');
}
});
})
});
});
I need to handle the possible event that a value has not been selected and so the value of the select box will be "please make a selection", which is set as the default value.
So I guess I need to wrap some kind of if statement around the code that creates the table, so as to not display anything if nothing has yet been selected.
Any help would be massively appreciated as deadlines are looming.
Thanks again.
You appear to be using jQuery, so from the jQuery Documentation
var dropdownValue = $('#mySelect').val();