JQuery for-loop with variable - php

I have a table out of different MySQL data. I want to highlight cells with the same ID in it on hover. I did that with a simple jQuery, the script is almost working but you see I've got the var nr and want the integer i to be added to the class string. What is my mistake, why isn't it working? If you change the var nr = '.id_' + i; to a static variable like var nr = '.id_2'; it is working.
for (i = 0; i < 10; i++) {
var nr = '.id_' + i;
var bgcol = $(nr).css('backgroundColor');
$(nr).hover(
function(){
$(nr).css({"background":"yellow"});
},function(){
$(nr).css({"background":bgcol});
});
}
http://jsfiddle.net/Nkdny/210/
Solution, thanks to Karl-André Gagnon: http://jsfiddle.net/Nkdny/215 Look in the comments for details.

You're missing an echo in front of your php statement.
<?php echo $amount; ?>

Related

Fixing jQuery plugin to handle duplicating nested fields with unique ID's

I have a quick question for you guys here. I was handed a set of lead generation pages and asked to get them up and running. The forms are great, expect for one small issue... they use the jQuery below to allow users to submit multiple instances of a data set by clicking an "Add another item" button. The problem is that the duplicated items are duplicated EXACTLY. Same name, id, etc. Obviously, this doesn't work when attempting to process the data via PHP, as only the first set is used.
I'm still learning jQuery, so I was hoping that someone could point me in the right direction for how to modify the plugin below to assign each duplicated field an incremental integer on the end of the ID and name assigned. So, the fields in each dataset are Role, Description, Age. Each additional dataset will use the ID & name syntax of fieldname#, where # represents numbers increasing by 1.
Thanks in advance for any advice!
/** https://github.com/ReallyGood/jQuery.duplicate */
$.duplicate = function(){
var body = $('body');
body.off('duplicate');
var templates = {};
var settings = {};
var init = function(){
$('[data-duplicate]').each(function(){
var name = $(this).data('duplicate');
var template = $('<div>').html( $(this).clone(true) ).html();
var options = {};
var min = +$(this).data('duplicate-min');
options.minimum = isNaN(min) ? 1 : min;
options.maximum = +$(this).data('duplicate-max') || Infinity;
options.parent = $(this).parent();
settings[name] = options;
templates[name] = template;
});
body.on('click.duplicate', '[data-duplicate-add]', add);
body.on('click.duplicate', '[data-duplicate-remove]', remove);
};
function add(){
var targetName = $(this).data('duplicate-add');
var selector = $('[data-duplicate=' + targetName + ']');
var target = $(selector).last();
if(!target.length) target = $(settings[targetName].parent);
var newElement = $(templates[targetName]).clone(true);
if($(selector).length >= settings[targetName].maximum) {
$(this).trigger('duplicate.error');
return;
}
target.after(newElement);
$(this).trigger('duplicate.add');
}
function remove(){
var targetName = $(this).data('duplicate-remove');
var selector = '[data-duplicate=' + targetName + ']';
var target = $(this).closest(selector);
if(!target.length) target = $(this).siblings(selector).eq(0);
if(!target.length) target = $(selector).last();
if($(selector).length <= settings[targetName].minimum) {
$(this).trigger('duplicate.error');
return;
}
target.remove();
$(this).trigger('duplicate.remove');
}
$(init);
};
$.duplicate();
Add [] to the end of the NAME attribute of the input field so for example:
<input type ="text" name="name[]"
This way your $POST['name'] will hold an array of strings. For that element. It will be an array with keys that are numbers from 0 to however many items it holds.

Processing json where the number of json array is dynamic

