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/
Related
When a hyperlink 'Add More' is clicked, a dropdown list is added using jquery. I want the values in this dropdown to be generated from the mysql database using php.
I tried many ways,but i not able to get the values from php to jquery.. The values retrieved from mysql database using while loop should be displayed in the dropdown using jquery. Thanks
The values in $val should be displayed in dropdown options
Here is the sample
php code retrieving values from database
<?php
$aquery = "SELECT * from filter";
$aresult =$base->execute_query($aquery);
while($row=mysql_fetch_array($aresult))
{
$val=$row[1];
}
?>
jquery where $val values should be added in dropdown
<script type="text/javascript">
jQuery(document).ready(function($){
$('.my-form .add-box').click(function(){
var box_html = $('<select><option><?php echo $val; ?></option>');
$('.add-box:last').before(box_html);
return false;
});
});
</script>
Please help me.Thanks
If you want this on button click as your code then try this solution:
var box_html = '<select><?php foreach ($val as $value) {
echo "<option>$value</option>" ;
}?>';
The PHP Script is actually over-writing on your $val.
Perhaps you can do the following:
<?php
$val = "";
while($row = mysql_fetch_array($aresult)) {
$val .= "<option value=". $row[1] .">". $row[1] ."</option>";
}
?>
and your JavaScript code should suffice in this case, just remove the option tags before the php script.
Hope this helps.
var box_html = $('<select><?php echo $val; ?></select>');
php will build you an array
you need to convert it to java object json_encode
try var abc=
also when your printing it you need to run a loop through the object after creating the select section
see each() jquery
this is my second time asking for help here so I hope you don't mind if I make a mistake.
See I have a problem accessing an element (In this case, it's a < td >). I dynamically added it's name using JQuery as I 'echoed' it. I did this because the values inside the table it belongs to, are chosen by the user and is triggered by a button click.
Here's the JQuery:
$("#tblAddServices tbody").delegate("tr", "click", function(){
firstCellServ = $("td:first", this).text();
secondCellServ = $("td:eq(1)", this).text();
thirdCellServ = $("td:eq(2)", this).text();
fourthCellServ = $("td:eq(3)", this).text();
})
$('.service').on('click', function(e){
var $table = $("#tblServiceIncluded");
var newTR = $("<tr><td colspan=\"3\" name=\"servID[]\">"+firstCellServ+"</td>
<td colspan=\"3\">"+secondCellServ+"</td>
<td colspan=\"3\">"+thirdCellServ+"</td>
<td colspan=\"2\" class=\"sumService\">"+fourthCellServ+"</td>
</tr>");
$table.append(newTR);
});
Now, I have a PHP script that should be getting the value(s) of the first column of the table which I named 'servID[]'. I am using an array to get its values but I always end up with an Undefined Index warning for the 'servID'.
This is the PHP script:
<?php
if(isset($_POST['btnSavePack']))
{
$serviceArray = array();
foreach($_POST['servID'] as $serviceKey){
$serviceArray[] = $serviceKey;
}
foreach($serviceArray as $result) {
echo $result, '<br>';
}
}
?>
I hope you someone could help me figure out a way to make this work. I know I could do this with Ajax but I prefer this method since I am only a beginner. Thank you.
You can put the value in an input box with a type hidden.
"<td colspan=\"3\"><input name=\"servID[]\" type=\"hidden\" value=\""+firstCellServ+"\"/>"+firstCellServ+"</td>"
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 :)
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.
I have two dropdown lists containing customers info.
Using PHP for loop, I have allowed to enter 5 customers details at a time.
for($i=1; $i<6; $i++)
{
echo "<tr><td><select id=\"customer_" . $i . "_class\"></select></td>";
echo "<td><select id=\"customer_" . $i . "_age\"></select></td></tr>";
}
Now I want to execute a jQuery function in such a way that if, for example, customer_2_class changes, it executes some function to its corresponding customer_2_age.
$("#customer_?_clas").change(function()
{
//some function to execute on corresponding customer_?_age
});
Add class to your <select> and move the id to another attribute, like data:
echo "<tr>";
echo "<td><select class=\"customer_class\" data-id=\"$i\"></select></td>";
echo "<td><select class=\"customer_age\" data-id=\"$i\"></select></td>";
echo "</tr>";
And in your javascript:
$('.customer_class').change(function() {
var id = $(this).attr('data-id');
// process customer_class with this id
});
You could use the attribute ends-with selector:
$('select[id$="_class"]').change(function() {
It might be worth browsing through the full list of jQuery selectors.
$('select').
filter(function() {
return /^customer_[0-9]_class$/.test(this.id); // filter on select
// based on id format
})
. change(function() { // binding change
// to filtered select
var num = this.id.match(/\d/)[0]; // get numerical value
// of select box on change
$('#customer_' + num + '_age') // point to target select
.css('background', '#f00'); // do something
});
Working sample