How can I use input Box ID from PHP to JavaScript? - php

My JavaScript function works fine, but I have problems getting different ids from the PHP input box.
JavaScript
window.onload = function()
{
new JsDatePick({
useMode:2,
target:"inputField1", //HERE I WOULD LIKE TO PASS DIFFERENT ID ex. "inputField1"+ "i"
dateFormat:"%Y-%M-%d",
yearsRange:[1978,2120],
limitToToday:false,
cellColorScheme:"beige",
imgPath:"main/img/",
weekStartDay:1
});
My PHP input box for loop
<div class = "start_date" >
<strong><label for="start_date">Start Date</label></strong>
<br/><br/>
<?php
for($k=1;$k<=$textboxindex;$k++)
{
echo "<input type=\"text\" class='textboxsize' id= \"inputField1\" name=\"start_date[]\" value=\"$start_date\" />";
echo "<br/>";
}
?>
</div>
It works fine, but I would like to have different ID names to use in the JavaScript function. Any ideas?
This doesn't work...
echo "<input type=\"text\" class='textboxsize' id= \"inputField+$k\" name=\"start_date[]\" value=\"$start_date\" />";
Any help will be appreciated.

It's most likely with JsDatePick widget. Its target parameter takes a single ID of an element, therefore you'd have to wrap the JS code in a loop and initiate a separate instance of the widget for each field ID.
Assuming your input field indexing starts with 1:
window.onload = function()
{
var i = <?=$totalNumberOfInputs;?>
for(j=1;j<=i;j++) {
new JsDatePick({
useMode:2,
target:"inputField" + j, //HERE I WOULD LIKE TO PASS DIFFERENT ID ex. "inputField1" + j
dateFormat:"%Y-%M-%d",
yearsRange:[1978,2120],
limitToToday:false,
cellColorScheme:"beige",
imgPath:"main/img/",
weekStartDay:1
});
}
}
You don't need to put the + sign to concatenate strings within double quotes (it's dot, by the way).

Change:
id= \"inputField+$k\" name=...
To:
id=\"inputfield$k\" name=...
What is screwing it up is the "+" sign. PHP uses "." to concatenate strings. ECHO out $k properly and you shouldn't have any trouble

//this is doesn't work
echo "<input type=\"text\" class='textboxsize' id= \"inputField$k\" name=\"start_date[]\" value=\"$start_date\" />";
just remove that + sign.

Related

jQuery don't work inside PHP echo

Value of $qty is in my database. I've read few similar questions and I already added $(document).ready but it's still not working.
echo "<div class='sp-quantity'>
<div class='sp-minus fff'><a class='ddd' href='#' data-multi='-1'>-</a></div>
<div class='col-xs-3 sp-input'>
<input type='text' class='quntity-input form-control qty' pid='$bookid' id='qty-$bookid' value='$qty'/>
</div>
<div class='sp-plus fff'><a class='ddd' href='#' data-multi='1'>+</a></div>
</div>";
echo "<script>";
echo "$(document).ready(function(){";
echo "$('.ddd').on('click', function() {";
echo "var $button = $(this);";
echo "var $input = $button.closest('.sp-quantity').find('input.quntity-input');";
echo "$input.val(function(i, value) {";
echo "return +value + (1 * +$button.data('multi'));";
echo "});";
echo "});";
echo "});";
echo "</script>";
You're getting your PHP & Javascript variable syntax confused. PHP uses $ as the start of every variable name. Javascript doesn't, plus jquery uses $ in a special way. On top of that, PHP does automatic string substitution of anything starting with a $ that can be a valid variable name as long as the string uses " instead of '. So the result of your code is:
<script>
$(document).ready(function(){
$('.ddd').on('click', function() {
var $button = $(this);
var $input = $button.closest('.sp-quantity').find('input.quntity-input');
$input.val(function(i, value) {
return +value + (1 * +$button.data('multi'));
});
});
});
</script>
$button and $input will be substituted with the contents of the PHP variables of those names. I suspect that's not what you want - though I have done things like that at times myself. What I think you want is:
<script>
$(document).ready(function(){
$('.ddd').on('click', function() {
var button = $(this);
var input = button.closest('.sp-quantity').find('input.quntity-input');
input.val(function(i, value) {
return +value + (1 * + button.data('multi'));
});
});
});
</script>
Two other suggestions:
1 - If you have absolutely no PHP values within a bunch of Javascript (or plain HTML) echo lines, you can exit out of PHP code mode by using ?> and not use echo and avoid any issues of string substitution.
2 - Personally, I prefer using {$string} for my variables inside strings as it makes the substitution more obvious and sometimes less ambiguous.

Unable to get values of checkboxes with jQuery

