Populating JScript Array for reuse on SELECTs - javascript

Forgive me if this is already 'somewhere' on StackOverflow, but I don't 100% know exactly what it would come under...
I'm trying to retrieve information from a WebService, store this in an array, and then for each <select> within my ASP.Net Datalist, populate it with the array AND have binding attached to an OnChange event.
In other words, I have an array which contains "Yes, No, Maybe"
I've an ASP.Net Datalist with ten items, therefore I'd have 10 <Select>s each one having "Yes, No, Maybe" as a selectable item.
When the user changes one of those <Select>s, an event is fired for me to write back to the database.
I know I can use the [ID=^ but don't know how to:
a) Get the page to populate the <Select> as it's created with the array
b) Assign a Change function per <Select> so I can write back (the writing back I can do easy, it's just binding the event).
Any thoughts on this?

I have built a simple example that demonstrates, I think, what you are attempting to accomplish. I don't have an ASP.Net server for building examples, so I have instead used Yahoo's YQL to simulate the remote datasource you would be getting from your server.
Example page => http://mikegrace.s3.amazonaws.com/forums/stack-overflow/example-multiple-selects-from-datasource.html
Example steps:
query datasource to get array of select questions
build HTML of selects
append HTML to page
attach change event listener to selects
on select value change submit value
Example jQuery:
// get list of questions
$.ajax({
url: url,
dataType: "jsonp",
success: function(data) {
// build string of HTML of selects to append to page
var selectHtml = "";
$(data.query.results.p).each(function(index, element) {
selectHtml += '<select class="auto" name="question'+index+'"><option value="Yes">Yes</option><option value="No">No</option><option value="Maybe">Maybe</option></select> '+element+'<br/>';
});
// append HTML to page
$(document.body).append(selectHtml);
// bind change event to submit data
$("select.auto").change(function() {
var name = $(this).attr("name");
var val = $(this).val();
// replace the following with real submit code
$(document.body).append("<p>Submitting "+name+" with value of "+val+"</p>");
});
}
});
Example datasource => http://mikegrace.s3.amazonaws.com/forums/stack-overflow/example-multiple-selects-from-datasource-datasource.html
Example loaded:
Example select value changed:

Related

javascript ajax onchange select box while doing update

I have a select box which populates data based on selection on other select boxes.
I am able to populate data. But how to make a value selected and do onchange event during editing of the form. ie, updation.
I am facing difficulty in making it selected based on database entry and to do onchange. What I am able to do it just the populating data from DB based on change.
you can easly create it with jquery, here's the example:
$('#id_of_your_select').change(function(){
var val = $('#id_of_your_select option').attr('selected', 'selected');
$.post({
url: "your_url",
data: {
value: val; // get the input post of value in server side
},
success: function(result){
// loop a json array and use append function of the jquery on the second select box
}
})
});
i can only explain like that cause there's no code that you give.

Populating drop downs with MySQL entries

I have a MySQL database that contains, amongst other things, 2 tables. One is the events table, containing event names and other details. The other is the instance table. This table links the events table to a venue table and adds a date, so each row is an instance of the linked event.
I am making an event booking form for internal use for these events. I want to allow selection of the event to be booked via a dropdown list. So, I have populated one dropdown with the event names:
$qEvent = "SELECT event_name, event_id FROM events";
$rEvent = mysqli_query($dbc,$qEvent);
echo '<select>';
while ($row = mysqli_fetch_assoc($rEvent)) {
echo '<option value="'.$row['event_id'].'">'.$row['event_name'].'</option>';
}
echo '</select>';
What I now want to do is, for the selected event, grab all the instances associated with that event, and populate another dropdown with the dates.
Can I do this with PHP, or do I need to dip into Javascript? I think I just need some way to grab the event_id value of the dropdown selection and then query based on that, but I don't know how without Javascript.
You should be looking at Javascript or jQuery for achieving your goal. I've used jQuery based on my question to you earlier. It's also simpler and less code.
Your PHP:
Add an ID attribute event_menu to your select menu
echo '<select id="event_menu">';
while ($row = mysqli_fetch_assoc($rEvent)) {
echo '<option value="'.$row['event_id'].'">'.$row['event_name'].'</option>';
}
echo '</select>';
<div id="container_for_new_menu"></div>
Using jQuery:
$('#event_menu').on('change', function() {
// get selected value and build data string for AJAX
var event_selected = "event_selected="+$(this).val();
// send the selected data to a PHP page to build the populated menu
$.ajax({
url : 'populate-menu.php',
type: 'POST',
data : event_selected,
dataType : 'html',
success : function(data) {
$('#container_for_new_menu').html(data);
}, error : function() {
alert("Something went wrong!");
}
});
});
On populate-menu.php, have something like:
$event_selected = isset($_POST['event_selected']) ? $_POST['event_selected'] : null;
// do SQL query here based on user's selection
// making sure you validate the data in the POST request for malicious BS
// or use parameterized queries
// then build a new menu to send back
echo '<select>';
// loop through results and build options
echo '</select>';
This new menu will then be posted back to your original page into the container_for_new_menu element.
By the looks of it, you want to populate the "instances" dropdown based on the selection the user makes on the "event" dropdown. You cannot do this without Javascript.
My suggested way of doing this is to use AJAX to pull the instance data and populate the "instances" dropdown on change of the "event" dropdown. Useful resources below for simple AJAX get with jQuery:
http://api.jquery.com/jQuery.get/
http://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax/
You need some kind of Javascript to accomplish this. Either:
Basic- submit the form on select and let php populate the instance drop-down.
More elegant- use Javascript to make an Ajax call on select which will dynamically replace the instance drop-down's div.
You will need JavaScript to populate the second drop down box. I suggest you load all the values into JSON on the page and then you can just use a jQuery on change event to populate the second select box.

Executing Javascript to populate a drop down before HTML page loads

I have 2 Drop Downs in a HTML form. The first dropdown needs to be populated with a list of usernames present in the DATABASE.
Secondly, Depending upon the selection made in the first drop down, I then need to run another JS script to make another call to the DB to retrieve the list of associated addresses to that username.
Can you please let me know whats the best way to achieve this objective?
1) How can I run a JSscript before the HTML form loads to return that list?
2) Should I get both the usernames and associated addresses in one Db call or just get the usernames first and then use onChange event on the first dropdown to execute the second call?
Any code would be most appreciated.
Thanks
well if you have all the info in same table then why dont you get all data in one go by querying as to the DB and then sort and put up data in the elements the way you want.
the other way will need to query DB 2 times.
here you can create your HTML to server call OR you can make HTML locally.
i have created options for selectbox at server and innerhtml to locally.
<select id="selectbox1" onchange="getData(this)"></select>
<select id="selectbox1"></select>
$(document).ready(function() {
$.ajax({
url: 'http://localhost/getUsername.php',
success: function(data) {
$('#selectbox1').html(data);
alert('Load was performed.');
}
});
});
function getData(selData) {
$.ajax({
url: 'http://localhost/getSecoundCall.php?id='+selData,
success: function(data) {
$('#selectbox2').html(data);
alert('Load was performed.');
}
});
}

