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.
Related
I have a dropdown that is filled by a database and everything works well. However I want to pass a parameter to php based on the value of the dropdown which I can do. If I force the var to have a particular number it gets the corresponding item in the database. I'm having a problem to get the value of a dropdown. I've tried all the suggestions here in the forum and nothing works in this particular area of my code. I have it working on another piece of my code but not on this particular one and I don't know why. Here is my code:
<select id="servicos" onChange="return selectServ();">
<option value="item" class="itemoption">Serviço</option>
This is the code that is not working:
function selectServ() {
var e = document.getElementById("servicos");
var idserv = e.options[e.selectedIndex].value;
$.getJSON("http://ib.esy.es/gestao/_php/servicos_threadingpreco.php", { serv: idserv }, null).then(function(data) {
console.log(data);
var tr = data
for (var i = 0; i < data.length; i++) {
var tr = $('<tr/>');
// Indexing into data.report for each td element
$(tr).append("<td>" + data[i].preco + "</td>");
$('.table1').append(tr);
}
});
}
If I put
var idserv = "1"
It is working, however this:
var e = document.getElementById("servicos");
var idserv = e.options[e.selectedIndex].value;
Is not getting a value. The console log gives:
selectdynamicpreco.html:76 Uncaught TypeError: $(...).value is not a function
You should consider using jQuery to get the value of the dropdown:
$('#dropdown').val() will give you the selected value of the drop down element. Use this to get the selected options text.
$("#dropdown option:selected").text();
Should get you the text value of the dropdown.
This is working on another piece of the code
<script>
function selectCat(){
$('#servicos').change(function() {
$('#demo').text($(this).find(":selected").text());
});
//for textbox use $('#txtEntry2').val($(this).find(":selected").text());
var e = document.getElementById("categoria");
var servSelected = e.options[e.selectedIndex].value;
var url = "";
var items="";
if(servSelected === "1"){
url = "http://ib.esy.es/gestao/_php/servicos_threading.php";
}
if(servSelected === "2"){
url = "http://ib.esy.es/gestao/_php/servicos_sobrancelhas.php";
}
if(servSelected === "3"){
url = "http://ib.esy.es/gestao/_php/servicos_manicure.php";
}
$.getJSON(url,function(data){
$.each(data,function(index,item)
{
items+="<option value='"+item.ID+"'>"+item.servico+"</option>";
});
$("#servicos").html(items);
});
};
</script>
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);
});
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
});
I am new to json n php..
using code below to fetch data for radio button check box and text box with json . It is working fine but I donno how to populate data in select box in the same way .
function get_input_value(name, rval) {
//console.log(name + ' && ' + rval);
var i = 0;
var chk = $('input[name="' + name + '"]');
while (i < chk.length) {
//console.log($(chk[i]));
if ($(chk[i]).val() == rval) {
//console.log('loopvalue => ' + i);
$(chk[i]).prop('checked', true);
}
i++;
}
}
function loadJson (table, id) {
$.get("json-object.php", {'table': table, 'id':id}, function (data) {
console.log(data);
$.each(data, function (k, v) {
if ($('input[name="'+k+'"]').is('input[type="text"]')) {
$('input[name="'+k+'"]').val(v);
}
if ($('select[name="'+k+'"]').is('input[type="radio')) {
get_input_value(k,v);
}
if ($('input[name="'+k+'"]').is('input[type="checkbox"]')) {
get_input_value(k,v);
}
console.log(k+' ==> '+v);
});
}, 'json');
}
Your code is just setting value of text boxes and auto select certain checkboxes based on the PHP output.
To have it auto set the proper item in drop down lists as well you need to change this wrong code:
if ($('select[name="'+k+'"]').is('input[type="radio')) {
get_input_value(k,v);
}
To this:
$('select[name="'+k+'"]').val(v);
(No point to check type of <select> since it got none)
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.