Assign value to textbox onchange of php while select - javascript

I'm slowly understanding PHP but this one has me stumped.
I am populating a 'select' HTML element with data from PHP using.....
while($row = mysql_fetch_array($result))
All is working fine and I understand why.
I just wanted to fill in other textboxes on the page when a selection is made.
There is a very helpful fiddle at http://jsfiddle.net/TPE9r/5/ but it does not use PHP.
This is part of my code...
while($row = mysql_fetch_array($result)){
echo '<option value=" ',$row['ContactID'],' ">', $row['ContactName'],' -- ', $row['BusinessName'],
'</option>';}
Sorry about the formatting - new on here also...
I have used similar JavaScript to the fiddle but I can't display $row['ContactName'] or $row['BusinessName'] in a textbox. I can do this with a normal HTML select but not when the rows are in a 'while loop'

because you try to do something, what should be done on other way.
In the while loop, you are putting out the options html tags.
To do this, i think, the best practice, if you build an array from your results, so you can use that later, if you want to do it in PHP.
The code is not tested.
echo '<select name="whatever">';
$results = array();
while($row = mysql_fetch_array($result)){
//Storing all the rows in an array
$results[] = $row;
}
for($i=0;$i < count($results); $i++) {
echo '<option value=" ',$results[$i]['ContactID'],' ">', $results[$i]['ContactName'],' -- ', $results[$i]['BusinessName']."</option>";
}
echo '</select>';
//And now you can youse your $resuls array more then one time.
$key = 0;
//The key is based on, wich data you need.
//Maybe you want to set it in the loop with an if condition
echo '<input type="text" value="'.$results[$key]['ContactName'],' -- ', $results[$key]['BusinessName'].'" />';

