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
Related
how to pass a variable to jquery with php ?
i have to call the jquery from html this is what is confusing me:
jquery:
$(document).ready(function() {
$('#pre-info').click(function() {
$('#hide').slideToggle("fast");
});
});
now i want a $i after #pre-info and after #hide.
im calling the jqueryScript like this :
thank you.
Okay, here is more code :
<?php
$i =0;
//Make some querys nd stuff
foreach ($all as $one) {
//Here the event 1 is createt but the pre info gets increased with each event listet
echo "<div class='EVENT'><div id='pre-info$i'>";
// get som other tables nd stuff
echo"</div><div id='hide$i' style='display:none;'>";
//now this part is hidden until i click on the pre-info
//hidden Stuff
$i++;
}
?>
<script type="text/javascript">
$(document).ready(function() {
$('.pre-info').click(function() {
var hiddenid=$(this).data('hiddenid');
$('#'+hiddenid).slideToggle();
});
});
</script>
it does still not work, did i miss anything?
for me it looks like pre-info in this javascript needs a reference ( $i) as well ?
maybe i just dont understand the jquery completly..
Ok so you have several hidden divs and for each one you also have a listener to toggle their visibility. The original list comes from php which in turn gets the data from a query.
You could use data attributes to link pre-infos to hidden elements:
$i =0;
foreach ($all as $one) {
echo "<div class='pre-info' data-hiddenid='hide$i'>click me</div>";
echo "<div id='hide$i' style='display:none;'> hidden stuff </div>";
$i++;
}
then you just need one listener on jQuery
jQuery(document).ready(function() {
jQuery('.pre-info').click(function() {
var hiddenid=jQuery(this).data('hiddenid');
jQuery('#'+hiddenid).slideToggle();
});
});
Hope it helps (edit, I wrapped the listener in the document ready event)
By the way, it seems to me you're reinventing the wheel. You could use jQuery UI's accordions or Bootstrap collapsibles with nice, crossbrowser transitions.
If the JS is in .php file, you can just use:
$(document).ready(function() {
$('#pre-info<?php echo $x; ?>').click(function() {
$('#hide<?php echo $x; ?>').slideToggle("fast");
});
});
Your question does not contain enough information to give you more detailed answer, I'm afraid.
you could embed the php variable you require into a hidden html attribute or a data attribute
Hidden Element HTML
<input type="hidden" id="someId" name="someName" value="<?php echo $someVariable?>"/>
Javascript
var someVar = $('#someId').val()
Data HTML
<div id="someId" data-some-var="<?php echo $someVariable?>"></div>
Javascript
var someVar = $("#someId").data("some-var")
Note that if you use data you must include the keyword "data" before whatever you decide to name the attribute
i have created the drop down menu using php and i want to use the selected value of menu on url of the current page. How can i do this without redirecting to the next page. the code for creating dropdown menu is:
echo '<select name="Company">';
if($data['count']>0){
foreach($data['results'] as $key=>$value){
echo "<option value='".$value['CID']."'>".$value['Name']."</option>";
}
}
echo "</select>";
Hum? Dont know what you exactly want. You want to create a dropdown menu and use the selected value on the current php page?
That wont work. Ill show you how it works:
PHP renders page -> gives it to you.
When you see the page, the php-script is already done. So you have to call your page again and give it the value via $_POST ...
echo <form action="page.php" method="post">
echo '<select name="Company">';
if($data['count']>0) {
foreach($data['results'] as $key=>$value){
echo "<option value='".$value['CID']."'>".$value['Name']."</option>";
}
}
echo "</select></form>";
... or $_GET (this only works in combination with JS!) ...
echo "<a href='page.php?company=companyname'>Im a link!</a>"
You need to get drop down value using javascript or JQuery
In Javascript:
<script type="text/javascript">
var myselect=document.getElementById("Company")
for (var i=0; i<myselect.options.length; i++){
if (myselect.options[i].selected==true){
alert("Selected Option's index: "+i)
break
}
}
</script>
In JQuery
$('select[name=Company]').val()
It's not entirely clear how you want to use this value, but you can refer to it on the same page using javascript. Consider the code below, which will update the line "Your company is:" whenever a new option is selected from the dropdown box.
<script type="application/javascript">
function update_box() {
selected_value = document.getElementById('company_dropdown').value;
document.getElementById('your_company').innerText = selected_value;
}
</script>
<form action="page.php" method="post" id="my_form" name="my_form" onchange="update_box()">
<select name="company_dropdown" id="company_dropdown">
<option value='A'>A</option>
<option value='B'>B</option>
<option value='C'>C</option>
</select>
</form>
Your company is: <span id="your_company" name="your_company"></span>
If I am getting it right, you want to use the selected value from dropdown on the same page url via querystring.
You can do that like following:-
echo '<select name="Company" onchange="location.href = location.href+'?var=' + this.value">';
if($data['count']>0){
foreach($data['results'] as $key=>$value){
echo "<option value='".$value['CID']."'>".$value['Name']."</option>";
}
}
echo "</select>";
When you will change the value in dropdown, current page will refresh with the selected option value in querystring. You can use the querystring value as following:-
<?php echo isset($_GET['var']) ? $_GET['var'] : ''; ?>
You can also do it via use of hash value without refreshing the page
When ever you change the dropdown on the onchange event you can write the code
onchange="window.location.hash(this.value);"
it will set a hash value in the url and then you can write a function which will detect the change in the hash value as the page is not refreshing you need to track the change in the hash value and then you can show the selected menu on the basis oh the hash value.
use this to detect the change in the hash value
$(document).ready(function() {
$(window).bind('hashchange', function(e) {
var hashStr = window.location.hash;
hashStr = hashStr.substring(1, hashStr.length);
hashArray = hashStr.split('&');
// here you will get the array of all the parameters you passed in the array
});
});
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/
In Dreamweaver I have a list box or menu/list.
I am dynamically adding data from an array into it, so when the page loads, I have a list-box with names in.
This is how it looks
<?php
echo "<select name="."username"."id="."username".">";
foreach ($user_array as $arr) {
echo "<option>$arr</option>";
}
echo "</select>";
?>
Now how do I go about making the listbox executesomething when the user selects something in it?
Because I have three other textboxes, and when the user selects a name in the list box, I want to put that name he selected into a variable (also don't know how I'm going to do that with a list box) and then search through my database and insert some of the data of that person in the textboxes.
So all i need to know is:
How to create that on event click event and
How to put that selected value then in a variable (inside the event)
You can easily execute a javascript function by using something like this:
<select name=".$username."id=".$username." onchange='yourfunction()' >
The following php code generated a select field with a dynamic number of options.
<?php
$user_array = Array("Smith", "John", "Bob", "Jake");
echo "<select name="."username"." id="."username".">";
foreach ($user_array as $arr) {
echo "<option>$arr</option>";
}
echo "</select>";
?>
The following JavaScript handles change events on the select element.
$(document).ready(function() {
var username = $('#username');
var selectedValue = null;
username.change(function(){
alert(username.val());
selectedValue = username.val();
});
});
I'm trying to build a form where certain text fields and text areas have autocomplete.
I've used the formidable plugin for wordpress to build my form. I'm using the jQuery autocomplete plugin for the autocomplete part.
The code looks like this:
<script>
$(document).ready(function(){
var data = "Core Selectors Attributes Traversing Manipulation CSS Events Effects Ajax Utilities".split(" ");
$("#example").autocomplete(data);
});
</script>
So basically I need to use php to pull data from the mysql database and feed it to that data var. I'm a php newbie, so I'm not sure how to do this. A coder who works on the formidable plugin suggested the following code for the var data part:
<?php
global $frm_entry_meta;
$entries = $frm_entry_meta->get_entry_metas_for_field($field_id, $order='');
?> //db_frm_entry_metas is the name of the mysql db that stores the values for every field from the form. I suspect get_entry_metas_for_field is a function added by the formidable plugin. $field_id is the id for a given field on the form.
var data = new Array();
<?php foreach($entries as $value){ ?>
data[] = <?php echo $value ?>;
<?php } ?>
I tried to run this code with an id number in the place of $field_id, but it didn't work. I'm stuck here.
I can understand most of the code, except for this part:
var data = new Array();
<?php foreach($entries as $value){ ?>
data[] = <?php echo $value ?>
I don't get what the data[] is doing there... should the php be feeding the data to the var data= line?
I have around 15 form text/textarea fields, each of which needs to pull data associated with its given field_id. Unless there's an easier way to do this, this means I'll have to write 15 scripts, each with a particular $field_id and jQuery object with field's css selector.
Any help getting this to work would be much appreciated!
The coder is wrong, this:
data[] = something;
will cause a syntax-error in JS, it's a PHP-shorthand for pushing members to an array and doesn't work in JS.
Try this:
data.push(unescape('<?php echo rawurlencode($value); ?>');
According to the autocomplete docs, you can pass a url as the data parameter. That being said, do something such as the following:
<?php
// --- PLACE AT VERY TOP OF THE SAME FILE ---
$search = isset($_GET['q']) && !empty($_GET['q']) ? $_GET['q'] : null;
if (!is_null($search))
{
$matches = Array();
// some search that populates $matches based on what the value of $search is
echo implode("\r\n",$matches);
exit;
}
?>
then, in your jQuery code replace the .autocomplete(data) with .autocomplete('<?php echo $_SERVER['PHP_SELF']; ?>');
your jquery will be something like this
$("#example").change(function(){
$.ajax(
{
type: "POST",
url: "php_page.php",
data: "data=" + $("#example").val(),
beforeSend: function() {
// any message or alert you want to show before triggering php_page.php
},
success: function(response) {
eval(response);
// print your results
}
});
});
in your php page after getting all info echo the results like this.
echo "var result=" . json_encode($results);
then eval(response) jquery function will give you javascript variable result with your results in it.
Hope this helps...