EDIT:
Ive edited my code a little thanks to Alexander's advice, but im still getting the problem of the contents of the div not showing, ive looked up proper closing and cant see where else or if i need to add it anywhere else in the code. My update question is, what am i missing for this to work? Thanks
I have a table which is generated from a query, in this table there is a div, i need this div to show/hide onclick, now i have a working show/hide javascript (shown below) but this only works for 1 div.
how do i modify this so that my divs with id's generated from my database ($id) can all be shown/hidden seperatly?
javascript:
<script language="javascript">
function toggle(id) {
var ele = document.getElementById(id);
var text = document.getElementById(id);
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "show";
}
else {
ele.style.display = "block";
text.innerHTML = "hide";
}
}
</script>
html:
Info: <a id='$id' href='javascript:toggle(\"$id\");'>show</a>
<div id='$id' style='display: none'></div>
in your generated HTML you can pass id value to your toggle() function so resulting HTML code will look like
Info: <a id='$id' href='javascript:toggle("$id");'>show</a>
<div id='$id' style='display: none'></div>
javascript
function toggle(id) {
var ele = document.getElementById(id);
var text = document.getElementById(id);
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "show";
}
else {
ele.style.display = "block";
text.innerHTML = "hide";
}
}
Related
I'm trying to implement an expanding searchbox in wordpress. I have applied the HTML in my search-form.php and CSS in my style.css. However, I'm not sure how to apply the Jquery part. Is it as follows:-
add_action ('wp_footer','vr_search_head',1);
function vr_search_head() {
?>
<script>
$(document).ready(function(){
var submitIcon = $('.searchbox-icon');
var inputBox = $('.searchbox-input');
var searchBox = $('.searchbox');
var isOpen = false;
submitIcon.click(function(){
if(isOpen == false){
searchBox.addClass('searchbox-open');
inputBox.focus();
isOpen = true;
} else {
searchBox.removeClass('searchbox-open');
inputBox.focusout();
isOpen = false;
}
});
submitIcon.mouseup(function(){
return false;
});
searchBox.mouseup(function(){
return false;
});
$(document).mouseup(function(){
if(isOpen == true){
$('.searchbox-icon').css('display','block');
submitIcon.click();
}
});
});
function buttonUp(){
var inputVal = $('.searchbox-input').val();
inputVal = $.trim(inputVal).length;
if( inputVal !== 0){
$('.searchbox-icon').css('display','none');
} else {
$('.searchbox-input').val('');
$('.searchbox-icon').css('display','block');
}
}
</script>
<?php
}
search box from http://codepen.io/nikhil/pen/qcyGF/
I tried applying the above code in my child themes functions.php but it doesnt seem to work. On clicking search, the search box doesnt open.
Thanks
I'm using bootstrap for website. I include Ajax, css and PHP to show Auto Suggestions for mp3 search. Everything is working fine but an issue happened. I tried with different way but the issue is still there.
The Issue
When type keyword it show suggestion. (OK)
When you click on keyword from suggestion it works. (OK)
But when we erase keyword and click on anywhere at page then page content reload and shown as u can see in picture.
Url of website is http://www.4songs.pk
Code in header
<script src="http://www.4songs.pk/js/jquery-1.10.2.js"></script>
<script>
$(function(){
$(document).on( 'scroll', function(){
if ($(window).scrollTop() > 100) {
$('.scroll-top-wrapper').addClass('show');
} else {
$('.scroll-top-wrapper').removeClass('show');
}
});
$('.scroll-top-wrapper').on('click', scrollToTop);
});
function scrollToTop() {
verticalOffset = typeof(verticalOffset) != 'undefined' ? verticalOffset : 0;
element = $('body');
offset = element.offset();
offsetTop = offset.top;
$('html, body').animate({scrollTop: offsetTop}, 500, 'linear');
}
</script>
<script type="text/javascript">
var myAjax = ajax();
function ajax() {
var ajax = null;
if (window.XMLHttpRequest) {
try {
ajax = new XMLHttpRequest();
}
catch(e) {}
}
else if (window.ActiveXObject) {
try {
ajax = new ActiveXObject("Msxm12.XMLHTTP");
}
catch (e){
try{
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
return ajax;
}
function request(str) {
//Don't forget to modify the path according to your theme
myAjax.open("POST", "/suggestions", true);
myAjax.onreadystatechange = result;
myAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myAjax.setRequestHeader("Content-length", str .length);
myAjax.setRequestHeader("Connection", "close");
myAjax.send("search="+str);
}
function result() {
if (myAjax.readyState == 4) {
var liste = myAjax.responseText;
var cible = document.getElementById('tag_update').innerHTML = liste;
document.getElementById('tag_update').style.display = "block";
}
}
function selected(choice){
var cible = document.getElementById('s');
cible.value = choice;
document.getElementById('tag_update').style.display = "none";
}
</script>
The 2nd issue
When auto suggestions load it also include some empty tags as you can see in picture
I take this picture as doing Inspect Elements
PHP Code are clean
<?php
include('config.php');
if(isset($_POST['search']))
{
$q = $_POST['search'];
$sql_res=mysql_query("SELECT * FROM dump_songs WHERE (song_name LIKE '%$q%') OR (CONCAT(song_name) LIKE '%$q%') LIMIT 10");
while($row=mysql_fetch_array($sql_res))
{?>
<li><a href="javascript:void(0);" onclick="selected(this.innerHTML);"><?=$row['song_name'];?></li>
<?php
}
}?>
In the function request(str) put an if statement to check if str length is greater than zero.
function request(str) {
if(str.length > 0)
{
// Your existing code
}
else
{
document.getElementById('tag_update').innerHTML = '';
}
}
In short words the problem you are describing is happping because the str parameter in the data that you send to /suggestions is empty. The server returns 304 error which causes a redirect to the root page. Your js script places the returned html into the suggestion container. And thats why you are seeing this strange view.
-UPDATE 1-
Added the following code after user request in comments
else
{
document.getElementById('tag_update').innerHTML = '';
}
-UPDATE 2- (16/07/2014)
In order to handle the second issue (after the user updated his question)
Υou forgot to close the a tag in this line of code
<li><a href="javascript:void(0);" onclick="selected(this.innerHTML);"><?=$row['song_name'];?></li>
I have a bunch of items setup with <div id="first" class="source">
I'm in Google Chrome, and when page loads it hides those items when I click the OnClick button it will un hide them, but I'm not able to click it again and make it hide.
HTML
<body onload="setup();">
<a href="#first" onClick="shoh('first');" >
JS:
function setup() {
foo = document.getElementById('first');
foo = document.getElementsByClassName('source');
for (c=0; c<foo.length; c++) {
foo[c].style.display='none'
}
}
function shoh(id) {
if (document.getElementById(id).style.display = 'none'){
var divs = document.getElementById(id);
for(var i=0; i<divs.length; i++) {
divs[i].style.display='block'
}
} else {
cow = document.getElementById(id);
for(a=0; a<cow.length; a++) {
cow[a].style.display='none'
}
}
}
Your conditional isn't doing a comparison. You need to change
if (document.getElementById(id).style.display = 'none'){
to
if (document.getElementById(id).style.display == 'none'){
You have a couple of issue here:
If you compare two variables you need to use ==, so therefore it should be:
document.getElementById(id).style.display == 'none'
Also, you are using getElementById, which returns a single node, not an array. So therefore you should not loop over the returned value:
var div = document.getElementById(id);
div.style.display='block';
So in the end, it should look like this:
function shoh(id) {
if (document.getElementById(id).style.display == 'none'){
var div = document.getElementById(id);
div.style.display='block';
} else {
cow = document.getElementById(id);
cow.style.display='none';
}
}
I want to toggle divs by clicking on links. but things are not going well for me when I click on a link it shows a new div but don hide the previous one
JavaScript Code
<script type="text/javascript">
function toggle(id){
var el = document.getElementById(id);
if(el != null && el.style["display"]== 'none'){
el.style["display"] = "block";
}
}
</script>
My divs code
<?php foreach($titles_data as $title){ ?>
<div style="display:none" id="content_<?php echo $title['idtitles'] ?>">
<div id="left-ad"></div>
</div>
<?php } ?>
My links code
<?php foreach($titles_data as $title){ ?>
<li class="flag_<?php echo strtoupper($title['language']) ?>">
<a id="title_<?php echo $title['idtitles'] ?>" href="" title="<?php echo $title['title'] ?>" onclick="toggle('content_<?php echo $title['idtitles'] ?>')">
</a>
</li>
<?php } ?>
How can it be done so that when i click on link its respective iv becomes visible and the previous one hides?
Thanks
Using native JS:
function toggle(id){
var el = document.getElementById(id);
el.style.display = el.style.display == "none" ? "block" : "none";
}
toggle("myId");
Using jQuery:
function toggle(selector) {
$(selector).toggle();
}
toggle("#myId");
To toggle the display, you dont need to do that much
$("#elementid").toggle();
In reference to your question
$('a').click(function() { // however this is select all anchors, better use class
// selector like $(".mylinkclass")
var id= $(this).attr('id'); //get the id
var ids = id.splite("_"); //split the id on "_", to extract the idtitles
$("#content_"+ids[0]).toggle(); // use that to toggle
});
Assuming that there is always only one div that is displayed, you can check for it:
Alter your logic, to declare a global variable to hold the value of the currently visible div. And then update that variable whenever a link is clicked, to hold the id of the currently visible div. So, using your exisitng code, you can do this :
using core javascript:
var visibleDiv;
function toggle(id){
// hide the previous div using visibleDiv
if(document.getElementById(visibleDiv)!= null) document.getElementById(visibleDiv).style["display"] = "none";
var el = document.getElementById(id);
if ( el.style["display"] == "" || el.style["display"] == 'none' ){
el.style["display"] = 'block';
}
visibleDiv = id; // update the current visible div name
}
using jquery like this :
var visibleDiv;
$("[id^=content_]").each(function() {
if($(this).is(':visible')){
visibleDiv = $(this).attr('id');
}
});
Check my new answer. I just created the sample html page, with 3 divs. Initially all are shown. When you click on one of them, it is hidden. When you click on some other div. The old one is made visible again and the current one is hidden. Modify the logic as per your requirements.
<html>
<head>
<title>asdsa</title>
<script type="text/javascript">
var visibleDiv;
function toggled(id){
//$('#div_2').html($('#div_1').html());
if(document.getElementById(visibleDiv) != null){ document.getElementById(visibleDiv).style["display"] = "block";}
var el = document.getElementById(id);
document.getElementById(id).style["display"] = "none";
visibleDiv = id;
}
</script>
</head>
<body>
<div id="div_1" onclick="toggled('div_1')">div1</div>
<div id="div_2" onclick="toggled('div_2')">div2</div>
<div id="div_3" onclick="toggled('div_3')">div3</div>
<hr/>
</body>
</html>
Thanks.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Call php function from javascript
I understand that php is server side and JavaScript is client side. But I would like to know how to run a PHP method when a JavaScript function is called. Below is my code, I know the error is but how can I perform the php method?
<script type="text/javascript">
function toggle()
{
var ele = document.getElementById("addCatTextBox");
var text = document.getElementById("addCatButtonText");
if(ele.style.display == "block") {
ele.style.display = "block";
text.innerHTML = "Save category";
<?php Category::addCategory($inCatName)?>
}
else {
ele.style.display = "none";
text.innerHTML = "Add new category";
}
}
</script>
Thanks for your help.
Using the Prototype library (www.prototypejs.org):
Javascript:
<script type="text/javascript">
function toggle()
{
var ele = document.getElementById("addCatTextBox");
var text = document.getElementById("addCatButtonText");
if(ele.style.display == "block") {
ele.style.display = "block";
text.innerHTML = "Save category";
var options={
method: 'get',
parameters: 'inCatName='+ele.value,
onSuccess: function(xhr) {
// TODO: Whatever needs to happen on success
alert('it worked');
},
onFailure: function(xhr) {
// TODO: Whatever needs to happen on failure
alert('it failed');
}
};
new Ajax.Request('addCategory.php', options);
}
else {
ele.style.display = "none";
text.innerHTML = "Add new category";
}
}
</script>
addCategory.php:
<?php
$inCatName=isset($_REQUEST["inCatName"]) ? $_REQUEST["inCatName"] : null;
Category::addCategory($inCatName);
?>
The idea is that the Javascript sends a GET (or it could be POST) request to the addCategory.php page behind the scenes, passing it whatever info it needs to create the category.
Hopefully this is enough to get you going. There's a lot missing from my code - you'll need to validate the variables addCategory.php receives and perform any other pertinent security checks before letting it anywhere near the database. addCategory.php will also require any include files, etc so that it knows about your Category class. Finally, addCategory.php should really return some form of variable back to the Javascript code that called it so that it knows what the outcome was.
You can use an Ajax request to an endpoint that triggers your PHP and then perform Category::addCategory($inCatName)
With Jquery:
$.ajax({
url: "addCategory.php",
context: document.body,
success: function(){
// whatever you need to do
}
});
This might help. Use ajax to call you php file (categories.php was used in the example). Send a parameter called "function" and set it as "addCategory". In your php file write code to detect if $_GET['function'] is set and also to detect if it is set as "addCategory". If it is, have the code call the function. I also saw that you were trying to pass the $inCatName parameter to the php function. To send this just add it into the url below.
<script type="text/javascript">
function toggle()
{
var ele = document.getElementById("addCatTextBox");
var text = document.getElementById("addCatButtonText");
if(ele.style.display == "block") {
ele.style.display = "block";
text.innerHTML = "Save category";
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","categories.php?function=addCategory",true);
xmlhttp.send();
}
else {
ele.style.display = "none";
text.innerHTML = "Add new category";
}
}
</script>