How to get values from dynamically added (using javascript) elements?

On my aspx page I dynamically create html controls on client side using javascript. For example, after page load you can click button in a browser, by clicking button html input and select elements appear. You may click once again, and this elements (input and select) will added again. So, you can create so many inputs and selects as you want (all this using javascript, no postbacks)
After user created some inputs and selects and entered some information in it, he posted form. I want on server side to find all this dynamically added elements and perform some actions depends on values in this controls.
How can I find dynamically added elements, and what is the best and elegant way to achieve this?
Thanks in advance.
In the Javascript that creates the new elements, increment a counter each time an element is created. Add the value of the counter to the name of the input element so each element has a unique name.
Add the final value of the counter to a hidden form field when the form is posted.
In your server side code, create a loop that starts at zero and continues until you have reached the value of the counter. Within the loop, fetch the posted value of the corresponding form field.
When you add the elements, assign unique IDs to them, and then retrieve their values using Request.Form["UniqueIdHere"] (C#) or Request.Form("UniqueIdHere") (VB.NET).
Create a loop that loops through each input and select object, that grabs the name/id of the current object and its corresponding value. Then add those items to an array and once the loop is completed, pass those values to your aspx file.
You can view an example with this approach at: http://jsfiddle.net/euHeX/. It currently just alerts the values, but you could easily modify it to pass the values as a parameter via ajax to your handler aspx file. The code will add new inputs or select boxes based off of the input provided. This would of course be modified to reflect your current setup.
HTML:
<div id="dynamic"></div>
<input type="button" id="submit-form" value="Submit>>">
JavaScript (using jQuery):
function createInput(type){
for(var i=0; i<5; i++){
if(type==0){
var obj = '<input type="text" id="'+i+'" class="dynamicContent">';
}else if(type==1){
var obj = '<select id="'+i+'" class="dynamicContent"><option>--Select--</option></select>';
}
$("#dynamic").append(obj);
}
}
function getContent(){
var inputArray = [];
$(".dynamicContent").each(function(k,v){
var o = $(this);
var oType;
if(o.is("input")){ oType = "input"; }
if(o.is("select")){ oType = "select"; }
var oID = oType+o.attr("id");
var oValue = o.val();
inputArray.push(oID+'='+oValue);
});
alert(inputArray);
}
$("#submit-form").click(function(){
getContent();
});
// Set type to 0 for input or 1 for select
var type = '1';
createInput(type);
If you're using jQuery you can use .live() to achive this like a peace of cake!
http://api.jquery.com/live/
I don't know if your controls will survive the postback the way you're creating them, but a good technique for accessing dynamically generated controls (assuming that you've figured out how to persist them) is to do something like the following:
Add a panel to your page. Add your dynamically created controls to this panel.
In the OnClick event handler (or other method), do something like the following:
foreach (DropDownList ddl in Panel1.Controls.OfType<DropDownList>())
{
//put code here
}
foreach (TextBox txt in Panel1.Controls.OfType<TextBox>())
{
//put code here
}

Dynamically generate the content of Drop Down list via jQuery

I am new to Javascript, JSON and jQuery. So please be easy on me. I have a JSP page that contain a drop down list. The contents of the drop down list are populated when the page is loaded. I wrote a Servlet that return the contain of the drop down list in the form of Map, and convert it to JSON string and sent back to the jsp via response.getWriter().write(json); However I am having trouble to getting the result back from the jsp side, and populate the contain of the drop down list from the result. Here are my codes
customer.jsp
$(document).ready(function() {
getCustomerOption('customer'); //try to pre-populate the customer drop down list
});
function getCustomerOption(ddId) {
var dd = $('#' + ddId);
$.getJSON("http://localhost:8080/WebApps/DDListJASON", function(opts) {
$('>option', dd).remove(); // Remove all the previous option of the drop down
if (opts) {
$.each(opts, function(key, value) {
dd.append($('<option/>').val(key).text(value));
}
}
});
}
down where the drop down list is generated
<select id="customer" name="customer">
<option></option>
</select>
The result is nothing get populated into the list. So sad
I think you are invoking the wrong function in document ready
Shouldn't it be
getInitialOption('customer');
instead of
getCustomerOption('customer');
You may add additional <option> elements to a <select> with the code:
$("#selectID").append("<option>" + text + "</option>");
see: JQuery Docs
I don't understand $(''), but I'm not sure that's the problem either, hard to tell exactly.
I do know it will be quicker if you do create the list of options in-memory and then do one append with .html(options) rather than append them one at a time. That may make it easier to understand also, to build the html up one line at a time and then append it.

Categories

Resources