jQuery text in div to input in admin - php

One page I have articles with prices. I would like to do administration. When I am administrator and I would click on price input field text would show.
My code for this:
$('#priceBig').click(function() {
var originalelement = this;
var dishID = this.id;
var currentText = $.trim($(this).text())
$(this).hide().before('<input class="input" id="'+dishID+'" style="padding:3px; text-align:left; font-size:17px; width:50px;" type="text" value="'+currentText+'"/>');
$('.input').live('change', function() {
var picaID = this.id;
var price = $(this).val();
var thisparam = this;
$.post('<?= site_url('dish/changePicaBigPrice') ?>',{ picaID : picaID, price:price},
function(data) {
$(thisparam).remove();
$(originalelement).text(price).fadeIn(1000);
},'text');
});
});
But this doesn't work because jQuery store all originalelement objects and every change of price change all originalelements which were clicked before...
I hope I was clear what I want to do.
I would like to click on price, change and one I go on other price

I believe my old answer won't work.
New tactics - save the old ID in an attribute on the new input you create, and use it in the success handler.
$('#priceBig').click(function() {
var currentText = $.trim($(this).text())
var input = $('<input />')
.addClass('input')
.attr('type', 'text')
.attr('orig-id', $(this).attr('id'))
.val(currentText)
.bind('change', function () {
var t = $(this);
var price = t.val();
var origID = t.attr('orig-id');
$.post('<?= site_url('dish/changePicaBigPrice') ?>',{ picaID : origID, price:price},
function(data) {
t.remove();
$('#' + origID).text(price).fadeIn(1000);
},'text');
});
$(this).hide().before(input);
});
EDIT: fixed typo in var origID = t.attr('orid-id');
EDIT: change picaID to origID in the $.post parameters

Related

Get index value from dropdown form

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>

Display information based on the autocomplete selected value