I am trying to get all selected checkbox values with JavaScript, but I have not been able to accomplish it until now. This is what I have tried. What am I doing wrong?
JS:
var femaleMatches = [];
$(".selectFemaleService:checked").each(function() {
console.log('found a female');
femaleMatches.push(this.value);
});
PHP:
echo "<div class='checkbox'><label><input id='selectFemaleServices' name='selectFemaleServices' type='checkbox' value='$id'>$description</label></div>";
Your jQuery is selecting by class, yet your checkboxes have an id. If there are multiple checkboxes you should change the id to class so you don't end up with duplicates.
echo "<div class='checkbox'>"
. "<label>"
. "<input class='selectFemaleServices' name='selectFemaleServices' type='checkbox' value='$id'>$description"
. "</label>"
. "</div>";
You should use the input name instead of the class to select it using jQuery
$("input[name='selectFemaleServices']:checked").each(function() {
I think this will help, the included fiddle shows how it does populate the array. You might need to change the way in which it is adding / or add remove functionality, but this will get you the value in the array
var femaleMatches = [];
$(".selectFemaleService").click(function() {
if($(this).is(':checked')){
console.log('found a female');
femaleMatches.push($(this).val());
console.log(femaleMatches);
}
});
http://jsfiddle.net/8uZ3e/
try this:
var femaleMatches = [];
$(".selectFemaleService").each(function() {
if(this.checked){
console.log('found a female');
femaleMatches.push(this.value);
}
});
http://jsfiddle.net/JPvwJ/

Can only read first value from form list using jQuery and PHP

I´m trying to build a shopping cart in jQuery and PHP but cannot read values from form list.
When trying to get value from the form that is submitted i only get values from
the first form in the list view.
Please look at behaviour here:
http://www.adlertz.se/index.php?op=prodlist&katID=9&sidemenu=menushop
Click buy on ex. the middle, you get value from first.
Please help me with this, i have benn looking for solution for three days.
Probably a simple problem but i cant find the answer anywhere :| !!!.
Many thanks in advance!
function prodlist(){
$katID = $_GET['katID'];
$sql = mysql_query("SELECT * FROM shop_prod WHERE kategoriID=$katID");
while ($rad=mysql_fetch_array($sql)) {
echo "<div class=\"shop_prod_list\">";
echo "<div class=\"shop_prod_list_tmb\"><img src=\"shop/images/prod_images_tmb/".$rad['prodID'].".png\" alt=\"\"></div>";
echo "<form id=\"addcartform\" class=\"addcartform\" method=\"post\">";
echo "<input type=\"hidden\" name=\"prodID\" id=\"prodID\" value=\"".$rad['prodID']."\" />";
echo "<input type=\"submit\" class=\"shop_prod_list_kundvagn\" value=\"\" id=\"addcart\"/>";
echo "</form>";
echo "</div>";
}
echo "<div id=\"search_results\"></div>";
}
$(document).ready(function(){
$(".addcartform").click(function(e){
e.preventDefault();
addcart();
});
});
function addcart(){
var prodID=(this).document.getElementById('prodID').value; <-(Reads value but only the first)
$.post("functions/cart.php", {prodID : prodID}, function(data){
if (data.length>0){
$("#search_results").show();
$("#search_results").html(data);
}
})
}
<?php
include "db_config.php";
include "db_connect.php";
$prodID = strip_tags(substr($_POST['prodID'],0, 100));
$prodID = mysql_escape_string($prodID);
echo $prodID ." is added.";
?>
Use class instead of id
echo "<input type=\"hidden\" name=\"prodID\" class=\"prodID\" value=\"".$rad['prodID']."\" />";
Send the element which was clicked to your function
$(".addcartform").click(function(e){
e.preventDefault();
addcart(this); //this line
});
Then use that element to find the input with your class
function addcart(element){
var prodID = $(element).find('.prodID').val(); //Get val of clicked item
$.post("functions/cart.php", {prodID : prodID}, function(data){
if (data.length>0){
$("#search_results").show();
$("#search_results").html(data);
}
})
Although i would use only one button, without a form like this.
Php:
echo "<button name='prodID' class='shop_prod_list_kundvagn addcart' data-prodid='".$rad['prodID']."' value='Add' />";
Javascript:
$(".addcart").click(function(e){
e.preventDefault();
var prodID = $(this).data('prodid');
$.post("functions/cart.php", {prodID : prodID}, function(data){
if (data.length>0){
$("#search_results").show();
$("#search_results").html(data);
}
});
});
The code you use to pick out the value is not correct.
In theory you are supposed to have unique id's - so thats your first issue to resolve.
Secondly you need to find a better way to locate the value you are interested in.
My suggestion would be to add a button within each form and call it 'submit'.
On this button you add a data attribute that contains the product id.
With an onclick handler on this button you'll be able to get the data attribute directly.
Example which is not tested:
<button data-prodid="XYZ" onlcick="handleclick()">submit</button>
Javascript:
$(this).data('prodid')
Please note that you should not have duplicate IDs on the same page.
In this case, all three of your products have the id of "prodID". So in your JavaScript, when you getElementById, you will always get the first ID with that name.
There are many solutions for this. For example, you could add the product ID to the ID of the button, like 'id="addcart_' . $rad['prodID'] . '"'
You'd then parse that ID upon form submit to determine which product was selected.
I found another solution here: http://api.jquery.com/serialize/ - to pass hidden values.
But your solution is much simpler :)

how to get information from a field that is in a loop using javascript

I have a bunch of image names that is being retrieved from my data base and is in a while loop. In this loop I have a small form with the image names. This form is being use for another purpose. what I want is to get the field information with the item name to a javascript.
Example :
while($row = mysql_fetch_array($query)) {
$itemname = $row['name'];
echo "< input type='hidden' name='$itemname' value='$itemname'>
<img src='source' onclick='getname()' width='100%' height='100%' />";
}
I believe the reason why every image I click on is only giving me the first information from the database is because my id is being duplicated. My question is how can I get the field information to javascript without using the getElementById?
Use the following altered PHP:
$i = 0;
while($row = mysql_fetch_array($query)) {
$itemname = $row['name'];
echo "<input type='hidden' name='".$itemname."[]' id='input$i' value='$itemname' />";
echo "<img src='source' onclick=\"getname('input$i')\" width='100%' height='100%' />";
$i++;
}
Then you can retrieve the input value in Javascript:
function getname(id) {
var theinput = $('#'+id).val(); // jQuery example
// do something
(I also changed the input name to be an array, of couse you could name it what you want, maybe $itemname$i could be an idea, it depends how and if you want to process your form, however the name should be unique or array for good practice)
Here is a working example of HTML/JS: http://jsfiddle.net/fuHSv/1/
How about using some jQuery 1.8.2 like the following:
$(document).ready(function() {
var inputs = $('input').on('click', function() {
var name = $(this).attr('name');
var val = $(this).val();
// do stuff
});
});
See api.jquery.com for more.

How to access the value of an element detected by livequery

I am using $_SESSION to pass back a value in the event of page redirect.
As jquery cannot access $_SESSION I decided to use PHP to output the value to a hidden div and remove that div once the value had been picked up. I expect that there is a neater way to do this but I don't know how else to expose the $_SESSION variable to jquery.
<?php
$pass_Back = $session->get_Pass_Back();
$session->clear_Pass_Back();
?>
<?php
if (count($pass_Back) != 0){
echo "<input class=\"field_Input_Left\" id=\"schedule_Description\" type=\"text\" name=\"schedule_Description\" value=\"" . array_shift($pass_Back) . "\"/><br />";
echo "<div id=\"pass_Back\" style=\"visibilty: hidden;\" ></div>";
} else {
echo "<input class=\"field_Input_Left\" id=\"schedule_Description\" type=\"text\" name=\"schedule_Description\"/><br />";
}
?>
Once this was done I needed a method to let jquery know if and when this new element was added to the DOM. Hence I used the plugin livequery to match when the element added. This it does which is great.
But when I try to access the value in the div it states that it is undefined.
$("#pass_Back").livequery(function(){
if ($("#class_Name").val() != 0){
var class_Name = $("#class_Name").val();
get_Schedule_Data(class_Name);
} else {
var class_Name = "ALL";
get_Schedule_Data(class_Name);
}
$value = $(this).attr("value");
auto_Fill_Schedule($("#pass_Back").attr("value"));
// destroy pass back
$("#pass_Back").remove();
});
When reviewed in firebug I note that at the point that livequery finds the added element no html is displayed. The DOM is ready otherwise the livequery couldn't have functioned but is this why no value is found?
Any guideance gratefully received.
Don't use this:
$value = $(this).attr("value");
Do the following to get a value (for inputs in most of cases):
(assuming $(this) is your input)
$value = $(this).val();
For div cases, there is no value, but you can get the html or text from inside as the value:
(assuming $(this) is your div)
$value = $(this).html();
//or:
$value = $(this).text();
Just to know...
You can mix PHP with jQuery but take a look at my answer from this post for better understanding:
Is echoing Javascript code condtionally based on server-side logic considered harmful?
As long you're not outputting the entire $_SESSION array, or anything of importance, you're going to be ok:
<?php
$pass_Back = $session->get_Pass_Back();
$session->clear_Pass_Back();
if (count($pass_Back) != 0){
echo '<div id="passBack" type="text" value="'.implode(",", array_shift($pass_Back)).'" />';
}
?>
JS
$(function() {
if ($("#passBack").length) {
//element exists in DOM, get the value
var passBack_data = this.value;
//do something with the value
}
});
Just output the element and make sure it's a string, not an array ( I used implode() ), and on pageload see if it exists (has length), and get the value.

Categories