Facing error while populating dynamic dropdown - javascript

m trying to add some <option> in existing <select> dynamically, but facing error "An attempt was made to reference a Node in a context where it does not exist." i have tried to resolve it failed...
HTML code:
<label class="control-label" for="selectError">Ayat/Hadith no.:</label>
<div class="controls">
<select id="ayat_selector" disabled >
<option id="all_ayat" selected>All </option>
</select>
</div>
javascript :
var selectHTML = "<option id='200'>Select Surah</option>";
alert("ajax going ");
$.ajax({
url: "../Surah_CRUD/Load_Surahs",
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
data: '',
success: function (result) {
var mera_obj = result.key;
for (var i = 0; i < 5; i++) {
selectHTML += "<option id='" + i + "'>" + mera_obj[i].Surah_Description + "</option>";
}
var qa = document.getElementById('ayat_selector');
qa.appendChild(selectHTML);
alert("done"+qa.className);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("3> " + thrownError);
},
});

The problem is that you trying to select an element by id that isn't exist.
try to change this:
var qa = document.getElementById('surah_selector');
to this:
var qa = document.getElementById('ayat_selector');
UPDATE
try to change this
var qa = document.getElementById('ayat_selector');
qa.appendChild(selectHTML);
alert("done"+qa.className);
With this code in jQuery:
$('#ayat_selector').append(selectHTML);
alert('done');

Related

ASP.NET MVC - After HTML append with Jquery the DropDownList value comes as undefined

I have two dropdownlist and when I change the value of the first one with refreshes the value of the second one with the following code:
function FillBooks(val) {
$("#ddl_dep").attr("class", "form-group");
$("#Help1").css("visibility", "hidden");
var CategoryId = val;
//console.log(CategoryId);
console.log(CategoryId)
$("#DDL_TIPO").empty();
$.ajax({
url: '#Url.Action("UpdateTipo", "Tickets")',
type: "POST",
dataType: "JSON",
data: { value: CategoryId },
success: function (data) {
var markup = "<option value='0'>Selecione um Tipo</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].value + ">" + data[x].Text + "</option>";
}
$("#DDL_TIPO").html(markup).show();
}
});
}
P.S - The data comes from the controller which is not relevant for the exemple that I am showing.
After this when I try to get the value of the Second dropdownlist it comes as undefined.
I tested before this jquery code and it gives me the value of the dropdownlist, it just doesn't give when I get this function to work on it.
Try this:
<script>
function FillBooks(val)
{
$("#ddl_dep").attr("class", "form-group");
$("#Help1").css("visibility", "hidden");
var CategoryId = val;
//console.log(CategoryId);
console.log(CategoryId)
$.ajax
({
url: '#Url.Action("UpdateTipo", "Tickets")',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: { value: CategoryId },
success: function(result)
{
$("#DDL_TIPO").html("");
$.each($.parseJSON(result), function(i, tipo)
{
$("#DDL_TIPO").append($('<option</option>').val(tipo.Value).html(tipo.Text))
})
},
error: function()
{
alert("Whooaaa! Something went wrong..")
},
});
}
</script>

Dynamic Creation of Div inside an array and Appending data to it

