Dynamically add dropdownlist to table by using append() - javascript

Can i add dropdownlist to table by using jquery append.
Eg.
$(#table).append("<tr><td>#Html.DropDownList('TP',new SelectList(#Model.RefList, 'Value', 'Text',#Model.Ref))</td></tr>");
I dont known how to change this "#Html.Dropdownlist" to valid string.

you cannot add a server control with javascript, you can add an HTML select and load the options using ajax
$('#table').append('<select id="mySelect"></select>');
Example:
$.ajax({
url: "myServiceURL"
}).done(function(myOptions) {
$.each(myOptions, function(key, value) {
$('#mySelect')
.append($("<option></option>")
.attr("value",key)
.text(value));
});
});

This Code will append Select menu to the last row of the table.
var select_list = '<select id="list">';
//you can add more options by repeating the next line & change text,value
select_list += '<option value="changevalue">change text</option>';
select_list += '</select>';
$("#table").append("<tr><td>"+select_list+"</td></tr>");

Related

Dynamically build AJAX dropdown resets to original state when trying to save with django form?

I my form I have few dropdowns chained between them with AJAX.
This is how I a populating them
function getleaseterm() {
//get a reference to the select element
$select = $('#id_leaseterm');
//request the JSON data and parse into the select element
var l_id = ($("select[name='lease'] option:selected").attr('value'));
//var l_id = 13;
l_url = "/api/get_leaseterm/"+l_id+"/";
$.ajax({
url: l_url,
dataType:'JSON',
success:function(data1){
//clear the current content of the select
$select.empty();
$select.append('<option value="-1">Select term </option>');
//iterate over the data and append a select option
$.each(data1, function(key, val){
$select.append('<option value="' + val.id + '">' + val.as_char + '</option>');
})
},
});
}
And this is the control
<select class="select" id="id_leaseterm" name="leaseterm">
<option value="-1" selected="selected">-----</option>
</select>
It all works , I am changing values in my dropdowns and options of other dropdowns are updated.So I can select the relevant value.
The problem is when I Save the for - the form gets not the value that I have put there but the default value that was there before any manipulation of Ajax have been done.
Also when I do view source I see in the code is default value and not what was selected from what I have build with AJAX.(Even that on the screen I do see the correct values in the select options...)
My backend is Django .
My Django form formatted in following way.
class MassPaymentForm(forms.ModelForm):
leaseterm = forms.ModelChoiceField(queryset=LeaseTerm.objects.none()) # Need to populate this using jquery
lease= forms.ModelChoiceField(queryset=Lease.objects.none()) # Need to populate this using jquery
class Meta:
model = LeasePayment
fields = ['lease', 'leaseterm', 'payment_type', 'is_deposit', 'amount', 'method', 'payment_date', 'description']
What could be the problem ? And any idea how to solve it?
I have figured out what was the problem
it is in my form file
If I keep the lease and leaseterm fields just in Meta class that it doesn't reset those fields on submit any more . And all my logic finally works as designed.
class MassPaymentForm(forms.ModelForm):
class Meta:
model = LeasePayment
fields = ['lease', 'leaseterm', 'payment_type', 'is_deposit', 'amount', 'method', 'payment_date', 'description']

How to display data in select box option using jquery

I want to display data in select box option from ajax response.
here is my view file
<select class="form-control" name="vendor" id="vendor_list" required style="width: 159px;">
<option value="">Vendor 1</option>
</select>
Here is my ajax success function
success: function(data) {
$.each(data, function(i, value) {
console.log(value);
$('#vendor_list').append('<option value="'+ value.id+'">'+ value.vendor_name +'</option>');
console.log(value);
});
}
here is my ajax response json data
[{"vendor_name":"scscss"},{"vendor_name":"xzcdsfdx"}]
How to display value in select box.
giv me suggestion.thanks
I think the problem is with
$('#vendor_list').append('<option value="'+ value.id+'">'+ value.vendor_name +'</option>');
It will be much better if you create a option string & append it after entire data has been iterated
Since it is not possible to replicate the ajax , so I have directly use the ajax response
You can put the entire code inside success block , but you will not need var x because data will play role of var x=[...] in your case
var x = [{"vendor_name":"scscss"},{"vendor_name":"xzcdsfdx"}]
var _options =""
$.each(x, function(i, value) {
_options +=('<option value="'+ value.id+'">'+ value.vendor_name +'</option>');
});
$('#vendor_list').append(_options);
Check this jsFiddle

Laravel - Return with input from a dynamic select menu after validation error

I have a couple of select menus that are populated dynamically by selecting an option from another menu.
because these are populated dynamically, Laravel's withInput function does not return the data that was selected if the form does not pass validation.
Is there a way to return Input from dynamically created field data?
Here is my java script that builds the select menu
$('.admin-select').change(function() {
$.getJSON("/locations/getlocationslist/"+$(this).val(), function(data) {
var location = $('#location');
location.empty();
$.each(data, function(index, element) {
location.append("<option value='"+ element.id +"'>" + element.name + "</option>");
});
$.one(location.prepend("<option>- Select -</option>"));
});
});
This is the function that gets the data for the menu:
public function getlocationslist($id)
{
$company = Company::find($id);
$locations = $company->locations();
return Response::make($locations->get(['id','name']));
}
In my users controllers store function I check validation:
$this->userNewForm->validate(Input::all());
Then the error handler:
App::error(function(Laracasts\Validation\FormValidationException $exception, $code)
{
return Redirect::back()->withInput()->withErrors($exception->getErrors());
});
As the location select menu is dynamically created via AJAX the option isn't there for Laravel to preselect when it reloads the page.
However you can check if an option has been selected on page load for .admin-select and if it has then do the ajax call to refill the dynamic drop down and select the relevant option.

Auto populate select box using Javascript and jQuery

I have a select box:
<select id="translationOptions" name="translationOptions"></select>
And I have a js array
var translationOptions = ["Egyptian Hieroglyphs", "Al Bhed (Final Fantasy X)", "Futurama"];
How would I auto populate the select box based on the var translationOptions?
$.each(translationOptions, function(key, value) {
$('#mySelect')
.append($("<option></option>")
.attr("value",key)
.text(value));
});
What is the best way to add options to a select from an array with jQuery?
$.each(translationOptions, function(index, value) {
$('#translationOptions').append($("<option />").val(index).text(value));
});
This uses text for display and index in the array for value.
You can create options dynamically and append to select box in this way as well.
jQuery.each(translationOptions, function(key, value) {
jQuery('<option/>', {
'value': key,
'text' : value
}).appendTo('#translationOptions');

Jquery append html element to div after for loop, strange behaviour

Here is the code:
$('#date').append(
'<select id="date">'+
'<option value="0">- - SELECT - -</option>');
for(var i in data){
$('#date').append(
'<option value="">'+data[i]['date_time']+'</option>');
});
$('#date').append('</select>');
</select> is always added above for loop. If i replace it with just work select for example, it is appended at the end, where it should be. Why is this happening and how can i fix it?
I believe that jQuery will generate the DOM like this:
<div id="date">
<select id="date">
<option value="0">- - SELECT - -</option>
</select>
<option value="">foo</option>
<option value="">bar</option>
etc...
</div>
Since it is automatically closing the <select> after the first .append(). What you are doing afterwards is appending the options to the <div id="#date"/> rather than the <select> that was appended. I don't think the final closing </select> will actually do anything either.
If you really want to use append the following JavaScript will add the options to the correct node:
// dummy data object for example
var data = new Array(new Array(), new Array());
data[0].date_time = 2011;
data[1].date_time = 2012;
var options = new Array();
$.each(data, function(index, option) {
options.push('<option value="' + index + '">'+ option.date_time +'</option>');
});
$('<select id="date"/>').append(options.join('')).appendTo('#date');
Assuming the existing HTML:
<div id="date"></div>
However this does incur an overhead since appending is occurring twice. The faster approach is to build up the options markup as already answered by ShankarSangoli
It is not the right way to create html dynamically. You should create the complete markup all at once by putting it into an array and then provide it to jQuery. Try this
var html = [];
html.push('<select id="date">');
html.push('<option value="0">- - SELECT - -</option>');
for(var i in data){
html.push('<option value="">'+data[i]['date_time']+'</option>');
}
html.push('</select>');
//This selector should be some container like dateContainer
//because you have already give date as id to the above select element
$('#dateContainer').html(html.join(''));
$('#date').append($("<select/>", { name: "name"+i})
.find('select')
.append($("<option/>", { value: "abc"+i}).text('cell'))
.append($("<option/>", { value: "abc"+i}).text('home'))
.append($("<option/>", { value: "abc"+i}).text('work'));
all options should wrap inside select
I imagine the base HTML you have looks something like this:
<div id="date"></div>
then after the first $('#date').append('<select id="date">... in your code, you will have this:
<div id="date"><select id="date">...</div>
which is 2 elements with the same ID attribute.
The ID attribute is like the highlanders, there must only be one of them (in each page).
The seccond $('#date').append... works unexpectedly, and the 3rd one, also unexpectedly, doesn't work. Because you can't predict to which #date they are referring.
Also, as the other answers say, it will be better if you build it to do only 1 append, because calling the selectors so many times (especially inside the loop) it's a performance hit.
If you want to do it in your way - create, for example, string variable with html code in it and than append it.
data = [1, 2, 3];
var html = '<select id="date">'+
'<option value="0">- - SELECT - -</option>';
for(var i in data){
html += '<option value="">'+data[i]+'</option>';
}
$('#date').append(html)
or look here
What is the best way to add options to a select from an array with jQuery?
ps: the first append tries to create a valid DOM structure inside of document, closing select tag automatically. that is why the second one will not insert options into the created select.
another possible way, based on the link above, is
var sel = $('<select id="date">');
$.each(data, function(key, value) {
sel.append($('<option>').text(key['date_time']));
});
$('#date').append(sel);

Categories