Why does .click() on an select option only work on firefox? - php

i have a select with some options generated from content:
<select style="color: #444;">
<?php
$select_optd = 0;
foreach($DATA as $EACHOPTION){
// Checking some internal stuff, this works
if(IFISVALID){ // Now lets say it is valid, it will output some options
// Option echo
echo '<option';
// Some code to show the first option as selected and setting some
// later needed POST javascript variables
if($select_optd == 0){
echo ' selected="selected" ';
$select_optd = 1;
$show_ctrl_id = $EACHOPTION['id'];
$show_ctrl_spot = $EACHOPTION['spot'];
}
// echo the option html data
echo ' id="PRJ_OPT_'.$EACHOPTION['id'].$EACHOPTION['spot'].'" >';
echo $EACHOPTION['title'] . ' - Spot: ' . $EACHOPTION['spot'];
echo '</option>';
?>
<script type="text/javascript">
// Now the Javascript for when the option is selected
$(document).ready(function(){
$('#PRJ_OPT_<?php print($EACHOPTION['id']); print($EACHOPTION['spot']);?>').click(function(){
// An image showing the option selected
$('#PRJ_IMG_SHOW').attr('src','<?php print($EACHOPTION['image_url']); ?>');
// Some posting inputs for later on
$('#w_prj_id_send').val('<?php print($EACHOPTION['id']); ?>');
$('#w_prj_spot_send').val('<?php print($EACHOPTION['spot']); ?>');
// An alert to test if it's working
alert('Changed');
});
});
</script>
<?php
}else{ // that option was not valid, next one. }
} // End of Foreach
?>
</select>
The problem is this .click() event on the options is only working on firefox. I've tried on Chrome, IE... only works Firefox.
Is there any resolution or explanation for this problem?
// ----------------------------------------------------------------- //
RESOLUTION:
<script type="text/javascript">
$(document).ready(function(){
$('#prj_selector').change(function(){
var SELECTED_PRJ = $('#prj_selector').val();
<?php
foreach($DATA as $EACHOPTION){
?>
if(SELECTED_PRJ == '<?php echo $EACHOPTION['title'] . ' - Spot: ' . $EACHOPTION['spot']; ?>'){
$('#PRJ_IMG_SHOW').attr('src','<?php print($EACHOPTION['image_url']); ?>');
$('#w_prj_id_send').val('<?php print($EACHOPTION['id']); ?>');
$('#w_prj_spot_send').val('<?php print($EACHOPTION['spot']); ?>');
}
<?
}
?>
});
});
</script>

Because <select> is a control, not a normal element.
Use .change() instead on the select element itself.

For select boxes you can use the .change() event instead of .click
http://comp345.awardspace.com/select_element_cheatsheet.pdf

Related

PHP drop down menu, once clicked

I have created a drop down menu in php that is displayed however, when a value has been clicked, I don't know how to collect this information.
<html>
<body>
<?php
$mydb = new mysqli('localhost','root','','TestTimeTableSolution');
$rows = $mydb->query("SELECT DISTINCT TeacherID FROM Teacher;")->fetch_all(MYSQLI_ASSOC);
$teachers = array();
foreach ($rows as $row) {
array_push($teachers, $row["TeacherID"]);
}
$dropdownMenu = "<select name='TeacherID' form='Teacher'><option value='Null' selected>All</option>";
foreach ($teachers as $topic) {
$dropdownMenu .= "<option value='" . $topic . "'>" . $topic . "</option>";
}
$dropdownMenu .= "</select>";
echo $dropdownMenu;
?>
</body>
</html>
Based on your last comment, "i want it to be dynamic so as soon as the user clicks on something the relevant information will pop up", it sounds like you will probably want to use Ajax/JavaScript (I will demonstrate a simple jQuery example, notating for clarity):
<?php
$mydb = new mysqli('localhost','root','','TestTimeTableSolution');
?>
<html>
<!-- Add the jQuery library -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
// Act when the document is ready
$(function(){
// listen for the select to change
$('select[name=TeacherID]').on('change',function(){
// Run the ajax – you can also use the shortcut $.post method found at:
// https://api.jquery.com/jquery.post/
$.ajax({
// This is the page that is going to do the data lookup/display action
url: '/lookup.php',
// This is how it's sending the data to that page
type: 'post',
// This is what is being sent ($_POST['submit'] in this case)
data: {
// Use $(this) to isolate the current selected element and get value (.val())
// The value is represented as $topic in your php
'submit': $(this).val()
},
// If all goes well and the page (lookup.php) returns a response
success: function(response) {
// Place the response into the div (see html snippet)
$('#loadspot').text(response);
}
});
});
});
</script>
<body>
<?php
$rows = $mydb->query("SELECT DISTINCT TeacherID FROM Teacher;")->fetch_all(MYSQLI_ASSOC);
$teachers = array();
foreach ($rows as $row) {
array_push($teachers, $row["TeacherID"]);
}
$dropdownMenu = "<select name='TeacherID' form='Teacher'><option value='Null' selected>All</option>";
foreach ($teachers as $topic) {
$dropdownMenu .= "<option value='" . $topic . "'>" . $topic . "</option>";
}
$dropdownMenu .= "</select>";
echo $dropdownMenu;
?>
<!---------------------------------------------->
<!-- THIS IS WHERE THE CONTENT WILL LOAD INTO -->
<!---------------------------------------------->
<div id="loadspot"></div>
</body>
</html>
In order for this to work, you need the page lookup.php in the domain root (you can make it whatever/where ever you want, but you need to match in the javascript url):
/lookup.php
<?php
# This is what will get placed into the parent page <div id="loadspot"></div>
# Do you your php here in place of this line and return whatever "relative information" you want
print_r($_POST);
You should review the jQuery page I have linked to to get more information and direction for that library and make sure you use your browser's developer tools to monitor javascript errors in the console. Ideally, you want to understand all this via the documentation instead of just copy and paste and move on...

displaying image from directory using dropdown using jquery

i have the code below that will change the image based on a dropdown
the image in db is stored example as mypicture.jpg and all thumbshot image is located at /images/thumbshots/
right now the image selected is displayed when we load the page but when changing the drop down the picture is not showing
i got
mydomain.com/mypicture.jpg instead of mydomain.com/images/thumbshots/mypicture.jpg
my code so far
echo "<label for='image'> Select Image File :</label>
<select name='image' id='selectsrc' class='form-control'>
<option value=''>Select Image </option>";
foreach(glob(dirname(__FILE__) . '/images/thumbshots/*.{jpg,png,gif}', GLOB_BRACE) as $image_db){
$image_db = basename($image_db);
if($image == $image_db) {
echo "<option value='" . $image_db . "' selected>".$image_db."</option>";
}
else
{
echo "<option value='" . $image_db . "'>".$image_db."</option>";
}
}
echo "</select></div>";
if ($image!='')
{
echo "<img src='images/thumbshots/$image' id='changesrc'>";
}
else
{
echo "<img src='".MY_URL."/images/blank.gif' id='changesrc'>";
}
?>
<script type="text/javascript">
var jQuery_1_9_1 =$.noConflict(true);
</script>
<script>
jQuery_1_9_1(document).ready(function() {
jQuery_1_9_1('#selectsrc').change(function(){
jQuery_1_9_1("#changesrc").attr('src',jQuery_1_9_1(this).val());
});
});
</script>
i think i need to change this code but im currently stuck with it..any input is much appreciated..thank you
<script>
jQuery_1_9_1(document).ready(function() {
jQuery_1_9_1('#selectsrc').change(function(){
jQuery_1_9_1("#changesrc").attr('src',jQuery_1_9_1(this).val());
});
});
</script>
As you are getting only image name you need to prefix your directory before name. And you dont need such a big selector jQuery_1_9_1 you can use simple one with single letter.
OR
Just add full path in option value then dont need any prefix your code will work in that case.
<script>
jQuery_1_9_1(document).ready(function() {
jQuery_1_9_1('#selectsrc').change(function(){
var img_path = 'images/thumbshots/' + jQuery_1_9_1(this).val();
jQuery_1_9_1("#changesrc").attr('src', img_path);
});
});
</script>

How to code Jquery Chosen on select event?

I'm having a little trouble with my code and I'm hoping someone can help. I'm trying to have the user select an option from a select box and then another select box to be based on that queries result. I know this should be simple but I can't seem to get it to work. Here's the code I've got so far.
The First select box:
select id="selCategory" name="category" class="chzn-select"<?php if (in_array('category',$_SESSION['iserror'])) {echo ' class="isError" ';} ?> >
<option value ="" ">
<?php
while ($row = hesk_dbFetchAssoc($res))
{
echo '<option value="' . $row['id'] . '"' . (($_SESSION['c_category'] == $row['id']) ? ' "' : '') . '>' . $row['name'] . '</option>';
}
?>
</select>
The second select box:
<select id="selAsset" name ="asset" class="chzn-select">
<option value="" selected="selected"></option>
<?php
while ($row = odbc_fetch_array($Assets))
{
echo '<option value="' . $row['AssetID'] . '"' . (($_SESSION['c_asset'] == $row['AssetID']) ? ' selected="selected"' : '')
. '>' . $row['AssetName']. '</option>';
}
odbc_close($conLansweeper);
?>
</select>
The code to handle if the second drop down box is displayed.
<script language="Javascript" type="text/javascript">$(function()
{
$(".selCategory").chosen().change(function(){
var selectedCategory=$(this).find("option:selected").val();
if(selectedCategory == "1")
{
$(.selAsset).show();
}
else
{
$(.selAsset).hide();
}
});
});
</script>
Footer Code:
<script type="text/javascript" src="script/chosen/jquery.min.js"></script>
<script type="text/javascript" src="script/chosen/chosen.jquery.js"></script>
<!--<script type="text/javascript" src="script/jquery/jquery-1.10.2.min.js"></script>-->
<script type="text/javascript">$(".chzn-select").chosen({disable_search_threshold: 10, width:200, placeholder_text_single:" ", search_contains: true, allow_single_deselect: true });</script>
The basic aim is for the second select box to be hidden when the page loads and the display when the appropriate value is selected in the first select box.
Can anyone help me out? I've not managed to get this working before and If i can get a working example and some help to show where I'm going wrong would really help.
Approach 1 (using existing html):
Hide with css:
#selAsset {
display:none;
}
Then jQuery:
$(function(){
var selCategory = $('#selCategory');
$(selCategory).change(function() {
$('option:selected').each(function() {
if($(this).text() === '3') {
jQuery('#selAsset').show();
}
});
});
});
This uses text() to check the selected option. In your code there is no need for .chosen() and you can change this: $(.selAsset).show(); to this: $('#selAsset').show(); (to match the html).
Demo: http://jsfiddle.net/dRM92/1/
A better approach (from comments):
We can use .change(function(){ and a switch case to check the option's value; then manipulate accordingly.
var selCategory = $('#selCategory');
var selAsset = $('#selAsset');
selCategory.change(function() {
switch ($(this, 'option:selected').val()) {
case "3":
selAsset.show();
break;
case "please select":
selAsset.hide();
break;
}
});
This is more extendable than the previous approach. There are many ways to check an option's value or text; for this instance we need to check the selected value only and the argument/s you wish to have.
Demo: http://jsfiddle.net/gzWGQ/1/

load() isn't working within PHP echo

I have the following snippet on my index page so that all links clicked on within the navbar will load within the 'content' div:
$(document).ready(function()
{
$("a.link").click(function() {
return false;
});
$("#navbar a").click(function(){
var a_href = $(this).attr('href');
$("#content").load(a_href);
});
});
This snippet works fine... But upon loading the page, I check with PHP to see if the index page has an argument to direct it to a specific page, which doesn't seem to work:
<?php
if(array_key_exists('page',$_GET)){
echo "<script>$('#content').load('" . $_GET['page'] . "', 'content')</script>";
} else {
echo "<script>$('#content').load('home.php')</script>";
}
?>
It may be a simple case of "it's staring you in the face but you've been looking at it for too long", but I can't seem to get the PHP snippet to work.
EDIT: I wrapped it in document.ready(), and it doesn't seem to have had an effect:
echo "
<script>
$(document).ready(function()
{
$('#content').load('home.php');
});
</script>";
Try this
<?php
echo "<script>"
echo "$(document).ready(function () {";
if(array_key_exists('page',$_GET)){
echo "$('#content').load('" . $_GET['page'] . "', 'content');";
} else {
echo "$('#content').load('home.php');";
}
echo "});";
echo "</script>";
?>

change div containing checkbox attributes when checked

this is my javascript that allows for a filter search field ...
function escape4regex(text)
{
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
function searchRegExFieldKeyUp()
{
var table = document.getElementById('ModelFilter');
var cells = table.getElementsByTagName('div');
var searchterms = escape4regex(this.value);
var regVar = '(?=.*' + searchterms.replace(/\s/g, '.*)(?=.*') + '.*)';
var i=cells.length;
while (i--)
{
var cell = cells[i];
var rowStr = cell.innerHTML;
// remove all tags
rowStr = rowStr.replace(/<(?:.|\n)*?>/gm, '').replace(/\n|\s{2,}/gm, ' '); // searches whole row
var regex = new RegExp(regVar,"gi");
var result = (regex.test(rowStr));
if(result)
{
cell.style.display = "";// check if compat with IE
}
else
{
cell.style.display = "none";
}
}
}
this creates checkboxes from databse inputs
<div id="ModelFilter">
<?php
while ($row = mysqli_fetch_assoc($result))
{
echo"<div class=\"modelfilter_td\" id=\"modelfilter_td\">";
echo"<input type=\"checkbox\" id = \"$row[ModelID]\"
name = \"selectedModels[]\"value =\"$row[Model]\" onclick=\"chkcontrol.apply(this);\">";
echo "$row[Model]";
echo"</div>";
}
echo"</div>";
I want to do the following :
when the checkbox is checked, it stays visible, even if it is not in the search terms of the filter field.
when the checkbox is checked , the background color is changed.
the checkbox and the title for the checkbox is held within a div, I want to allow the user to click anywhere in the div to allow toggling of the checkbox.
Anyone start me ont the right track with this?
EDIT: here is a solution to problem "3."
<script language="javascript">
$(document).ready(function(){
$(".modelfilter_td").click(function(e){
var chk = $($(this).find("input[type='checkbox']"));
if(chk.attr('checked'))
{
chk.attr('checked',false);
}else{
chk.attr('checked',true);
}
});
});
This is not a solution for you problem, but a recommendation on php-usage in html context:
<div id="ModelFilter">
<?php while ($row = mysqli_fetch_assoc($result)): ?>
<div class="modelfilter_td" id="modelfilter_td">
<input
type="checkbox"
id="<?php echo $row['ModelID'] ?>"
name="selectedModels[]"
value="<?php echo $row['Model'] ?>"
onclick="chkcontrol.apply(this);"
>
<?php echo $row['Model'] ?>
</div>
<?php endwhile ?>
</div>
This enables most IDEs to deal with HTML-autocompletion and code-analysis.

Categories