I am fetching result from database and i want too append it to dynamically created div.
for (j = 0; j <= 2; j++)
{
selected = $(".content" + (j + 1));
ajax1(arr[j]);
}
function ajax1(pref) {
$.ajax({
async: false,
url: "../handlers/guestpreference.ashx",
data: { "pref": pref },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: guestsuccess,
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
alert(thrownError);
}
});
}
function guestsuccess(resultset)
{
$.each(resultset, function (i, data) {
$(selected).append('<div class="blogpost" >');
$(".blogpost").append("<div class='blogposth'>");
$(".blogpost").append("<div class='blogpostf'>");
$(".blogposth").append('<font style="font-size:30px; color:blue;padding-left:10px;margin-top:10px;">' + data.Name + '</font>');
$(".blogpostf").append('<font style="font-size:30px; text-align:centre;">' + data.Title + '</font><br>');
$(".blogpostf").append('<font style="text-align:left;float:left;">' + data.Post + '</font><br>');
$(".blogpostf").append('<hr>');
var likes = data.Likes;
if (likes > 0)
$(".blogpostf").append('<font style="font-size:10px;text-align:left;float:left;">' + likes + ' people like it.</font><br>');
else
$(".blogpostf").append('<font style="font-size:10px;text-align:left;float:left;">Nobody like it.</font><br>');
$(selected).append("<br>");
});
}
Here selected holds the class where i have to append .blogpost.
this code is working fine if i have only 1 row of result but in case of multiple result the results are being appended to previously created div.
Since i have CSS for .blogpost .blogposth .blogpostf how can i modify my code so that i can append value uniquely.
create object of div which you append to "selected" . check demo on FIDDLE
$blogpost = $('<div class="blogpost" ></div>');
$blogpost.appendTo('#app');
$blogposth = $("<div class='blogposth'><div>");
$blogpost.append($blogposth);
$blogpostf = $("<div class='blogpostf'><div>");
$blogpost.append($blogpostf);
$blogposth.append('<font style="font-size:30px; color:blue;padding-left:10px;margin-top:10px;">Name</font>');
$blogpostf.append('<font style="font-size:30px; text-align:centre;">Title</font><br>');
$blogpostf.append('<font style="text-align:left;float:left;">POST</font><br>');
$blogpostf.append('<hr>');

How to extract and add the JSON data received as a AJAX response to the HTML select drop down using jQuery?

