I have some problem with this code and don't know how to fix it.
<?$result_bandeau_new_TOP_M = mysql_query("SELECT count(customers_id) from tbl_customers WHERE goods='Swimwear' and model='Bandeau'");?>
<p><span class="fon-assort">S : <?php echo mysql_result($result_bandeau_new_TOP_S, 0);?> </span></p>
I want to hide span with numeric value = 0.
This JavaScript code is not working and I don't know why
$function isItANumber() {var increased = parseInt($(".fon-assort").text());
if(isNaN(increased) || increased <= 0) {$(".fon-assort").hide();
}
}
isItANumber();
Maybe i can do this by php, but i don't know how, so.. i try to do this by Query.
There are lots of issues with the code you posted, but the change to the second line that makes the difference you want should be something like:
<?php
$count = mysql_result($result_bandeau_new_TOP_S, 0);
if( $count != 0) {
echo '<p><span class="fon-assort">S : <a href="somelink">' +
$count
+'</a></span></p>';
}
?>
And if combining with the existing first line, you don't need the
?>
<?php
In general you should stop using the deprecated mysql_* syntax. Use mysqli_* or PDO instead. See comparison here.
in my opinion you should hide span using php.
so your code should look like:
<?php
$result_bandeau_new_TOP_M = mysql_query("SELECT count(customers_id) from tbl_customers WHERE goods='Swimwear' and model='Bandeau'");
$data = mysql_result($result_bandeau_new_TOP_S, 0);
?>
<p>
<?php if ($data!=0): ?>
<span class="fon-assort">S : <?=$data;?> </span>
<?php endif; ?>
</p>
You can use jQuery specific selectors. By using the > you are saying, every element under the .fon-assort is what I want.
Then, you loop through each seperate item, get the text value as a number with parseInt, and do a typesafe check with === if it equals 0, if so, hide the parent .fon-assort element
Also, I suggest you don't use the mysql_xxxx functions, but learn mysqli or pdo and use prepared statements for your queries. the mysl_xxx queries are depricated. that means they will vanish at some point because they are obsolete, and usage is strongly advised against.
$('.fon-assort > a').each(function(index,elem) {
var $this = $(elem);
if(parseInt($this.text().trim()) === 0) {
$this.closest('.fon-assort').hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><span class="fon-assort">S : 0</span></p>
<p><span class="fon-assort">S : 4</span></p>
<p><span class="fon-assort">S : 2</span></p>
<p><span class="fon-assort">S : 0</span></p>
Related
Sorry for asking, I am probably missing something small here but have no clue. I dynamically generated a long list of radio buttons using PHP. On top of the list is an HTML input to search through the list using jQuery. This works, except for one tiny detail. The first radio button in the list always shows, no matter what the search result is. Even if I type something completely different, I will always see the first radio button in the list together with the matching results.
What is going wrong here?
This is my dynamically generated list of radio buttons, using HTML and PHP:
<input id="addplantSearch" class="form-control" type="text" name="addplantsearch" placeholder="Zoek op (Latijnse) naam..." style="margin:0; height:48px;"> <!-- Search input -->
<?php
$query = "SELECT * FROM plants ORDER BY plants.name ASC;";
$post_data = $data->execute($query);
// Prepared statement in 'execute' method (Database class)
?>
<div class="addplant-list">
<?php
foreach ($post_data as $post) {
# Loop start
?>
<div class="searchable">
<label class="pselect-container"> <?php echo $post['name']; ?>
<input type="radio" name="selectPlant" value="<?php echo $post['plant_id']; ?>">
<span class="pselect-checkmark" style="width:100%;">
<img src="../system/src/img/plants/<?php echo $post['directory']; ?>/icon.png" />
<?php echo $post['name'] . " - (" . $post['name_latin'] . ")"; ?>
</span>
</label>
</div>
<?php
# Loop end
}
?>
</div>
And this is my jQuery, responsible for searching through the list:
$("#addplantSearch").keyup(function() {
var value = this.value;
$(".addplant-list").find(".searchable").each(function(index) {
if (!index) return;
var id = $(this).find("span").first().text();
$(this).toggle(id.indexOf(value) !== -1);
});
});
EDIT: The first item in the list is determined by the alphabetical order (ASC) of my database results (see $query variable). So this is always the same item in alphabetical order.
It looks like your issue is with your if statement.
if (!index) return;
This problem occurs because JavaScript uses 0 based arrays, and 0 is also a falsy value. Meaning:
!0 === true
and the first item in the array will always return out of the function and won't be applicable to the toggle logic.
So probably a lot of ways to work around this, one would be to check the length of the array before the each function. Ex:
$("#addplantSearch").keyup(function() {
var value = this.value;
var searchableItems = $(".addplant-list").find(".searchable");
if (searchableItems.length) {
searchableItems.each(function(index) {
var id = $(this).find("span").first().text();
$(this).toggle(id.indexOf(value) !== -1);
});
}
});
I have a <td> in my html code that contains <a>. I want to give href to that anchor tag based on if-else statment.
for example: <td> if var=1 then <a herf="1"></a> else <a herf="2"></a>
</td>. Any ideas how can I do that please?
If you want to do it with PHP.
<td>
<?php if($var == 1) { ?>
<?php }else if($var == 2){ ?>
<?php } else { ?>
<?php } ?>
</td>
It's too much easy then you are thinking,
in php you can do that in following way-
<?php
$var=1;
?>
<td>
<a href="<?php if($var==1) echo "link1"; else echo "link2"; ?>" >Your Link Name</a>
</td>
There are more way to do that.
You can also do that in the following way if you only have few conditions:
This is the link by conditions
There are few ways to do this so these are just a couple more suggestions.
In all cases $var needs it's value to be checked (validated) that it is within the expected valid range.
This is procedural. Method 1 of n.
<?php
// Procedural method
// =================
// Determine the link to use dependant upon value of $var
// for testing set $var here
$var = 1;
// $url amd $link_name is always being set to something
switch ($var){
case 1:
$url = 'link1';
$link_name = 'link1';
break;
case 2:
$url = 'link2';
$link_name = 'link2';
break;
// Can add in as many links as you like.
default:
$url = '#';
$link_name = 'Invalid Link';
}
?>
<!-- Create the link -->
<td>
<?= $link_name; ?>
</td>
This is procedural. Method 2 of n.
<?php
$var = 1; // Used for debugging
// If $var is an integer it can be used to index into an array
$url_array = array(
array('url' => 'link1','link_name' => 'link1'),
array('url' => 'link2','link_name' => 'link2'),
array('url' => 'link3','link_name' => 'link3')
);
// Need to check $var is in between 1 and the maximum link count
$url_entry = $url_array[$var - 1]; // offset by 1 as arrays begin at index = 0
?>
<!-- Create the link -->
<td>
<?= $url_entry['link_name']; ?>
</td>
The idea here is to determine the link values to be used outside of the HTML (business logic) and then create the HTML (The View) with the required values.
You could take this even further but hopefully this gives you something to think upon.
Have fun.
Depending on the user type, my page dynamically creates either a select element (for admins to change) or a div with text (for regular users) using the same id.
if ($user_type == 'admin') {
echo "<tr><td>Type:</td><td><select id='type' >";
echo "<option value='student' >student</option><option value='teacher' >teacher</option>";
echo "</select></td></tr>";
}
else echo "<tr><td>Type:</td><td><div id='type'>" . $user_type . "</div></td></tr>";
When the page submits, I need either the .val() from the select element or the .text() from the div element.
I can't use .val() on the div element and I can't use .text() on the select element.
Is there a way in jQuery / javascript to get one or the other, depending on which element type was created?
make the else statement as so (use input[type=hidden], to use the .val())
else echo
"<tr>
<td>Type:</td>
<td>
<!-- div to show the value -->
<div>$user_type</div>
<!-- hidden input type to get the value via jQuery .val() -->
<input type='hidden' id='type' value='$user_type'>
</td>
</tr>";
Oh by the way, you can use PHP variables inside strings that are defined with double quotes echo "$someVar";
Since you are printing out from PHP the HTML out put, by the same time you can print a Javascript variable who has what method use to get the value/text. Then, use the variable in your Javascript to perform one query or other.
Something like :
if ($user_type == 'admin') {
echo "<tr><td>Type:</td><td><select id='type' >";
echo "<option value='student' >student</option><option value='teacher'>teacher</option>";
echo "</select></td></tr>";
echo "<script> var method = 'val'</script>";
}
else
{
echo "<tr><td>Type:</td><td><div id='type'>" . $user_type . "</div></td></tr>";
echo "<script> var method = 'text'</script>";
}
You can check it with the following simple code in javascript:
if(document.getElementById("type").tagName == "SELECT") {
//Your code for admin
}
else
{
//Your code if it is not admin
}
You can have the text or the value with a simple and elegant ternary condition :
var result = $("#type").val() !== undefined ? $("#type").val() : $("#type").text();
I have the following html code:
<?php foreach ($this->tags as $uri=>$tag){?>
<input type="checkbox" name="tags[]" style="display: none;" value="<?php echo $uri;?>" id="create_<?php echo $uri;?>" <?php echo isset($args['tags']) && in_array($uri, $args['tags'])?'checked="checked"':'';?> />
<span onclick="selectTag(this.id)" id="create_<?php echo $uri;?>" for="create_<?php echo $uri;?>" class="tag <?php echo isset($args['tags']) && in_array($uri, $args['tags'])?'selected':'';?>"><?php echo str_replace(' ', ' ', $tag);?></span>
<?php }?>
And here is my JS code:
function selectTag(id) {
var input = '.tags input#'+id;
var span = '.tags span#'+id;
if ($(input).is(':checked') && $(span).hasClass('selected')) {
$(span).removeClass('selected');
$(input).attr('checked', false);
}
else {
$(span).addClass('selected');
$(input).attr('checked', true);
}
}
When I click on a span box, selects the box, and when I click again on it, it unselects it. The problem is, that after the 3rd time, it just stops working.
What is wrong with my code that is not working?
JQuery now has a prop method that is a slightly better alternative to using the attr method.
Try replacing your calls with attr("checked", true); with calls to prop("checked", true);
See here for documentation on prop: http://api.jquery.com/prop/
Here for a discussion between the two: .prop() vs .attr()
Edit:
Also, as Ed Cottrell stated, you'll want to have UNIQUE id attributes for all your elements on your page.
Edit2:
I have created a fiddle that demonstrates this usage: http://jsfiddle.net/xDaevax/E39hc/
You are giving the input and the span the same id attribute. Ids must be unique per element; you cannot have an input and a span the same id. Doing it this way will cause all sorts of problems, including the behavior you are experiencing. Give one of them a slightly different id (like create_<?php echo $uri;?>_span).
Also, as #xDaevax says, you should use .prop rather than .attr -- I have had the same problem when using .attr.
I am fetching rows with title & its description from MySQL database.
I want to alter the strings that I got from the database.
<div class="title"><?php $row['title']?></div>
<div class="details"><?php $row['desc']?></div>
So please tell me, how to apply javascript to this content ($row['..'])? Means, how I can access those strings in Javascript?
If the string length is more than 50 characters, I want to limit the string & add dots (...) to it.
It is better to use mb_substr() than substr()
<?php
echo mb_substr($row['title'],0,50);
Source
You can do this using substr.
<?php echo (strlen($row['desc']) > 50) ? substr ($row['desc'] , 0, 50 ).'...' : $row['desc']; ?>
Why do that? Html has a css for that. you can fix the width and add the "text-overflow:ellipsis".
Try this:
<div class="fixedWidth title"><?php $row['title']?></div>
<div class="fixedWidth details"><?php $row['desc']?></div>
<style>
.fixedWidth{
width:200px;
white-space: nowrap;
overflow: hidden;
text-overflow:ellipsis;
}
</style>
If you are working with non-ASCII strings and you want to manipulate those then substr() is wrong to use. Instead you should use multibyte string functions, like mb_substr() and others.
For that you must have mbstring-extension enabled for PHP. see http://php.net/manual/en/mbstring.installation.php
I would also not directly echo string for using javascript - you never know what chars could be there and then you should start to escape some chars to work properly with javascript.
Instead I would encourage you to use json_encode. This will escape properly all special and UTF8-chars.
PECL's json-extension must be enabled for json_* functions. See http://php.net/manual/en/json.installation.php
Of course if you are using Zend-framework, then proper would be use Zend_Json::encode()
<?php
$maxLength = 50;
$encoding = 'UTF-8';
$tail = ' ...';
$row['desc'] = (mb_strlen($row['desc'], $encoding) > $maxLength) ? mb_substr($row['desc'], 0, $maxLength, $encoding) . $tail : $row['desc'];
?>
<script type="text/javascript">
var rowData = <?php echo json_encode($row); ?>;
alert(rowData.desc);
</script>
why don't you try in directly php scripting insted of javascript.
you can make it as below.
<div class="title"><?php echo $title = strlen($row['title']) > 50 ? substr($row['title'], 0, 50)."..." : $row['title']; ?></div>
Then you can get the title in javascript as well.
$(document).ready(function(){
var title = $(".title").text();
});