I'm trying to select state and cities according to the state (category and subcategory) but is giving a problem with the jquery ui plugin to search the value.
<script type="text/javascript">
$(function(){
$('#cod_estados').change(function(){
if( $(this).val() ) {
$('#cod_cidades').hide();
$('.carregando').show();
$.getJSON('cidades.ajax.php?search=',{cod_estados: $(this).val(), ajax: 'true'}, function(j){
var options = '<option value=""></option>';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].cod_cidades + '">' + j[i].nome + '</option>';
}
$('#cod_cidades').html(options).show();
$('.carregando').hide();
});
} else {
$('#cod_cidades').html('<option value="">– Escolha um estado –</option>');
}
});
});
</script>
http://imageshack.us/g/10/99913872.jpg/
remembering that I am using other javascript code that will be is conflicting?
lap
'jQuery.noConflict () '
instead of $ and then comes the
'(function () {'
but the code ceases to function.
If you want to use jQuery in noConflict mode, you can remap $ within your shortcut domReady call.
jQuery.noConflict();
jQuery(function($) {
// Your code here, access $ as usual
});
Related
I am trying to serialize value of form elements, where my combox is dynamicall added after user click.
I'm getting value from static combobox bt nt from dynamic combobox.
my code:
<script>
//submit data
$(function (a) {
$("form").submit(function (event) {
console.log($(this).serializeArray());
event.preventDefault();
});
});
// populate entree item to select menu
function populate() {
// only declare the variables once
var json = <?php echo $json; ?>, obj, option = ' ', i;
for (var i = 0; i < json.length; i++) {
obj = json[i];
option += '<option value="' + obj.id + '">' + $.trim(obj.title) + '</option>';
}
return option;
}
//add more select box when addmore click
$(function (b) {
var i = 0;
$("a#addmore").click(function () {
i++;
$("p#entree").append('<select name="entree' + i + '">' + populate() + '<select><br>');
});
});
</script>
i got the value when i put my form outside the table. I dnt know why table is blocking the process to get value.
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'm having the below output from an ajax script:
{"DATA":[{"COUNTRYCODE":"1","DESCRIPTION":"USA","COUNTRYID":"211"}, {"COUNTRYCODE":"1","DESCRIPTION":"Canada","COUNTRYID":"37"},{"COUNTRYCODE":"1","DESCRIPTION":"Dominican Republic","COUNTRYID":"224"},
I am trying to populate a select menu with info from this JSON data:
<script type="text/javascript" charset="UTF-8">
$.getJSON(
'getcountries.php',
function(data) {
var items = [];
$('#country').append(data);
$.each(data['DATA'], function(key, val) {
$.each(val, function(key, value) {
console.log(value);
});
});
}
);
Issue with it is that the $('#country').append(data) (or append(data['DATA']) always returns error "Value does not implement interface Node."
Could anyone point out how I could get the specific JSON data I have into the select script?
.append() only accepts HTML string, DOM Element, or jQuery Object
See: http://api.jquery.com/append/
I assume this is the result you actually want.
var data = {"DATA":[{"COUNTRYCODE":"1","DESCRIPTION":"USA","COUNTRYID":"211"},{"COUNTRYCODE":"1","DESCRIPTION":"Canada","COUNTRYID":"37"},{"COUNTRYCODE":"1","DESCRIPTION":"Dominican Republic","COUNTRYID":"224"}]};
var $select = $('#country').empty();
$select.append(
data.DATA.map(function (el, i) {
return $('<option>')
.val(el.COUNTRYID)
.text(el.DESCRIPTION)
.data('DATA', el); // in case you also want to access its COUNTRYCODE
})
);
jsFiddle: http://jsfiddle.net/terryyounghk/ZshG4/
DEMO: http://jsfiddle.net/q5Q3d/
var a = {
"DATA":[
{"COUNTRYCODE":"1","DESCRIPTION":"USA","COUNTRYID":"211"},
{"COUNTRYCODE":"1","DESCRIPTION":"Canada","COUNTRYID":"37"},
{"COUNTRYCODE":"1","DESCRIPTION":"Dominican Republic","COUNTRYID":"224"}
]
}
$.each(a.DATA, function(idx, val){
var option = "<option value='" + val.COUNTRYID + "'>" + val.DESCRIPTION + "</option>";
$('select').append(option);
});
How would I dynamically update the end part of an img URL based on a drop down selection?
for example when blue is selected the filename before .jog would get filled in with the word blue. It's using a css and I can't add any ids to the :
<img src="www.mysite.com/blue.jpg">
<select>
<option>green</option>
<option>blue</option>
</select>
$(document).ready(function() {
$('select').change(function(){
var src = $(':selected', this).text()
$('img').attr('src', location.hostname + "/" + src + '.jpg');
});
});
$(function () {
$('select').change(function () {
$(this).parent().attr('src', location.hostname + "/" + this.val() + '.jpg');
});
});
Try this:
$(function() {
var $img = $('img'), $select = $('select').on('change keyup', function() {
$img.attr('src','http://www.mysite.com/' + $select.find(':selected').html() + '.jpg')'
});
});
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.