I've following HTML code :
<select id="student" name="student" class="form-control"></select>
The jQuery-AJAX function I've written for adding the options to the above HTML select control is as follows :
var mod_url = $('#mod_url').val();
$.ajax({
url : mod_url,
cache: false,
dataType: "json",
type: "GET",
async: false,
data: {
'request_type':'ajax',
},
success: function(result, success) {
$('#student').html(result);
},
error: function() {
alert("Error is occured");
}
});
From PHP file I've received a big array encoded into JSON format(i.e. the result variable from jQuery-AJAX function). For your reference I'm showing below only the first four records from that array. In HTML select control actually I want to show all the elements from this array.
[{"id":2,"stud_name":"John Dpalma","stud_address1":"277 Eisenhower Pkwy","stud_address2":"","stud_city":"Edison","stud_state":"New Jersey","stud_country":"USA","stud_zipcode":"07039","stud_email":"abc#gmail.com","created_at":1409739580,"updated_at":1410253832},
{"id":3,"stud_name":"Anthony Gonsalvis","stud_address1":"520 Division St","stud_address2":"","stud_city":"Piscataway","stud_state":"NJ","stud_country":"USA","stud_zipcode":"07201","stud_email":"pqr#gmail.com","created_at":1409740530,"updated_at":1410255590},
{"id":4,"stud_name":"James Bond","stud_address1":"6 Harrison Street, 6th Floor","stud_address2":"Ste-2324","stud_city":"New York","stud_state":"NY","stud_country":"USA","stud_zipcode":"10013","stud_email":"xyz#gmail.com","created_at":1409757637,"updated_at":1412263107},
{"id":9,"stud_name":"Mary Jane","stud_address1":"2112 Zeno Place","stud_address2":"CA","stud_city":"Venice","stud_state":"CA","stud_country":"","stud_zipcode":"90291","stud_email":"utp#gmail.com","created_at":1409908569,"updated_at":1410254282}]
In HTML select control I want to set the values in following manner(consider first two records from above array)
<select id="student" name="student" class="form-control">
<option value="">Select Store</option>
<option value="2">John Dpalma, 277 Eisenhower Pkwy, Edison</option>
<option value="3">Anthony Gonsalvis, 520 Division St, Piscataway</option>
</select>
You might have observed from the expected output above that I want to set the value of option as a id from array and the text that I want to display is comprising of stud_name+stud_address1+stud_city
How should I manage this for all the elements from the JSON data in my code?
Also please guide me in showing the loading option into the select control until the response from PHP comes.
Please provide me some help.
success: function(result, success) {
var $select = $('#student');
$.each(result, function (i, option) {
var txt = [option.stud_name, option.stud_address1, option.stud_city];
if (option.stud_address2)
txt.splice(2, 0, option.stud_address2);
$('<option>', {
value: option.id,
text: txt.join(', ')
}).appendTo($select);
});
},
or with $.map (slightly more efficient):
success: function(result, success) {
var options = $.map(result, function (option) {
var txt = [option.stud_name, option.stud_address1, option.stud_city];
if (option.stud_address2)
txt.splice(2, 0, option.stud_address2);
return $('<option>', {
value: option.id,
text: txt.join(', ')
});
});
$('#student').append(options);
},
In PHP file echo the following in a loop:
echo '<option value="">'.$stud_name.', '.$stud_address1.', '.$stud_address2.', '.$stud_city.', '.$stud_state.', '.$stud_country.'</option>';
Then attach this result to the select dropdown with jQuery through the ajax success.
Here is my solution. This checks address 2 and adds it to the options accordingly.
JS code:
for(var i=0;i<result.length;i++){
if(result[i]["stud_address2"]==""){
$('#student').append('<option value="' + result[i]["id"] + '">' + result[i]["stud_name"] + ', ' + result[i]["stud_address1"]+ ', ' +result[i]["stud_city"] +'</option>');}
else{
$('#student').append('<option value="' + result[i]["id"] + '">' + result[i]["stud_name"] + ', ' + result[i]["stud_address1"]+ ', '+ result[i]["stud_address2"]+ ', ' +result[i]["stud_city"] +'</option>');
}
}
Here is a working DEMO
This is exactly what you need!
$(document).ready(function(){
var mod_url = $('#mod_url').val();
$.ajax({
url : mod_url,
cache: false,
dataType: "json",
type: "GET",
async: false,
data: {
'request_type':'ajax',
},
success: function(result, success) {
$.each(result,function(index,item){
$label = item.stud_name +', ' + item.stud_address1 +', ' + item.stud_city;
$('#student').append('<option value="'+ item.id +'">'+ $label +'</option>');
});
},
error: function() {
alert("Error is occured");
}
});
});
It's a matter of iterating over the JSON you receive from the server, creating option tags for each record, then appending them to the select element:
var response = [{"id":2,"stud_name":"John Dpalma" ... }]
$.each(response, function (index, record) {
if (!record.stud_address2){
var stud_address2 = "";
} else {
var stud_address2 = record.stud_address2;
}
$('<option>', {
value: record.id,
text: record.stud_name + ", " + record.stud_address1 + ", " + record.stud_city + ", " + stud_address2
}).appendTo("#student");
});
Demo
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script>
function __highlight(s, t) {
var matcher = new RegExp("(" + $.ui.autocomplete.escapeRegex(t) + ")", "ig");
return s.replace(matcher, "<strong>$1</strong>");
}
$(document).ready(
function() {
$("#suggest").autocomplete(
{
source : function(request, response)
{
$.ajax({
url : 'URL',
dataType : 'json',
data : { term : request.term },
success : function(data)
{
//alert(data[0].title);
response($.map(data, function(item) {
//alert(item);
return {
label : __highlight(item.title, request.term),
value : item.title
};
}));
}
});
},
minLength : 3,
select : function(event, ui)
{
if(ui.item){
$(event.target).val(ui.item.value);
}
//submit the form
$(event.target.form).submit();
}
}).keydown(function(e) {
if (e.keyCode === 13)
{
$("#search_form").trigger('submit');
}
}).data("autocomplete")._renderItem = function(ul, item)
{
return $("<li></li>").data("item.autocomplete", item).append(
$("<a></a>").html(item.label)).appendTo(ul);
};
});
</script>

Codeigniter Jquery Ajax: How to loop returned data as html