Trying to post my own answer - having trouble with formatting on here.
The loop should be
for($i=0;$i < count($results); $i++) {
echo ''. $results[$i]['ContactName'].
"";
OOPS!!!!! Done it again - the loop code is truncated - don't know why

Finally, solved this one - maybe not the best way but it may help others.
I used : $(this).find(':selected').data('id') .... in the onchange
and used data-attributes in the loop
for($i=0;$i < count($results); $i++) {
echo '<option data-id="'.$results[$i]['ContactID'],' " data-bn="'.$results[$i]['BusinessName'],' " >'. $results[$i]['ContactName'].
"</option>";
and 3 textboxes whose id is bb, cc, dd ....
price2= this.value;
price1 = $(this).find(':selected').data('id')
price3 = $(this).find(':selected').data('bn')
$('#bb').val(price1);
$('#cc').val(price2);
$('#dd').val(price3);
Just a bit tricky with single and double quotes in the loop but 'Hey that's what we do!'

Use this instead. You do not want the value of the option but the text.
$('#job_title').live('change', function(){
var b = $(this).text();
$('#catch_value').val(b);
return false;
});

Related

change div backgroundcolor with js and php

i am working on my first own website. i try to display which cinema seats are already booked, by turning theire backgroundcolor red. i store the reservations in an sql database. i do get the correct value and i can display it on my website, but still the getById won t work.
This is how i create the divs i want to tune:
<?php
for ($i=0; $i < $saalinfo[2]; $i++) {
echo "<div class='rowsaal'>";
for ($j=0; $j < $saalinfo[3]; $j++) {
$k = $i+1;
echo "<a onclick='JavaScript:removeday($k$j)';>";
echo "<div id='$k$j' class='seat' >";
echo "</div>";
echo "</a>";
}
echo "</div>";
}
?>
This is the way i try to change the background color. I used the exact same js wording in other occasions and it did work so i am guessing my id value is not right:
function getres(){
var date = document.getElementById('labeldate').value;
document.getElementById('showdate').innerHTML = date;
var booked;
booked = "<?php echo $dis; ?>"; //$dis is one value i get back from mysqli_fetch_array in this case its 34
document.getElementById(booked).backgroundColor = "red";
document.getElementById('showdate').innerHTML = document.getElementById('showdate').innerHTML + booked;
}
For clarification: booked shows the correct value which is 34 in this case. In the database itself its saved as a txt value. if i look into the html source code i can see that the value 34 is assigned for booked.
booked = "34";
but the div id is set in the following pattern as it is limitted in the use of '' because they are formed in php
</a><a onclick='JavaScript:removeday(34)';><div id='34' class='seat' ></div></a>
i already had some issues where the use of "" and '' lead to different results. Is this the same case here? and how can i fix the issue? Many thanks in advance.
I have not checked all of your code but there is no "backgroundColor" on the element. You need the style property.
document.getElementById(booked).backgroundColor = "red";
should be
document.getElementById(booked).style.backgroundColor = "red";

Typeahead.js -- refresh data

I have managed to get this code to work for an application -- http://twitter.github.io/typeahead.js/ but, the problem I have run into, is that I need to be able to re-load the data. I would rather not duplicate the code to do this, although it's an option, it seems kind of silly. I have inserted some PHP into my JavaScript to create an array for the dropdown list, and it works great. But if I stuff it into a function, and then try to call the function in the document open, it doesn't work (nothing appears to happen).
$(document).ready(function()
{
// call function when page loads(?)
getAwards();
}); // end document.ready ...
This is the PHP code, if I comment out the JavaScript function parts it runs and the typeahead code sees the value of the array. If I put it into the function, it doesn't execute despite being called above, and I have no data for the typeahead code ...
function getAwards(
{
// build array for use with typeahead:
<?php
$sql_statement = "select title from awards order by title desc limit 1";
$aw_result = mysqli_query( $connect, $sql_statement );
$aw_row = mysqli_fetch_array( $aw_result );
$last_award = $aw_row["title"];
// need to rewind table:
mysqli_data_seek( $aw_result, 0);
// start from the top:
$sql_statement = "select title from awards order by title";
$aw_result = mysqli_query( $connect, $sql_statement );
$count = 0;
$out = 'awards = [';
while ( $aw_row = mysqli_fetch_array( $aw_result ) )
{
// the quotes deal with forcing this to handle
// branch names with apostrophes in them ...
$count++;
$out .= '"'. $aw_row["title"] . '"';
if( $aw_row["title"] != $last_award )
{
$out .= ',';
}
}
$out .= ']';
echo $out . "\n";
?>
})
I need to be able to update the data, and reload the list while working on the form (I am working that out in my fuzzy brain, but anyway I'll get to that -- currently intend to click a button to update the list used by the typeahead, which is why I want a function ...)
Any suggestions are gratefully accepted. I am at a loss ...

Using Returned SQL Array with Random Result Picker

I am writing a new feature plugin for a website I develop and am stuck with how to go about implementing such feature. I'm trying to return an SQL query to an array that I can then pass to a function in either PHP or JavaScript, to perform a random option picker, and display the results to the user. I'm trying to perform the random picker by an on-click functionality.
So far, I have figured out how to successfully select my SQL query, return statements, and in JavaScript, work with a random option picker. However, I have not been able to find a good way to combine all these things together to produce my result.
I was wondering if anyone knew of a way to do this. Is it better to perform the entire program functionality in PHP or better to pass it to a JavaScript function and return results through the JS code?
Here are some examples of my code. Please assume that my query works. I do not need the display option in my code. It is implemented to check query results. I was hoping to hide the array in the real plugin from users and use the returned results for the on-click functionality attached to an HTML element.
<?php
function choices() {
$config = parse_ini_file(*database file*);
$con = mysqli_connect(*database information*);
if(!$con){
exit("Please try again later.");
}
$query = "SELECT * FROM *query*";
$result = #mysqli_query($con, $query);
$num = mysqli_num_rows($result);
if ($num > 0) {
echo "<p>There are currently $num restaurants.</p>\n";
echo '<table width="60%">
<thead>
<tr>
<th align="left">Restaurant Title: </th>
<th align="left">Link: </th>
</tr>
</thead>
<tbody>
';
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo '<tr><td align="left">' . $row['post_title'] . '</td><td align="left">' . $row['guid'] . '</td></tr>
';
}
echo '</tbody></table>';
mysqli_free_result($result);
}
else {
echo '<p class="error">The results could not be retrieved.</p>';
}
mysqli_close($con);
}
$foo = choices();
?>
My JS code.
var favorites = ["choice #1, choice #2, choice #3, choice #4"];
var favorite = favorites[Math.floor(Math.random() * favorites.length)];
Thank you very much for any input regarding this question! I understand this is a rather lengthy question and I do appreciate time took to help me understand it.
Why not just have your database return a single random result since that's all you need?
SELECT * FROM tbl ORDER BY RAND() LIMIT 1
Take a look at this post about getting random rows
Put the results of the query in a PHP array. Then use json_encode() to convert that to a Javascript array. Then the onclick functionality can display a random element of the array.
$array = array();
while ($row = mysqli_fetch_assoc($result)) {
$array[] = $row['post_title'];
}
?>
<script>
var favorites = <?php echo json_encode($array); ?>;
$("#button").click(function() {
var favorite = favorites[Math.floor(Math.random() * favorites.length)];
alert(favorite);
});
</script>

Expanding the content by click it

When i click the more. I wanted the content should expand. I my page i have about 10 question with more option. The question content is coming through the php script.
<?php
$result = mysqli_query($conn, $query) or die("error: " . mysqli_error($conn));
//fetch the data.
if (mysqli_num_rows($result) > 0) {
while($data = mysqli_fetch_assoc($result)) {
$question = $data['question'];
echo "<span class=\"spanstyle\" id=\"fullquestion\">" . substr($question, 0, 170);
echo "...more</span><br>";
}
}
?>
I try to do that by javascript. ContectExpand() fire of when i click.
<script>
function contentExpand() {
var question = <?php echo $question; ?>;
document.getElementById("content").innerHTML = question;
}
</script>
Problem is, $question is changing the value as it is inside the loop. It doesn't have a fixed value.
Also I want to know that I can do that only along with php without javascipt.
For my solution you need some sort of $data['id'], which is unique for each question.. I think it cannot be done only in PHP, but you should try to use jQuery, it makes javascript much easier
<?php
$result = mysqli_query($conn, $query) or die("error: " . mysqli_error($conn));
//fetch the data.
if (mysqli_num_rows($result) > 0) {
while($data = mysqli_fetch_assoc($result)) {
$question = $data['question'];
echo "<span class='spanstyle' id='shortQuestion{$data['id']}'>" . substr($question, 0, 170).
"...<a href='#' onClick='return contentExpand({$data['id']});'>more</a></span>
<span class='spanstyle' id='longQuestion{$data['id']}'>{$data['question']}</span>
<br>";
}
}
?>
Javascript
<script>
function contentExpand( fullcontentId ) {
document.getElementById('shortQuestion'+fullcontentId).style.display = "none";
document.getElementById('longQuestion'+fullcontentId).style.display = "inline";
return false;
}
</script>
There are several issues with you code. Regarding your question, the most important are:
The while loop is generating several span elements with the same id.
The onClick function should content a reference to the element you want to expand.
You dind't include any code constraining the size of the span element, so there is nothing to be expanded.
How to fix them:
Modify the while loop
Create a $i variable that counts the rows and add it to the span id, to the link id and to the javascript function in this way:
$i = 0;
while($data = mysqli_fetch_assoc($result)) {
$i++;
$question = $data['question'];
echo "<span class='spanstyle' id='fullquestion_" . $i. "' >";
echo "<a href='#' id='link_" . $i . "' onClick='contentExpand(" . $i. ");'>more</a> ";
echo $question."</span><br>";
}
Create a javascript function that resize the span element:
You didn't tell us how you want to expand the content. There would be a lot of different ways to achieve it. This is just one that tries to respect your HTML markup, but surely not the best:
<script>
function contentExpand(id) {
var link = document.getElementById('link_'+id);
var span = document.getElementById('fullquestion_'+id);
if(link.innerHTML=='more')
{
link.innerHTML = 'less';
span.style.width = '100px';
}else{
link.innerHTML = 'more';
span.style.width = 'auto';
}
}
</script>
Modify the css of the span element:
A block element like a div would suit better anyway, but maybe you have very good reasons to use a span.
span {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
text-align: right;
}
How to do it without javascript (just PHP):
It is certainly possible, but I guess you don't want to do it.
But if still you want to do so, generate the loop with just partial information about the related $question (as you do in the original code, substr($question, 0, 170)) but put the elements inside a form.
When the user click the more span element, submit the form to send from the client back to the server the information about the selected item.
Then, the PHP script would generate again the page but, this time, the selected item will load the full text of the question ($question instead of substr($question, 0, 170)).
So, you will have to make a new HTTP request call (that means to reload the page, AJAX is not an option if you don't want to use javascript).
Doing all this add a new layer of complexity and make it less efficient.
My advice is, if you don't have strong reasons to don't use javascript, use it.

Tooltip echo from PHP

I'm dealing with this problem since 2 days and I haven't found a solution.
Here's the tooltip script that I'm using: http://iamceege.github.io/tooltipster/
It works fine, I'm able to show data in HTML format, no problem.
But the problem comes when I want to echo a HTML code from a function that was written by me. The output of the function isn't showed in the tooltip, but outside it.
Here's my function:
public function showProducts($uId, $wid){
$sql1 = "SELECT pids FROM wishlists WHERE uid='$uId' AND id='$wid'";
$q = mysql_query($sql1) or die(mysql_error());
while($data=mysql_fetch_array($q)){
$dbprods = $data['pids'];
$prods = explode(",", $dbprods);
for($i = 0; $i < count($prods); $i++){
$id=$prods[$i];
$q=mysql_query("SELECT * from products where id='$id'");
while($bd = mysql_fetch_array($q)){
echo ''.$bd['name'].'<br />';
}
}
}
}
If I'm typing return $bd['id'];, the tooltip is fine. The problem comes only with that HTML output. The tooltip and function call is this echo '# <a class="tooltip" title="Products <br />'.$this->showProducts($uid, $wid).'">'.$data['name'].'</a><br />';
I have also tried to modify the my function into something like
while($bd = mysql_fetch_array($q)){ ?>
<?php echo $bd['name'];?><br />
<?php }
but still no result. Does anyone helps me out?

Categories

Resources