i have a select2 element that load data from database using ajax. i want to load the value from db and select it as selected value in edit mode.
but im not able to load the value using trigger function.
i tried using looping by comparing selected values but i got the select2 option orinted twice.
$(document).ready(function(){
var area = $('#area').select2({
placeholder: "Pilih Cabang Area Tagih Collector Agency...",
multiple: true,
allowClear: true,
width: 'resolve'
});
var k;
var selected = [];
//imloading the value from db and insert it into an array
<?php foreach($area_coll as $area){
?>
selected.push("<?php echo $area->group_branch_id;?>");
<?php
}?>
$.ajax({
url: "<?php echo base_url();?>ama/c_agency/populate_dropdown_cabang",
type: 'GET',
success: function(data) {
var html = '';
var j;
data = JSON.parse(data);
//looping cabang
for(j=0; j<data.length; j++){
$('#area').append($('<option>').val(data[j].GroupBranchID).text(data[j].branch));
}
}
});
//this function not working at all
area.val(selected).trigger("change");
});
im not getting any error with this code nor the value still not selected.
Select2 have ajax options.
So I think you can use ajax directly as an options of select2 (reference: https://select2.org/data-sources/ajax#default-pre-selected-values)
The document said:
To provide default selections, you may include an <option> for each selection that contains the value and text that should be displayed:
<select class="js-example-data-ajax form-control">
<option value="3620194" selected="selected">select2/select2</option>
</select>
Mean that at the options you can push selected="selected" at edit page when option is stored on exist record.
Hope it help. thanks
Related
Im using TomSelect to control my <select> UI for my dependent select dropdowns.
The <option>...</option> list of the To dropdown depends on the From dropdown and is updated per ajax call on the selection in the From dropdown. The first initialization works fine on both dropdowns. Unfortunately, after repeating the ajax request through selecting another location on the From dropdown results in the following error:
Uncaught Error: Tom Select already initialized on this element
What i did so far:
1. On page load i'm initializing TomSelect on the From dropdown with:
tsfrom = new TomSelect('#from-select-field',ttddssettings);
The relevant lines of code:
<select id="from-select-field" name="from" onchange="getTo();">
<option value='0'>Choose...</option>
</select>
<select id="to-select-field" name="from">
<option value='0'>Select From first</option>
</select>
<script>
jQuery(document).ready(function($) {
var tsfrom;
var ttddssettings = {
plugins: ['dropdown_input'],
};
tsfrom = new TomSelect('#from-select-field',ttddssettings);
var totoval = "xymydomain.com/get-to-options.php";
getTo = function () {
var fromvalue = $("#from-select-field").val();
var tovalue = $("#to-select-field").val();
$.ajax({
type: "POST",
url: totoval,
data: {
from: fromvalue,
to: tovalue,
},
success: function(data) {
$("#to-select-field").html(data);
},
});
}
});
</script>
The relevant lines of code inside the requested PHP file:
<?php
$sql_to = "SELECT * FROM locations WHERE ..... ORDER by names ASC";
$quer_to = $pdo_conn->prepare($sql_to);
$quer_to->execute();
$fetch_to_values = $quer_to->fetchAll();
foreach ( $fetch_to_values as $tovalues ) {
?>
<option value="<?php echo $tovalue['name']; ?>" <?php if ( $tovalue['name'] == $to) { echo "selected";} ?>><?php echo $tovalue['name']; ?></option>
<?php } ?>
<script>
jQuery(document).ready(function($) {
var tsto;
var tttossettings = {
plugins: ['dropdown_input'],
};
tsto = new TomSelect('#to-select-field',tttossettings);
});
</script>
2. After selcting a From location the To dropdown gets populated per ajax. The requested file (see above) through ajax url: includes also the following code to initialize TomSelect on the To dropdown:
tsto = new TomSelect('#to-select-field',tttossettings);
So far everything works fine.
3. THE PROBLEM:
As mentioned before, after repeatedly selecting a different location on the From dropdown i get the error Tom Select already initialized on this element.
The TomSelect DOCS mentioning refreshOptions(triggerDropdown) (Refreshes the list of available options shown in the autocomplete dropdown menu.). Unfortunately I have no idea if this is the right approach or how to fix this. Any help would be greatly appreciated.
Two changes should get rid of the error:
Remove script block from PHP page:
Get rid of the <script> block in your PHP file and only return the <option>...</option> values. This is also messy as you are setting the HTML of the <select> to be what the PHP code has generated, including the returned script block.
Trigger updating the drop down in the AJAX success block
$.ajax({
type: "POST",
url: totoval,
data: {
from: fromvalue,
to: tovalue,
},
success: function(data) {
$("#to-select-field").html(data);
tsto.clear(); // unselect previously selected elements
tsto.clearOptions(); // remove existing options
tsto.sync(); // synchronise with the underlying SELECT
},
});
Using the sync method should update the styled dropdown options based on the underlying <select>.
Alternatively, calling tsfrom.refreshOptions(); instead of sync() could also work.
I currently have a webpage that works great. I select my load number and a ajax query gets the information and puts the results in textboxs. The page is split, one part displays information, but when "print" is selected, it formats the results to print a bubble sheet.
Here is the problem. Instead of displaying the "On Screen" results in textboxs, I would rather just display as normal text.
The active page is located at this address
The retrieval code is quite long, here is a sample.
<script>
$(document).ready(function(){ /* PREPARE THE SCRIPT */
$("#loads").change(function(){ /* TRIGGER THIS WHEN USER HAS SELECTED DATA FROM THE SELECT FIELD */
var loadnumber = $(this).val(); /* STORE THE SELECTED LOAD NUMBER TO THIS VARIABLE */
$.ajax({ /* START AJAX */
type: "POST", /* METHOD TO USE TO PASS THE DATA */
url: "actionprt.php", /* THE FILE WHERE WE WILL PASS THE DATA */
data: {"loadnumber": loadnumber}, /* THE DATA WE WILL PASS TO action.php */
dataType: 'json', /* DATA TYPE THAT WILL BE RETURNED FROM action.php */
success: function(result){
/* PUT CORRESPONDING RETURNED DATA FROM action.php TO THESE TEXTBOXES */
for (i = 1; i < 14; i++) {
$("#prtDescription" + i).val("");
$("#prtMethod" + i).val("");
$("#prtPONumber" + i).val("");
$("#prtGallons" + i).val("");
$("#prtAmount" + i).val("");
}
$("#NumberStops").val(result.NumberStops);
$("#ShipperName").val(result.CustomerName);
$("#prtship").val(result.CustomerName);
$("#ShipperAddr1").val(result.CustomerAddress);
$("#ShipperAddr2").val(result.CustomerAddress2);
$("#ShipperCity").val(result.CustomerCity);
$("#prtshipcity").val(result.CustomerCity);
$("#ShipperState").val(result.CustomerState);
$("#prtshipstate").val(result.CustomerState);
$Phone = result.CustomerPhone
$Phone = '(' + $Phone.substring(0,3) + ') ' + $Phone.substring(3,6) + '-' + $Phone.substring(6,10)
$("#ShipperPhone").val(result.CustomerPhone);
$("#ShipperContact").val(result.CustomerContact);
$("#PickupDate").val(result.PickupDate);
$("#prtdate").val(result.PickupDate);
$("#PickupTime").val(result.PickupTime);
$("#CustomerPO").val(result.CustomerPO);
$("#Weight").val(result.Weight);
$("#prtweight").val(result.Weight);
$("#Pieces").val(result.Pieces);
$("#prtpieces").val(result.Pieces);
$("#BLNumber").val(result.BLNumber);
$("#prtbol").val(result.BLNumber);
$("#TrailerNumber").val(result.TrailerNumber);
$("#prttrailer").val(result.TrailerNumber);
...
I tried document.write() but that cleared the page which is not what I am looking for. I want to keep my images and combobox selection box on the page so I can select other loads when needed rather then just one at a time.
Please help.... If you require more information to answer the question, please ask and I will post.
Why not just make a new div after your load selection and simply append all those results into it?
There are different options to use Ajax as per your Requirement. You can replace the Entire div with the new Data or with the Entire HTML or you can change the selected part alone. It is up-to you who have to choose the suitable method which will be easy for you.
These are the methods available:
Method 1:
function testAjax(handleData) {
$.ajax({
type: 'POST'
url:"yourpostpage.php",
data: "&s=1",
success:function(data) {
handleData(data);
}
});
}
This above method will replace the Ajax success with the data that is available after your process is completed.
Method 2:
function testAjax(handleData) {
$.ajax({
type: 'POST'
url:"yourpostpage.php",
data: "&s=1",
success:function(html) {
handleData(html);
}
});
}
The above function will replace the entire success div with the new HTML part.
Now i will illustrate it with a simple example of how to replace the div using PHP and HTML using AJAX.
Scenario: User Has to select the city and the City Details will load up in Ajax.
HTML:
<select name="city" onchange="selectcity(this.value)">
<option value="">Please Select</option>
<option value="1">USA</option>
<option value="2">Europe</option>
</select>
<div id="ajax_output">
</div>
While selecting the city it will load up the function by using onchange attribute in jQuery and the Ajax will be passed.
JS:
function selectcity(a) {
$.ajax({
type: 'POST'
url:"yourpostpage.php",
data: "&city="+a,
success:function(html) {
$('#ajax_output').html(html);
}
});
}
In the JS am getting the selected value using a since i have passed a parameter to the function and passing it to the Ajax Page.
Ajax Page:
Note: Ensure that if you are going to display the information form the DB you have to connect the DB file to the Ajax page.
<?php
$city_id = $_POST['city']; // Jquery Data that i am retriving on Ajax Page
$select="SELECT * FROM TABLENAME WHERE `city_id`='".$city_id."'";
$query = $con->query($select);
$count = $query->num_rows;
if($count==0)
{
echo 'No Data Found';
}
else
{
while($fetch = $query->fetch_assoc())
{
?>
<div class="col-sm-6">
<label>City</label>
<span><?php echo $fetch['city_name']; ?></span>
</div>
<div class="col-sm-6">
<label>Place</label>
<span><?php echo $fetch['place']; ?></span>
</div>
<?php
}
}
?>
Now in my example i am going to replace the #ajax_output div with the content that is going to come from the Ajax page.
As per the request made in the question i hope so this would be the easiest method so that PHP will execute faster when compared to the JS and the Errors will also be minimal when you use this method.
Hope so my explanations would be clear for you and if you face any hindrance in development let me share thoughts and i will provide you with a solution.
Happy Coding :)
I have a multiple select item, which allows me to check multiple items. I want to send those selected items via ajax request and afterwards I want to import the those items into my database. My problem is, that I don't know how to loop thru the passed array, which I get by the POST request.
Ajax Request
function insertPlayers(){
var data = $("#playerCards").serialize();
$.ajax({
url: "/database/playercards.php",
type: "POST",
data: data,
success: function (response) {
}
});
}
This is my HTML multiple select:
<select multiple id="assignAccount" name="assignAccount" class="form-control select">
// Options inserted by JQuery later
</select>
This is how my data looks like when I alert it before sending the Ajax Request:
playersearch=test&buypercentage=85&assignAccount=9&assignAccount=10&assignAccount=11
How I add the options to my multiple selectbox:
// loop the response
$.each(response, function(i, e){
// just use your column names, these are just an example, but you get the idea
opt += '<option value="'+e.id+'">'+ e.email + ' - ' + e.coins + '</option>';
});
// append the markup to that select box
$('#assignAccount').html(opt)
My problem:
It should be clearly now that the assignAccount variable is a array which I want to loop thru in PHP but I don't know how I can do this because I don't know the indices. This is what I've tried:
$accountIds = $_POST['assignAccount'];
foreach ($accountIds as $account){
echo $account;
}
Change
<select multiple id="assignAccount" name="assignAccount" class="form-control select">
to something more like
<select id='assignAccount' name='assignAccount[]' multiple='multiple' class='form-control select'>
make the select statement multiple id an array
<select name='assignAccount[]' id='assignAccount[]'>
on your php page you will now have an array for this post.
$_POST['assignAccount'][0]
$_POST['assignAccount'][1]
and so on.
The select element when multiple send data like this:
playersearch=test&buypercentage=85&assignAccount=9,10,11
Hence, in the PHP side you do this:
$accountIds = explode(",", $_POST['assignAccount']);
foreach ($accountIds as $account){
echo $account;
}
I have a code that will display select and textbox depending on the count of the loop. The select dropdown will display currencies on acronym format if selected example USD the textbox will display "US Dollars". on the second loop if I select JPY it will display Japan Yen on the textbox on the second row and so on. Is this possible on jquery?
Here is my code
<script>
$(document).ready(function(){
$('#acr').change(function(){
//get json + this.value get corresponding value on db
//retrieve data
});
});
</script>
<?php
foreach($data as $d) {
?>
<select name = "acr" id = "acr">
//Records from db
</select>
<input type = "text" readonly value = ""> <br>
<?
}
??
Yes. But first please give a name attribute to your textbox and assume its id is 'longName'. You may have two options:
option 1:
Save the currencies short name/Long name in select. JPY
code:
$('#acr').change(function(){
$('#longName').val($(this).val());
});
option 2:
$('#acr').change(function(){
var sel = $(this);
$.ajax({
url: "your url",
type: "POST",
data: 'data='+sel.val(),
dataType:'json',
success: function(data) {
//Do what ever you want. Data holds the response from server
},
error: function() {
//Error occured, handle it
}
});
});
Read more on ajax here
When I select one item from 1st dropdown, an ajax event will fire up, invoke another function that will and load information to the second dropdown. I do not want this (No button solution please)
<select id=combo1>
<option>...</option>
...
</select>
<input type=button onclick="loadCombo2()">
You can go about something like this:
<select id="combo1" onchange="requestSend(this.value);">
options..........
</select>
<select id="combo2">
options...........
</select>
<script>
function requestSend(txt)
{
$.ajax({
url:'process.jsp',
data: "v=" + txt,
cache:false,
success: function(response){
$("#combo2").val(response);
}
});
}
</script>
....
Populating Combo2 Options:
To populate combo2 options, you need to create them in the script which process ajax request, for example in php (i don't know which language you are using), i will do something like this in ajax processing script:
// db queries to get data or whatever
// create a variable that will hold options and shown in combo2
$options = '<option value="whatever">whatever</option>' . "\n";
$options .= '<option value="whatever">whatever</option>' . "\n";
$options .= '<option value="whatever">whatever</option>' . "\n";
//........ etc
// Now we send back the $options variable which will populate the combo2
echo $options;
If it was being implemented in ASP.NET I'd use an HTTP handler to return the data in JSON format to the second combobox.
Using jQuery you'd call the handler in the following way to implement cascading:
$("#combo1").change(function()
{
$("#combo2").html("");
var valueSelected = $("#combo1").val();
if (valueSelected != 0)
{
$.getJSON('LoadCombo2.ashx?valueSelected=' + valueSelected, function(returnedData)
{
$.each(returnedData, function()
{
$("#combo2").append($("<option></option>").val(this['ID']).html(this['Value']));
});
});
}
});
To see how to implement the HTTP handler, take a look at a more complete step-by-step in this post:
http://www.codedigest.com/Articles/jQuery/224_Building_Cascading_DropDownList_in_ASPNet_Using_jQuery_and_JSON.aspx
If you don't need cascading the comboboxes, it gets easier. Just call the handler passing no parameters and load any data you need to fill the second combobox in the callback function of jQuery.
http://api.jquery.com/jQuery.getJSON/
Hope you get the idea.