Im new to JQuery AJAX thing, this is my script:
$(document).ready(function() {
$("#city").change(function() {
var city_id = $("#city").val();
if (city_id != '') {
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id,
success: function(block_list) {
// WHAT TO PUT HERE ?
},
});
}
});
If i put console.log(block_list) it returns the right data with JSON type:
[{"id":"1601","id_city":"16","block":"A"},
{"id":"1602","id_city":"16","block":"B"}]
What is the correct way to loop the returned data? I did this to see what the loop returned:
$.each(block_list, function() {
$.each(this, function(index, val) {
console.log(index + '=' + val);
});
});
But it was totally messed up :(, if the looped data is correct I also want to put the id as a value and block name as a text for my <option> tag how to do that? thank you.
UPDATE
Sorry, I have try both answer and its not working, I try to change my code to this:
$("#city").change(function(){
var city_id = $("#city").val();
$.get("<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id, function(data) {
$.each(data, function(id, val) {
console.log(val.id);
});
});
});
it returns :
**UNDEFINED**
I also try to change it into val[id] or val['id'] still not working, help :(
$.each(block_list, function(id, block){
console.log('<option value="' + block['id'] + '">' + block['block'] + '</option>')
});
The output would be:
<option value="1601">A</option>
<option value="1602">B</option>
try something like:
success: function(data, textStatus, jqXHR) {
if (typeof(data)=='object'){
for (var i = 0; i < data.length; i++) {
console.log(data[i].id + ':' + data[i].id_city);
}
}
}
if ur json output is in this format
[{"id":"1601","id_city":"16","block":"A"},
{"id":"1602","id_city":"16","block":"B"}]
then
var city_id = $("#city").val();
if (city_id != '') {
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id,
success: function(data) {
$.each(data, function(index)
{
console.log(data[index]['id']);
$('#'+ddname+'')
.append($("<option></option>")
.text(data[index]['id']+"-"+data[index]['block']));
});
},
});
}

JQuery Illegal invocation when using variable to select

My javascript dont seem to like the var divTag = '#' + ratinglistid + " > select[name=SelectedValue] > option:selected";
I couldn't find the answer searching.. Sorry for the messed up formatting, couldn't get it to go away.
Script:
<script>
function doSubmit(form, myRating, ratinglistid){
var divTag = '#' + ratinglistid + " > select[name=SelectedValue] > option:selected";
var ratingValue = $(divTag);
$.ajax({
type: "GET",
url: "/RatingLists/Done",
data: ({
myrating: ratingValue,
myRatingListId: ratinglistid
}),
contentType: "application/json; charset=utf-8",
dataType: "json"
});
}
</script>
Html I want to get value from:
<div id='2'>
<input type="hidden" name="RatingListId" value="2"/>
<select id="SelectedValue" name="SelectedValue" onchange="doSubmit($(this).parents('form'),2);"><option value="1">Inget intresse, tas bort</option>
<option value="2">Svagt intresse, sparas</option>
<option selected="selected" value="3">Intresserad-ingen kontakt än</option>
<option value="4">4-Intreserad-vill ha kontakt</option>
<option value="5">5-Vill byta!</option>
<option value="100">6-Avvaktar värdar</option>
</select>
</div
You are trying to pass a jQuery object to be serialized in the ajax function which causes the Illegal invocation error, use the .val() to get the value of the form element.
data: ({
myrating: ratingValue.val(),
myRatingListId: ratinglistid
}),
It could not evaluate inside get call so I had to do it like this:
var divTag = '#' + ratinglistid + " > select[name=SelectedValue] > option:selected";
var ratingValue = $(divTag).val();
$.ajax({
type: "GET",
url: "/RatingLists/Done",
data: ({
myrating: ratingValue,
RatingListId: ratinglistid
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess(ratinglistid),
error: function () {
var id = ratinglistid;
$('#' + id + "tbody td").hover(function () {
$(this).parents('tr').addClass('highlight');
}, function () {
$(this).parents('tr').removeClass('highlight');
});
}
});

Categories

Resources