How to add data asp:dropdownlist item on javascript? - javascript

I have ajax function on aspx page.
function fav() {
var p = "3";
var e = document.getElementById('<%= ddlCountry.ClientID %>');
var j = e.options[e.selectedIndex].text;
//var aralik = p[1] + p[2];
$.ajax({
type: "POST",
url: "STry.aspx/Fill",
data: "{'Param': '" + p + "','Param2': '" + j + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (xhr, status, error) {
//alert the error if needed
},
success: function (msg) {
var data = msg.d;
if (data.indexOf(',') < 0)
{
document.getElementById('<%= ddlCity.ClientID %>').options.add(data);
}
else
{
data.split(",").forEach(function (item) {
var opt = document.createElement(item);
document.getElementById('<%= ddlCity.ClientID %>').options.add(opt);
});
}
}
});
}
the data return var data = msg.d; so, my return data is data. data type like this, if one more than;
text1,text2,text3,text4
and i want to split this value and add dropdownlist that is ddlCity
this part is my try:
var data = msg.d;
if (data.indexOf(',') < 0)
{
document.getElementById('<%= ddlCity.ClientID %>').options.add(data);
}
else
{
data.split(",").forEach(function (item) {
var opt = document.createElement(item);
document.getElementById('<%= ddlCity.ClientID %>').options.add(opt);
});
but it is not working.
Briefly, I have a return data like (text1,text2,text3,text4) how to add return data in ddlCity item on javascript?
Thank you for your answers.

Try this
data.split(",").forEach(function (item) {
var option = document.createElement("option");
option.text = item;
option.value = item;
var ddl= document.getElementById('<%= ddlCity.ClientID %>')
ddl.appendChild(option);
});
Check below
append option to select menu?

Using forEach as in your code snippet:
Demo: http://jsfiddle.net/abhitalks/63eX6/1/
var data = "text1,text2,text3,text4";
var ddl = document.createElement("select");
ddl.id = "s1";
document.getElementById("container").appendChild(ddl);
data.split(",").forEach(function(item) {
var opt = document.createElement("option");
opt.value = item;
opt.text = item;
ddl.appendChild(opt);
});
Create a select, assign an id to it, and append it to an existing container like div,
Loop over the split array, create option element, assign value and text and then append it to the select.

Related

Onclick for arrays in JSON

I'm retrieving data through an api, and creating a list using JS. I was wondering if it was possible to create a onclick function for every element in an array element of a JSON. The elements are being displayed, but nothing happens when I click them. Also, is it possible to pass on data in the JSON with this redirection to a new page?
My code is as follows:
var url = "https://api.nytimes.com/svc/movies/v2/reviews/all.json?api-key=b5f6bc931d6e446a998eb063a7c13d8e";
$.ajax({
url: url,
method: 'GET',
dataType: 'json',
success: function (data) {
var data = data;
details(data);
for (var i = 0; i < Object.keys(data.results[0]).length; i++) {
document.getElementById("movlist");
var item = document.createElement('li');
item.className = 'listele';
var itempicdiv = document.createElement('div');
itempicdiv.className = 'picdiv';
var itempic = document.createElement('img');
itempic.className = 'pic';
itempic.src = data.results[i].multimedia.src;
var itemnamediv = document.createElement('div');
itemnamediv.className = 'namediv';
var itemname = document.createTextNode(data.results[i].display_title);
itemname.className = 'name';
itempicdiv.appendChild(itempic);
itemnamediv.appendChild(itemname);
item.appendChild(itempicdiv);
item.appendChild(itemnamediv);
list.appendChild(item);
}
}
}).done(function (result) {
console.log(result);
}).fail(function (err) {
throw err;
});
function details(data) {
for (var j = 0; j < Object.keys(data.results[0]).length; j++) {
var t = data.results[j];
t.onclick = function () {
location.href = 'detail.html';
}
}
}

JS insertHtml without focus?

I have some code written in PHP with textarea input field. I also have a JS code that inserts html code into field:
$('form textarea#response').ready(function() {
function populateGet() {
var obj = {}, params = location.search.slice(1).split('&');
for(var i=0, len=params.length;i<len;i++) {
var keyVal = params[i].split('=');
obj[decodeURIComponent(keyVal[0])] = decodeURIComponent(keyVal[1]);
}
return obj;
}
var test = populateGet();
var ticid;
for(var key in test) {
if(Object.prototype.hasOwnProperty.call(test, key)) {
var val = test[key];
ticid = val;
}
}
$('form select#cannedResp').val('original');
var fObj = $(this).closest('form');
var $url = 'ajax.php/tickets/'+ticid+'/canned-resp/original.json';
$.ajax({
type: "GET",
url: $url,
dataType: 'json',
cache: false,
success: function(canned){
console.log('dupa');
//Canned response.
var box = $('form textarea#response'),
redactor = box.data('redactor');
if(canned.response) {
if (redactor){
redactor.insertHtml(canned.response);
}else{
box.val(box.val() + canned.response);
box.blur();
}
//if (redactor)
//redactor.observeStart();
}
//Canned attachments.
var ca = $('.attachments', fObj);
if(canned.files && ca.length) {
var fdb = ca.find('.dropzone').data('dropbox');
$.each(canned.files,function(i, j) {
fdb.addNode(j);
});
}
document.getElementById('focustest').focus();
}
})
.done(function() { })
.fail(function() { });
});
The problem is that execution of above code (redactor.insertHtml(canned.response);) causes focus on the textarea. The code is executed on page load.
Is there any way I can insert the content into field without causing the focus to placed on this field?
Thank you in advance and best regards
Tom

How to pass the select box value as an array using AJAX from one page to another in PHP?

var message = $("#send_message").val();
var Teaminput = $("#sms_reminder_team").val();
for (var i = 0; i <Teaminput.length; i++)
{
var team=Teaminput[i];
}
var Memberinput = $("#sms_reminder_members").val();
for (var i = 0; i <Memberinput.length; i++)
{
var members=Memberinput[i];
}
Get 2 varaibles as array members and team
var parameter = "message="+message+"&team="+team+"&members="+members;
$.ajax({
url: base_url+'ajaxfiles/dir_sendmessage',
type: 'POST',
data: parameter,
success: function(data)
{
document.getElementById('check').innerHTML = data;
}
});
How to send both array variables using AJAX from current page to "dir_sendmessage".
Change the below line
var parameter = "message="+message+"&team="+team+"&members="+members;
to
var parameter = "message="+message+"&team="+JSON.stringify(team)+"&members="+JSON.stringify(members);
Edit: Modify like this too
var team = [];
var members = [];
for (var i = 0; i <Teaminput.length; i++)
{
team=Teaminput[i];
}
var Memberinput = $("#sms_reminder_members").val();
for (var i = 0; i <Memberinput.length; i++)
{
members=Memberinput[i];
}
Note: When you add var in each line in the loop, it will declare a new variable. You have to edit like the above code
After update the code with the JSON.stringify() function, you will be able to get the value as an array in you PHP code
Ajax will not directly pass Jquery array to PHP
First of all ideally you should send in JSON format or use array.tostring() ( can avoid this )
But if you have to send it as array you can try following:
$.ajax({
url: base_url+'ajaxfiles/dir_sendmessage',
type: 'POST',
data: {team:team, members: members},
success: function(data) {
document.getElementById('check').innerHTML = data; } });
var message = $("#send_message").val();
var teaminputt = $("#sms_reminder_team").val();
team = new Array();
members = new Array();
for (var i = 0; i <teaminputt.length; i++)
{
var team=teaminputt[i];
}
var memberinput = $("#sms_reminder_members").val();
for (var i = 0; i <memberinput.length; i++)
{
var members=memberinput[i];
}
var parameter = "message="+message+"&team="+team+"&members="+members;
$.ajax({
url: base_url+'ajaxfiles/dir_sendmessage',
type: 'POST',
data: parameter,
success: function(data)
{
document.getElementById('check').innerHTML = data;
}
});
$("#msg-send-btn").click(function() {
var message = $("#send_message").val();
var optionsmembers = $('#sms_reminder_members option:selected');
var members = $.map(optionsmembers ,function(option) {
return option.value;
});
//---- Using $.map get all selcted data as a an Array.
var postData = {
message,
members
}
//---- For Avoid Json-Stringfy.
$.ajax({
url: base_url+'ajaxfiles/dir_sendmessage.php',
type: 'POST',
data:{myData:postData},
//----- And It's Work Perfectly.

getting "undefined" when i print json array with js

I want to parse json array it came down from json.jsp, but when i access parse.js it displays undefined
Here is parse.js
$(document).ready(function() {
$('#login').click(function(event) {
$.get('json.jsp', {
}, function(responseText) {
var myJSONObject1 = responseText;
var myJSONObject = JSON.parse(myJSONObject1);
var len = myJSONObject.length;
var out = "";
for (var i = 0; i < len; i++) {
var student = myJSONObject[i];
out += "<li>"+student.ircEvent + "<li>" + student.method+"<li>"+student.regex;
}
document.getElementById("ajaxResponse").innerHTML = out;
});
});
});
and my json.jsp is,
<%
response.setContentType("plain/text");
User user = new User("RAM","ram#gmail.com");
User user1 = new User("Ravi","ravi#gmail.com");
User user2 = new User("Raghu","raghu#gmail.com");
List list = new ArrayList();
list.add(user);list.add(user1);list.add(user2);
String json = new Gson().toJson(list);
response.getWriter().write(json);
%>
when i access parse.js file, it displays undefined
any ideas......
Just use $.ajax and set the dataType to json. No need to parse anything. jQuery does it for you. http://api.jquery.com/jquery.ajax/
jQuery(document).ready(function($) {
$.ajax({
url: 'json.jsp',
type: 'get',
dataType: 'json',
success: function(data) {
if (data.length) {
var ajaxResponse = document.createElement('table'),
tbody = document.createElement('tbody');
for (var i in data) {
if (data.hasOwnProperty(i)) {
var tr = document.createElement('tr'),
key = document.createElement('td'),
keyText = document.createTextNode(i),
value = document.createElement('td'),
valueText = document.createTextNode(data[i]);
key.appendChild(keyText);
tr.appendChild(key);
value.appendChild(valueText);
tr.appendChild(value);
tbody.appendChild(tr);
}
}
ajaxResponse.appendChild(tbody);
$("#ajaxResponse").append(ajaxResponse);
}
else alert("No data returned!");
}
});
});

rendering list-images bbui from database mysql

I'm trying to make a list bbui image using ajax call in a mysql database, but in the process I do not get the same format as the image of bbui list, following my code
var idmember='glut1';
function dataOnLoad_initialLoad(element) {
var listItem, dataList = element.getElementById('dataList');
$.ajax({
type: "GET",
url: "ajax/history.php?id_member=" + idmember,
dataType: "json",
error: function(xhr, settings, exception) {
alert("error");
},
success: function(data){
$.each(data, function(key, val) {
listItem = document.createElement('div');
listItem.setAttribute('data-bb-type', 'item');
listItem.onclick = function() {
bb.pushScreen('detail.htm', 'detail');
};
listItem.setAttribute('data-bb-title', val.tglorder);
listItem.innerHTML = val.namastatus;
dataList.appendChild(listItem);
var order = val.idorder;
});
}
});
}
and then the code implemented in beforedetail.html like this code
<div id="dataList" data-bb-type="image-list" data-bb-images="none" data-bb-style="arrowlist">
</div>
I had a similar problem but my case was to generate an image list with a header to group items.
I did it the only way i know ho and it worked but am open to suggestions on how to do it better.
Here is the js code:
var listItem, header,
dataList = document.getElementById('dataList');// this is my list already in the DOM
var list = [];
var user = localDB.getScreenName();
$.ajax({
url: reg.api(),
data: {action: 'getAttire', formData: user},
type: 'post',
dataType: 'jsonp',
jsonp: false,
jsonpCallback: 'result',
beforeSend: function() {
document.getElementById('indicator').style.display = 'block';
},
complete: function() {
document.getElementById('indicator').style.display = 'none';
},
success: function(res) {
//showbList();
var title = [];
for (var i = 0; i < res.length; i++) {
if ($.inArray(res[i].item, title) === -1) {
title.push(res[i].item);//creates header array with unique values cos i had headers with duplicate names
}
// This creates header Array from the list
}
for (var k = 0; k < title.length; k++) {
header = document.createElement('div');
header.setAttribute('data-bb-type', 'header');
header.id = 'headers';
header.innerHTML = title[k];
header.style.background = '#f6f6f6';
header.style.fontSize = '20px';
header.style.fontWeight = 'bold';
// header.style.boxShadow = ''
list.push(header);//header created here
for (var i = 0; i < res.length; i++) {
if (header.innerHTML === 'Bag' && res[i].item === 'Bag') {
//var date =
listItem = document.createElement('div');
listItem.setAttribute('data-bb-type', 'item');
listItem.setAttribute('data-bb-img', res[i].img_link);
listItem.setAttribute('data-bb-title', res[i].name);
listItem.setAttribute('data-bb-accent-text', 'Added: '+jQuery.timeago(res[i].date));
listItem.setAttribute('dressup',res[i].DRESS_ID);
listItem.setAttribute('id','wardropeLink');
listItem.innerHTML = "Suited for: " + res[i].suited;
listItem.style.color = "#fff";
listItem.onclick = function() {
var selected = document.getElementById('wardropeLink').getTitle();
console.log(selected); // trying to get d title of a selected or clicked list but it returns the whole group. still working on it
};
list.push(listItem); //list item for a particular header created here
}
if (header.innerHTML === 'Trousers' && res[i].item === 'Trousers') {
listItem = document.createElement('div');
listItem.setAttribute('data-bb-type', 'item');
listItem.setAttribute('data-bb-img', res[i].img_link);
listItem.setAttribute('data-bb-title', res[i].name);
listItem.setAttribute('data-bb-accent-text', jQuery.timeago(res[i].date));
listItem.innerHTML = "Suited for: " + res[i].suited;
listItem.style.color = "#fff";
listItem.onclick = function() {
handleWardrope.listItems(res[i].DRESS_ID);
};
list.push(listItem);
}
}
}
var items = dataList.getItems();
if (items.length > 0) {
//list.insertItemBefore(item, items[0]);
} else {
dataList.refresh(list);//list added to DOM
if (bb.scroller) {
bb.scroller.refresh();
}
}
}
});
return false;
Hope this helps.
Warning and still trying to get the onclick function work for a particular list item but it seems to group them cos of the loop.
concerning the problem i had about getting the title of a list item
i solved it by calling the list selected function and then acted on the getTitle of the selected item.
code
listItem.onclick = function(){
var selected = document.getElementById('dataList').selected;
console.log(selected.getAttribute('dressup'));
}
what i did wrong before was i tried to get d selected item on d item itself and not on the imagelist.

Categories

Resources