I have two drop downs. First one contains mobile networks MTN , VODACOM , TELKOM and the second is a chosen multiselect dropdown which should contain data (cell numbers) populated via AJAX based on the mobile network above. but it is not firing after an AJAX call.
<div id="network" class="form-group required">
<label class="control-label">Mobile Network</label>
<select class="form-control" id="network" name="network">
<option id="MTN" value="MTN">MTN</option>
<option id="VODACOM" value="VODACOM">VODACOM</option>
<option id="TELKOM" value="TELKOM">TELKOM</option>
</select>
</div>
And the second one contain cell numbers based on what is selected from above. and the dropdown uses the Chosen Plugin
<div id="cellNumber" class="form-group required">
<label class="control-label">Select SIMs</label>
<select multiple class="chosen-select form-control" id="cellNumber" name="cellNumber[]">
</select>
</div>
On the page i do this
<script>
$("select.chosen-select").chosen(); //Initializing the plugin
$('select#network').change(function () {
var id = $('select#network').children(':selected').attr('id');
if(id != " "){
localStorage.clear();
AJAXCallNumbersByCarrier(id); //AJAX Call
}
});
</script>
And this is the AJAX
function AJAXCallNumbersByCarrier(data) {
var url = "/number/" + encodeURI(data) + "/carrier";
var type = "GET";
jQuery.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"').attr('content')
}
});
jQuery.ajax({
url: url,
type: type,
data: {
"_token": $('meta[name="csrf-token"').attr('content')
},
beforeSend: function () { },
success: function (data) {
try {
var count = data.length;
if (count > 0) {
var id = $('#cellNumber').attr('id');
$('select#cellNumber').empty();
var numbers = "<option value='' hidden=''>[Select SIMs]</option>";
for (var index = 0; index < count; index++) {
details = data[index];
id = details['cellnumber'];
cellnumber = details['cellnumber'];
simserial = details['simserial'];
realm = details['apnname'];
numbers += '<option id="' + id + '" value="' + cellnumber + '">'+'[ '+ cellnumber + ' ] [ ' + simserial + ' ] [ ' + realm + ' ]' + '</option>';
}
$('select#cellNumber').append(numbers);
$('div#cellNumber').show();
}else{
$('div#ErrorMessage').empty();
$('div#ErrorMessage').append("No numbers available for the selected customer");
$('div#ErrorMessage').show();
$('div.alert').not('.alert-important').delay(3000).fadeOut(350);
$('select#cellNumber').empty();
$('select#cellNumber').append("<option value'' hidden=''>[No numbers available for the selected customer]</option>");
$('div#cellNumber').show();
}
} catch (err) {
alert("Error running JS code from module: AJAXCallNumbersByCarrier");
}
},
error: function (url, jqXHR, textStatus, errorThrown) {
alert("url: " + url + " error: " + jqXHR.responseText + " status: " + textStatus + " errorThrown: " + errorThrown);
},
complete: function () { }
});
}
When i remove the $("select.chosen-select").chosen(); it works fine as a normal HTML multi select dropdown. The issue is the chosen. It is not firing. Data is empty. Please help.
try to reinitialize the chosen in the success function like
success:function(data){
// your code here
$('select#cellNumber').append(numbers);
$("select.chosen-select").chosen();
$('div#cellNumber').show();
}
it solved once i face the same issue.
Hope this helps.
I used Select2 instead. works well.
Related
This is my playingcards-advance (view page):
<h5>Country:</h5>
<select class="productcategory put" id="prod_cat_id">
<option value="0" disabled="true" selected="true">-Select-</option>
#foreach($prod as $cat)
<option value="{{$cat->id}}">{{$cat->product_cat_name}}</option>
#endforeach
</select>
<h5>State:</h5>
<select class="productname put">
<option value="0" disabled="true" selected="true">Select State</option>
</select>
<h5>City:</h5>
<select class="city put">
<option value="0" disabled="true" selected="true">Select City</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(document).on('change', '.productcategory', function () {
// console.log("hmm its change");
var cat_id = $(this).val();
// console.log(cat_id);
var div = $(this).parent();
var op = " ";
$.ajax({
type: 'get',
url: '{!!URL::to('findProductName')!!}',
data: {'id': cat_id},
success: function (data) {
//console.log('success');
//console.log(data);
//console.log(data.length);
op += '<option value="0" selected disabled>Select City</option>';
for (var i = 0; i < data.length; i++) {
op += '<option value="' + data[i].id + '">' + data[i].productname + '</option>';
}
div.find('.productname').html(" ");
div.find('.productname').append(op);
},
error: function () {
}
});
});
$(document).on('change', '.productname', function () {
var prod_id = $(this).val();
var a = $(this).parent();
console.log(prod_id);
var op = "";
$.ajax({
type: 'get',
url: '{!!URL::to('findcity')!!}',
data: {'id': prod_id},
dataType: 'json',//return data will be json
success: function (data) {
console.log('success');
console.log(data);
op += '<option value="0" selected disabled>choose city</option>';
for (var i = 0; i < data.length; i++) {
op += '<option value="' + data[i].id + '">' + data[i].city + '</option>';
}
a.find('.city').html(" ");
a.find('.city').append(op);
},
error: function () {
}
});
});
});
</script>
This is my Route code:
Route::get('/playingcards-advance', 'PagesController#prodfunct');
Route::get('/findProductName', 'PagesController#findProductName');
Route::get('/findPrice', 'PagesController#findPrice');
Route::get('/findcity', 'PagesController#findcity');
This is PagesController code
public function prodfunct()
{
$prod = ProductCat::all();//get data from table
return view('playingcards-advance', compact('prod'));//sent data to view
}
public function findProductName(Request $request)
{
//if our chosen id and products table prod_cat_id col match the get first 100 data
//$request->id here is the id of our chosen option id
$data = Product::select('productname', 'id')->where('prod_cat_id', $request->id)->take(100)->get();
return response()->json($data);//then sent this data to ajax success
}
public function findcity(Request $request)
{
//if our chosen id and products table prod_cat_id col match the get first 100 data
//$request->id here is the id of our chosen option id
$q = City::select('city', 'id')->where('state_id', $request->id)->take(100)->get();
return response()->json($q);//then sent this data to ajax success
}
The problem is that I'm not able to display state and city but I'm able to display country
I have also made model of all table
why it is not displaying state and city in the code
when I click on console and try to select country as America it is giving this error GET http://localhost/tmcards2/public/findProductName?id=1 500 (Internal Server Error)
The problem is that I'm not able to display state and city but I'm able to display country
I have also made model of all table
why it is not displaying state and city in the code
when I click on console and try to select country as America it is giving this error GET http://localhost/tmcards2/public/findProductName?id=1 500 (Internal Server Error)
The problem is that I'm not able to display state and city but I'm able to display country
I have also made model of all table
why it is not displaying state and city in the code
when I click on console and try to select country as America it is giving this error GET http://localhost/tmcards2/public/findProductName?id=1 500 (Internal Server Error)
why it is not displaying state and city in the code
when I click on console and try to select country as America it is giving this error GET http://localhost/tmcards2/public/findProductName?id=1 500 (Internal Server Error)
I use jquery in comboboxes, and I'm not abele to get the comboboxes in the interface to be displayed. The error in firebug is the following :
TypeError: $ is undefined : $.widget("ui.combobox", {
I'm using the following file jquery.ui.combobox.js:
Code :
$.widget("ui.combobox", {
options: {
openDialogButtonText: "+",
dialogHeaderText: "Add option",
saveButtonImgUrl: null,
closeButtontext: "Ok"
},
_create: function() {
var selectBox = $(this.element),
id = selectBox.attr("id"),
self = this;
selectBox.addClass("ui-combobox");
// create HTML to inject in the DOM
this.addHtml(id, selectBox);
// turn dialog html into a JQuery UI dialog component
this.addDialog(id);
// #todo set proper button height (roughly equal to select height)
$("#" + id + "-button-opendialog").bind("click", function() {
$("#" + id + "-editor-dialog").dialog("open");
}).button();
$("#" + id + "-button-save").bind("click", function() {
self.addOption(id, selectBox);
}).button();
this._init();
return this;
},
addHtml: function(id, selectBox) {
var imgHtml = "";
if (this.options.saveButtonImgUrl != null) {
imgHtml = '<img src="' + this.options.saveButtonImgUrl + '" alt="opslaan" />';
}
$(' <button id="' + id + '-button-opendialog">' +
this.options.openDialogButtonText +
'</button>' +
'<div id="' + id + '-editor-dialog" class="ui-combobox-editor">' +
'<input id="' + id + '-newitem" type="text" /> ' +
' <button id="' + id + '-button-save">' +
imgHtml + ' Opslaan' +
' </button>' +
'</div>').insertAfter(selectBox);
},
addDialog: function(id) {
var options = this.options;
$("#" + id + "-editor-dialog").dialog( {
autoOpen: false,
modal: true,
overlay: {
opacity:0.5,
background:"black"
},
buttons: {
// #todo make button text configurable
"Ok": function() {
$("#" + id + "-editor-dialog").dialog("close");
return;
}
},
title: options.dialogHeaderText,
hide: 'fold'
});
},
addOption: function(id, selectBox) {
var newItem = $("#" + id + "-newitem");
// #todo do not allow duplicates
if (newItem !== null && $(newItem).val().length > 0) {
// #todo iterate over options and get the highest int value
//var newValue = selectBox.children("option").length + 1;
var highestInt = 0;
selectBox.children("option").each(function(i, n) {
var cInt = parseInt($(n).val());
if (cInt > highestInt) {
highestInt = cInt;
}
});
var newValue = highestInt + 1;
var newLabel = $(newItem).val();
selectBox.prepend("<option value='" + newValue + "' selected='selected'>" + newLabel + "</option>");
this._trigger("addoption", {}, newValue);
// cleanup and close dialog
$(newItem).val("");
$("#" + id + "-editor-dialog").dialog("close");
} else {
this._trigger("addoptionerror", {}, "You are required to supply a text");
}
},
_init: function() {
// called each time .statusbar(etc.) is called
},
destroy: function() {
$.Widget.prototype.destroy.apply(this, arguments); // default destroy
// $(".ui-combobox-button").remove();
// $(".ui-combobox-editor").remove();
}
});
Can you please help me?
The message "$ is undefined" means that the function called "$" is not defined anywhere on your page. Thus, when this code is executed, it does not know what to do when this line is encountered.
The $ function is defined by jQuery. Therefore, the message is indicating that it hasn't loaded the jQuery library by the time your code is executed. This could be for a number of things
You haven't included the full jQuery library on your page. This may be because you have forgotten to include it or you have only included some extension to jQuery such as jQuery.UI.
If you are unsure, try adding the following line to the top of your head element in your HTML. Make sure you haven't put any JS before this line:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
You have included jQuery but it is failing to load. This may be because the link you are using is incorrect. Double check by using the Net Panel in Firebug.
jQuery is included on your page, but you have included your own JS first. This won't work because the $ function won't get defined until jQuery is loaded, but your code will try and execute first. Check the order in which you are including your JS and make sure that jQuery is first.
I decided to go AJAX route for the heck of it, mainly to learn it, and to see how it worked. I want to add a page selection for comments that exceed, say, 10 posts.
I am using Codeigniter, and will post what I have so far:
Controller:
public function updatefilters()
{
$this->blurb_model->create_session_filter($_POST['filters']);
$this->blurb_model->get_threads($_POST['pagenum']);
}
Model:
public function get_threads($page = 0)
{
$NEEDPAGEHERE = $page
[fetch threads]
[return threads / count / etc]
}
So my goal is to display the number of pages to the user. This part is done. I have a submit button displayed for each page based on the total count of items returned in the "get_threads" model (code is omitted for relevance sake).
Here is my AJAX/javascript
Focus lies on the updatefilter function. I use the returned thread list to construct HTML and post it within the div. This works fine.
The problem is that I want to reuse the updatefilters() function when the user clicks on a page button...but its not working. I want to pass the value of the submit button into the updatefilter(pagenum) so that it then goes to the controller -> method, and I can do the math, but it does not work.
Javascript:
function updatefilters(pagenum){
// get the selected filters
var html;
var i = 0;
if (!pagenum)
{
pagenum = 0
}
var $selected = $('#selectable').children('.ui-selected');
// create a string that has each filter separated by a pipe ("|")
var filters = $selected.map(function(){return this.id;}).get().join("\|");
$.ajax({
type: "POST",
async: false,
url: 'welcome/updatefilters',
dataType: 'json',
data: { filters: filters, pagenum: pagenum },
success: function(data){
var html = "";
html += "<div id=board>"
html += "<div class='board' id='table'>"
html += "<div id='row'>header here</div>"
var pages = Math.ceil(data['num_threads']/10);
var htmlpage = "<div class='pages'>"
for (i=1 ; i < pages+1 ; i++)
{
htmlpage += "<li><input type='submit' id='page"+i+"' value='"+i+"' onclick='updatefilters(this.value);' /></li>"
}
htmlpage += "<div>"
htmlpage += "</ul>";
htmlpage += "</br></br></br>";
html += htmlpage;
for (i=0 ; i < data['threads'].length ; i++)
{
html += "<div id=row>";
html += " <div id='author' style='background: url("+data['threads'][i].location + ") no-repeat; background-position: center;'><p>"+data['threads'][i].username + "</p></div>";
html += " <div id='arrow'></div>";
html += " <div id='subject' title='"+ data['threads'][i].body +"'>";
html += " "+ data['threads'][i].subject +"<p>Created: "+data['threads'][i].posttime+"</p></div>";
html += " <div id='info'>";
html += " <div id='replies'>" + data['threads'][i].replies_num + "</div>";
html += " <div id='lastpost'>"+ data['threads'][i].lastreply+"</div>";
html += " </div>";
html += "</div>";
}
html += "</div></div>";
$('#board').html(html);
}
});
}
$(function() {
$( "#selectable" ).selectable({
selected: updatefilters
});
getactivesession();
function getactivesession(ev, ui){
var i = 0;
var actfilter, strfilter;
var strfilterarray = new Array();
$.ajaxSetup({cache: false})
$.ajax({
type: "POST",
async: false,
url: 'welcome/getactivesession',
dataType: 'json',
success: function (data){
strfilter = JSON.stringify(data)
strfilterarray = strfilter.split(',')
for (i=0 ; i < strfilterarray.length ; i++) {
strfilter = strfilterarray[i]
strfilter = strfilter.replace(/[\[\]'"]+/g,'');
var strfilterdash = strfilter.replace(/\s+/g, '-')
actfilter = '#'+ strfilterdash
$(actfilter).addClass('ui-selected')
}
updatefilters();
}
});
}
});
This would be an INCREDIBLE learning experience for myself, and a huge help if someone can spot the problem and explain it in an easily understood manner. I am extremely new with javascript and programming in general (which might explain the ugliness of the code).
Thanks!
Modify your selected event callback.
$("#selectable").selectable({
// Here is the event callback signature for reference
selected: function(event, ui) {
updatefilters();
}
});
You were passing an unexpected first parameter to updatefilters function.
I have a form that uses the jQuery UI autocomplete function on two elements, and also has the ability to clone itself using the SheepIt! plugin.
Both elements are text inputs. Once a a value is selected from the first autocomplete (continents), the values of the second autocomplete (countries) are populated with options dependent on the first selection.
My problem is, when clones are made, if the user selects an option from the first autocomplete (continent), it changes the first input values on all clones. This is not happening for the second input (country).
What am I missing?
Note: the #index# in the form id and name is not CFML. I am using PHP, and the hash tags are part of the SheepIt! clone plugin.
Javascript:
<script src="../../scripts/jquery-1.6.4.js"></script>
<script src="../../scripts/jqueryui/ui/jquery.ui.core.js"></script>
<script src="../../scripts/jquery.ui.widget.js"></script>
<script src="../../scripts/jquery.ui.position.js"></script>
<script src="../../scripts/jquery.ui.autocomplete.js"></script>
<script src="../../scripts/jquery.sheepIt.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
function ord(chr) {
return chr.charCodeAt(0);
}
function chr(num) {
return String.fromCharCode(num);
}
function quote(str) {
return '"' + escape(str.replace('"', "'")) + '"';
}
String.prototype.titleCase = function () {
var chars = [" ", "-"];
var ths = String(this).toLowerCase();
for (j in chars){
var car = chars[j];
var str = "";
var words = ths.split(car);
for(i in words){
str += car + words[i].substr(0,1).toUpperCase() + words[i].substr(1);
}
ths = str.substr(1);
}
return ths;
}
function incrementTerm(term) {
for (var i = term.length - 1; i >= 0; i--){
var code = term.charCodeAt(i);
if (code < ord('Z'))
return term.substring(0, i) + chr(code + 1);
}
return '{}'
}
function parseLineSeperated(data){
data = data.split("\n");
data.pop(); // Trim blank element after ending newline
var out = []
for (i in data){
out.push(data[i].titleCase());
}
return out;
}
function loadcontinent(request, response) {
var startTerm = request.term.toUpperCase();
var endTerm = incrementTerm(startTerm);
$.ajax({
url: '/db/continent.php?startkey='+startTerm+'&endkey='+endTerm,
success: function(data) {
var items = parseLineSeperated(data);
response(items);
},
error: function(req, str, exc) {
alert(str);
}
});
}
function loadcountry(request, response) {
var startTerm = request.term.toUpperCase();
var endTerm = incrementTerm(startTerm);
var continent = $('.continent_autocomplete').val().toUpperCase();
$.ajax({
url: '/db/country.php?key=' + continent,
success: function(data) {
var items = parseLineSeperated(data);
response(items);
},
error: function(req, str, exc) {
alert(str);
}
});
}
$('#location_container_add').live('click', function() {
$("input.continent_autocomplete").autocomplete(continent_autocomplete);
$("input.continent_autocomplete").keyup(continent_autocomplete_keyup);
$("input.country_autocomplete").autocomplete(country_autocomplete);
$("input.country_autocomplete").keyup(country_autocomplete_keyup);
$('input.country_autocomplete').focus(country_autocomplete_focus);
});
var location_container = $('#location_container').sheepIt({
separator: '',
allowRemoveLast: true,
allowRemoveCurrent: false,
allowRemoveAll: false,
allowAdd: true,
allowAddN: false,
maxFormsCount: 10,
minFormsCount: 1,
iniFormsCount: 1
});
var continent_autocomplete = {
source: loadcontinent,
select: function(event, ui){
$("input.continent_autocomplete").val(ui.item.value);
}
}
var continent_autocomplete_keyup = function (event){
var code = (event.keyCode ? event.keyCode : event.which);
event.target.value = event.target.value.titleCase();
}
var country_autocomplete = {
source: loadcountry,
}
var country_autocomplete_keyup = function (event){
event.target.value = event.target.value.titleCase();
}
var country_autocomplete_focus = function(){
if ($(this).val().length == 0) {
$(this).autocomplete("search", " ");
}
}
$("input.continent_autocomplete").autocomplete(continent_autocomplete);
$("input.continent_autocomplete").keyup(continent_autocomplete_keyup);
$("input.country_autocomplete").autocomplete(country_autocomplete);
$("input.country_autocomplete").keyup(country_autocomplete_keyup);
$('input.country_autocomplete').focus(country_autocomplete_focus);
});
</script>
HTML:
<div id="location_container">
<div id="location_container_template" class="location_container">
<div id="continent_name">
<label> Continent Name:</label>
<input type="text" id="continent_name_#index#" name="continent_name_#index#" class="continent_autocomplete" />
</div>
<div id="country">
<label> Country:</label>
<input type="text" id="country_autocomplete_#index#" name="country_autocomplete_#index#" class="country_autocomplete" />
</div>
</div>
</div>
select: function(event, ui){
$("input.continent_autocomplete").val(ui.item.value);
}
That code says explicitly to set the value of every <input> with class "continent_autocomplete" to the selected value.
You probably want something like
$(this).val(ui.item.value);
but it depends on how your autocomplete code works.
This line: $("input.continent_autocomplete").val(ui.item.value); is updating all inputs with class continent_autocomplete.
UPDATE:
From jQueryUI Autocomplete Doc:select:
Triggered when an item is selected from the menu; ui.item refers to
the selected item. The default action of select is to replace the text
field's value with the value of the selected item. Canceling this
event prevents the value from being updated, but does not prevent the
menu from closing.
You shouldn't need the select bit at all, it looks like you're simply trying to achieve the default action.
I'm using jquery tabify with 4 tabs and each content same form calling via ajax.(assume form.php)
1st tab everything works fine with the form.
2nd,3rd and 4th tab failed to get input type="text" value
tabify field with (4 tabs here actually I make it short as the code is long):
$(document).ready(function () {
$('#general_information_tab').tabify();
});
function recp(refer,id,plan){
if(plan == 0)
{
$('.stgcontent').load('stage/stage_procedure1.php?plan_id=' + id + '&T_REFERID=' + refer );
}else{
$('.stgcontent').load('stage/new_taskstg.php?plan_id=' + id + '&T_ID=' + refer);
}
<div id="general_tab_content">
<ul id="general_information_tab" class="general_information_tab">
<li class="active"><a href="#one" onClick="recp('1','<?php echo $plan_id; ?>','0')" >Immediate Response Steps</a></li>
<div id="one" class="content_gi">
<div class="stg1">
<img src="images/task/add.ico" height="10px" width="10px" /> Add Task
<div class="stgcontent">
<script type="text/javascript">
recp('1','<?php echo $plan_id; ?>','0');
</script>
</div>
</div>
</div>
in new_taskstg.php
$(function(){
$(".newTaskSubmitBtn").click(function(){
var T_CONTENT = $(".task_name").val();
var T_REFERID = $(".refer").val();
var SAVE_PLAN = $(".plan").val();
var V_ID = $(".vendor").val();
var dataString='T_CONTENT=' + T_CONTENT + '&T_REFERID=' + T_REFERID + '&SAVE_PLAN=' + SAVE_PLAN + '&V_ID=' + V_ID;
alert(T_CONTENT + T_REFERID + SAVE_PLAN + V_ID);
if(T_CONTENT=='' || T_REFERID=='' || SAVE_PLAN=='' || V_ID=='')
{
//ERROR MESSAGE
$(".fail").show();
$(".success").hide();
}
else
{
$.ajax({
type: "POST",
url: "stage/insert.php",
data: dataString,
success: function(data){
//SUCCESS MESSAGE
$(".success").show();
$(".fail").hide();
}
});
}
return false;
});
});
form field code:
<input type="text" name="task_name" class="form_input task_name" />
TEST I DID :
As above var T_CONTENT = $(".task_name").val(); and prompt like this alert(T_CONTENT); what it shows on 1st tab it able to capture it while the 2nd 3rd and 4th tab failed...
Was suspecting multiple instances problem...
Problem Solved. Mian point is to avoid from multiple instances since tabify couldn't differentiate which tab the form is and it takes 4 tabs together. So to solve my case I just use unique id in 4 forms.