I have dynamic text field at Demo JSFiddle and I have done the autocomplete part for my item part no.
$ (document).ready(function() {
$("#addField").click(function() {
var intId = $("#buildyourform div").length + 1;
var fieldWrapper = $("<div id=\"field" + intId + "\"/>");
var fpartNo = $("<input type=\"text\" name=\"erfq_partNo[]\" class=\"partNumber\"/>");
var fDescription = $("<input type=\"text\" name=\"erfq_desc[]\" disabled/>");
var fPrice = $("<input type=\"text\" name=\"erfq_price[]\" disabled style=\"width:80px\"/>");
// remove textboxes and dropdown boxes
var removeButton = $("<input type=\"button\" class=\"remove\" value=\"-\" />");
removeButton.click(function() {
$(this).parent().remove();
});
fieldWrapper.append(fpartNo);
fieldWrapper.append(fDescription);
fieldWrapper.append(fPrice);
fieldWrapper.append(removeButton);
$("#buildyourform").append(fieldWrapper);
$(".partNumber").autocomplete({
minLength:1,
source: 'readPart.php',
select: function(event, ui){
var selected = ui.item.value;
}
});
});
});
readPart.php
$searchTerm = $_GET['term'];
$getPartSQL = base_executeSQL("SELECT * FROM eitem_item where eitem_item_part_no LIKE '%".$searchTerm."%' ORDER BY eitem_item_part_no" );
while($Partdata_row = base_fetch_array($getPartSQL))
if (base_num_rows($getPartSQL)!= 0)
{
$data[] = $Partdata_row['eitem_item_part_no'];
}
echo json_encode($data);
The first text field is uses for entering the part No.
My question is once the part no has been entered, the other relevant information (description and price) will be displayed at the other readonly text fields which the data are extract from my database. I have no idea what to continue with this select: function(event, ui){. Any help will be appreciated.
well, if you want to get the data on the basis of part # from database you can trigger an ajax call on blur of text box part number.
you can do something like this
$("#partNum").blur(function(){
var part = $("#partNum").val();
$.ajax({
type: 'get',
url:'/echo/js/?js='+part, //url to your database fetcher code.
complete: function (response) { //response contains what you got from pap page
$('textarea#des').val(response.responseText); //set textarea and textbox value popping out from db file
}
});
});
Here is HTML snippet to this request.
<input type = 'text' id = 'partNum' name = 'parts' />
<textarea id = "des" name = 'description' disabled></textarea>
FIDDLE
this will work on blur means when clicked outside the textbox. But if you want to get real time data(while user is typing) then you've to bombard the ajax requests on keyup event.
something like this:
$("#partNum").keyup(function(){
var part = $("#partNum").val();
$.ajax({
type: 'get',
url:'/echo/js/?js='+part,
complete: function (response) {
$('textarea#des').val(response.responseText);
}
});
});
FIDDLE here
Hope this will help.

jQuery Confirm on click of button

I have the following code that works in conjunction with a "value" that is given from data inputted into an input box.
How would I alter this code to just send the data - product_details['id'] without the need for input data?
Example jQuery Code:
$('body').on("click", "#product_change_set_order_btn", function (e) {
e.preventDefault();
var box = $("#product_set_order_box");
var id = box.data("id");
var url = box.data("url");
var data_array = {
id : id,
new_sort : box.val(),
};
if($.trim(box.val()) != "")
{
ajaxCall(url, data_array, null, "product_set_order");
alert("Your Sort Order Has Been Set");
}
});
HTML Button:
Delete <?php echo $product_details['name']; ?>
$('body').on("click", "#product_change_set_order_btn", function (e) {
e.preventDefault();
var box = $("#product_set_order_box");
var id = box.data("id");
var url = box.data("url");
var data_array = {
id : id,
new_sort : box.val(),
};
ajaxCall(url, data_array, null, "product_set_order");
alert("Your Sort Order Has Been Set");
});

Jquery Select list items in loop using keyup and key down

I am trying to make autosuggest in Jquery,ajax and json to search cities when user register to website.
So far I am able to get results from database.And i appended to list.but now i need to select data using up down and enter keys.
Key down event is adding class to first city. But I want to loop through all results using key up and down and add value to city textbox if user hits enter. I limit data by 5 in php so 5 results are coming in list item.
Here is my code:
$('#city').keyup(function (event) {
var input_query = $(this).val();
$.post("get_city.php", {
"query": input_query
}, function (data) {
$('#cityres').html("");
$.each(data, function (i, item) {
$('#cityresults').append("<li>" + item.city + "</li>");
});
}, "json");
//below code is for key event
var key = gtKeycode(event);
if (key == 40) {
// I am not sure i need to do this way
$('li').first().addClass('SelectedCity');
}
});
function gtKeycode(e) {
var code;
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
return code;
}
i think i have now the solution for your problem hope this will help you..!
I made a php file that echo out json encode just list this:
//PHP "action.php?action=show"
e.g $option[] = array(
'option0'=>".Choose an option",
'option1'=>'somepage1',
'option2'=>'somepage2',
'option3'=>'somepage3');
echo json_encode(array('options'=>$option));
I made up html that will be the handler of the output, then will append
<select class="myoptions">
</select> | <span class="optcap"></span>
JS
function selectedOption()
{
var myoptions = $(".myoptions");
$.ajax({
type:'GET',
url:'action.php?action=show',
dataType:'JSON',
success:function(data){
if(data.s==1){
myoptions.empty();
$.each(data.options, function(x,val){
myoptions.append("<option class='option' value='"+val.option0+"'>"+val.option0+"</option>"
+"<option class='option' value='"+val.option1+"'>"+val.option1+"</option>"
+"<option class='option' value='"+val.option2+"'>"+val.option2+"</option>"
+"<option class='option' value='"+val.option3+"'>"+val.option3+"</option>");
});
}
}
});
}
$(document).ready(function(){
selectedOption();
$(".myoptions").keyup(function(){
var option = [];
$("option.option:selected").each(function(x){
option[x] = $(this).val();
});
$(".optcap").html("["+option+"]");
});
});

Why is jQuery autocomplete updating all elements on my cloned form?

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.

Categories