I have a json response from php to ajax. The thing is depending on the value entered in a text box the number of json arrays vary. Example: sometimes it may return {"count1":10, "ccc1":30} and sometimes like this {"count1":10, "ccc1":32, "count2":40, "ccc2":123,"count3":32,"ccc3":21}. I extract the value in jquery this way:
success: function(response){
var count = response.count1;
//do something
}
But now since the number of counts are different I used a loop. Question is I can figure out how many of them I am receiving but how can I process them? The var count = response.count needs to be specific right? I cannot just concate any strings like this:
var count = 0;
while(something){
count = count + 1;
var str = "count"+count;
var whatever = response.str;
}
So, can someone please help me with a suitable solution in this case?
You are on the right track there. Something like this should work for you.
var i = 1;
while(response['count' + i]) {
var count = response['count' + i++];
}
You can access the properties as if they were array indices. so response['count'+i] works.
Loop through all properties and add them in a variable like following.
var response = { "count1": 10, "ccc1": 32, "count2": 40, "ccc2": 123, "count3": 32, "ccc3": 21 };
var count = 0;
for (var prop in response) {
if (prop.startsWith('count'))
count += response[prop];
}
console.log(count);
To retrieve all values use jQuery $.each function.
var data_tmp = '{"count1":10, "ccc1":32, "count2":40, "ccc2":123,"count3":32,"ccc3":21}';
var data = $.parseJSON(data_tmp);
$.each(data, function(k,val){
if(k.toLowerCase().indexOf("count") >= 0){
$('.wr').append('<div>' + val + '</div>')
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="wr"></div>
success: function(response){
var count = response.count1;
var object = JSON.parse(response);
alert(object.length);
for (i = 0; i < object.length; i++) {
console.log(object[i]);
}
}

How to get variable from url for .js file?

Example: Suppose the current page url(window.location.href) is http://example.com/page.html
The html page source code is...
<html><head></head><body>
<script src="http://example.com/script.js?user=Ankit&ptid=18"></script>
</body></html>
Now I need to use 'src' variables in script.js
And the script file script.js should return
var a="Ankit"
var b="18"
Can we use something like echo $_GET like in php?
Found this here. If you're using jQuery, this should be helpful.
function getURLParameter(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
This is a javascript function that will return the value in the url of a parameter that you pass to it. In this case, you would call it with
var a = getURLParameter("user");
var b = getURLParameter("ptid");
EDIT: I misinterpreted the original version of your question as asking about getting parameters to the .html page being loaded. I just tested this solution, and it does not work within the .js file itself. However, if you declare your variables in the .js file, and place this in the onLoad event, removing var from in front of a and b, it should assign the variables correctly.
Maybe outdated but a nice piece of code and would exactly do what was asked for in OP
// Extract "GET" parameters from a JS include querystring
function getParams(script_name) {
// Find all script tags
var scripts = document.getElementsByTagName("script");
// Look through them trying to find ourselves
for(var i=0; i<scripts.length; i++) {
if(scripts[i].src.indexOf("/" + script_name) > -1) {
// Get an array of key=value strings of params
var pa = scripts[i].src.split("?").pop().split("&");
// Split each key=value into array, the construct js object
var p = {};
for(var j=0; j<pa.length; j++) {
var kv = pa[j].split("=");
p[kv[0]] = kv[1];
}
return p;
}
}
// No scripts match
return {};
}
Source: James Smith - Extract GET Params from a JavaScript Script Tag
I know it's an old post, but as I was looking for something like that I came across it. The very simple solution I finally adopted is the following one:
<html><head></head><body>
<script>
var a = "Ankit";
var b = 18;
</script>
<script src="http://example.com/script.js?user=Ankit&ptid=18"></script>
</body></html>
If you absolutely want to complicate your life and use Lahmizzar's solution, I would recommend to give an id to your tag script, which avoids a greedy function.
HTML :
<script src="http://example.com/script.js?user=Ankit&ptid=18" id="myScript"></script>
JS :
function getParams(script_id) {
var script = document.getElementById(script_id);
if(script) {
// Get an array of key=value strings of params
var pa = script.src.split("?").pop().split("&");
// Split each key=value into array, the construct js object
var p = {};
for(var j=0; j<pa.length; j++) {
var kv = pa[j].split("=");
p[kv[0]] = kv[1];
}
return p;
}
// No scripts match
return {};
}
getParams("myScript");

run js function on dynamically created select menu

i have this code:
This is the addOptions function
<script>
var values = <?php
$sql="SELECT * FROM billing_sagenominalcodes order by code ASC";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$nominalcodes = array();
while($result=mysql_fetch_assoc($rs))
{
$nominalcodes[] = $result['code'];
}
echo json_encode($nominalcodes);
?>;
var names = <?php
$sql="SELECT * FROM billing_sagenominalcodes order by code ASC";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$nominalcodesname = array();
while($result=mysql_fetch_assoc($rs))
{
$nominalcodesname[] = $result['code'] . ' - ' . $result['name'];
}
echo json_encode($nominalcodesname);
?>;
function addOptions(select, values)
{
for (var i=0, iLen=values.length; i<iLen; i++)
{
select.appendChild(new Option(names[i],values[i]));
}
}
</script>
then the add row function
<script language="javascript" type="text/javascript">
var i=1;
function addRow()
{
var tbl = document.getElementById('table1');
var lastRow = tbl.rows.length;
var iteration = lastRow - 1;
var row = tbl.insertRow(lastRow);
var sagenominalcodeCell = row.insertCell(3);
var elSageNominalCode = document.createElement('select');
elSageNominalCode.type = 'select';
elSageNominalCode.name = 'sagenominalcode' + i;
elSageNominalCode.id = 'sagenominalcode' + i;
sagenominalcodeCell.appendChild(elSageNominalCode);
i++;
}
</script>
and then the HTML
<select name="sagenominalcode" id="sagenominalcode">
<script>addOptions(document.getElementById('sagenominalcode'), values);</script>
</select>
<input type="button" value="Add" onclick="addRow();" />
it adds the new rows ok but its no populating the select menu with the addOptions function.
is there any way to make it run that function once the new row/select menu has been dynamically created and then the same for all the others created when the addRow function is called?
So, reading your code a little bit more, I see you have
new Option(names[i],values[i])
My question to you is what does new Option return? I don't see code for it anywhere in your question.
Take a look at the spec for appendChild :
https://developer.mozilla.org/en-US/docs/DOM/Node.appendChild
It needs an element passed in. What you want to do is make a new element using the createElement() function like so:
var option = document.createElement("option");
And then edit the inner html to be what ever you need like this:
option.innerHTML = "your option content here";
Then pass the element in to the append child function:
appendChild(option);
Use jQuery here instead of straight js. My bet is that your listener for click is only bound to the items that are present on the page when it is created. If you set up a listener through jQuery, then it will fire even on components that are dynamically added.
Also from a code structuring stand point, be very careful about writing js with php. Although it sounds fun (like doing drugs in highschool) it is dangerous, frustrating and leads to untestable code (like doing drugs in highschool does).

Total value with JavaScript and PHP

I'm using this form script to automatically calculate totals. Now I need to get that total and add it to a database via PHP and MySQL.
I don't know how to 'name' the totalPrice div, so that I can pass its value to the database.
Edit:
I'm still not getting results in the database. I'm now using $_POST[totalValue] for the field set and totalPrice for the field name.
HTML:
<div id="totalPrice"></div></div>
<input type="hidden" name="totalValue" id="totalValue" />
JavaScript:
$("#vendorform").submit(function(){
var totalValue = document.getElementById('totalValue');
totalValue.value = vendorPrice; //the actual total value
});
function calculateTotal()
{
//Here we get the total price by calling our function
//Each function returns a number so by calling them we add the values they return together
var vendorPrice = getTentPrice() + getElecPrice() + getPropanePrice();
//display the result
var divobj = document.getElementById('totalPrice');
divobj.style.display='block';
divobj.innerHTML = "Total Price Vendor $"+vendorPrice;
}
The vendorPrice variable is not available outside the scope of the function calculateTotal. You could make vendorPrice a global variable, but that's a bit of an ugly hack.
Alternatively, you could do something like this:
function calculateTotal()
{
var vendorPrice = getTentPrice() + getElecPrice() + getPropanePrice();
var divobj = document.getElementById('totalPrice');
divobj.style.display='block';
divobj.innerHTML = "Total Price Vendor $"+vendorPrice;
return vendorPrice; // <-- ADDED
}
And this:
$("#vendorform").submit(function(){
var totalValue = document.getElementById('totalValue');
totalValue.value = calculateTotal(); // <-- CHANGED
});
This way, you assign the value that is now returned by calculateTotal() to totalValue.value.
By the way: since it looks like you're already using jQuery, you can rewrite your code like this:
// [...]
var divobj = $('#totalPrice');
divobj.css('display', 'block');
divobj.text("Total Price Vendor $"+vendorPrice);
// [...]
var totalValue = $('#totalValue');
totalValue.val(calculateTotal());
This makes it a bit more readable (although that's debatable) and a bit more cross-browser reliant. jQuery has great docs (e.g. the documentation on .val()). If you're going to use jQuery more often I can highly recommend bookmarking the docs and skimming through them.
Using jQuery:
$("#cakeform").submit(function(){
var price = $("#totalPrice").text().replace(/[\s\S]+\$/,"")
$("#cakeForm").append('<input type="hidden" name="estimated_price" value="' + price + '" />')
})
But as #nick-rulez pointed out, is usually not a good idea to save calculated values in a database.
You can set the value to:
<input type="hidden" name="totalValue" id="totalValue" />
Which you have to put inside your <form>...</form>.
When you submit the form you're going to receive input's value.
You can set the value to the hidden field with this sniped:
JS
var totalValue = document.getElementById('totalValue');
totalValue.value = myValue; //myValue is the total
JavaScript:
function calculateTotal()
{
var Price = getTshirtPrice() + getTshirtType() + getTshirtColour() +
getTextColour();
var divobj = document.getElementById('textbox');
divobj.value = "Total Price For the T-shirt: £"+Price;
return Price;
}
HTML:
<div id="totalPrice"><input type="text" id="textbox"></div>
Do that. It works perfectly fine.

Categories