I have a table that displays items from a database. One of the items is a description so it can be very long.The thing I'm having the most problem with is how can I use JS and HTML smoothly in my controller class.
I want to be able to display a little bit of it if its longer than 100 char, and a button that looks like '...' where if the user clicks on it, it displays the trimmed text. I want to do this using javascript and here is what I tried, this code is in my controller, so I'm just sending these to the view.
The problem is when I press the button it doesn't display anything so what is wrong here? Some suggested to use jquery but I don't want to write my js script elsewhere and call it again since I'm not sure how I will do that in Phalcon controller.
$this->view->tblColumns = [
'element one',
'element two',
function (tablename $instance) {
if (strlen($desc = $instance->getDescription()) > 100) {
return $shortDesc = substr($instance->getDescription(), 0, 100) . '
<button style="background: none;border: none" onclick="(function(){
var desc= <?php echo
$desc; ?>; document.write(desc) ;
})()" >...</button>';
} else {
return $instance->getDescription();
}
},
do NOT use document.write after load of the page. It will wipe the page
your desc needs to be in single quotes and have no carriage returns.
you cannot use an IIFE in an onclick unless it returns a function
if your button is in a form, you will submit the form - it should be type=button
You MAY mean
<button type="button" onclick="var desc='<?php echo $desc; ?>';
document.querySelector('#someContainer').innerHTML=desc;"...>
but a better way is to toggle the existing text inside tags (span for example)
I find a way to do what I wanted, using the code for read more,read less from this link https://codepen.io/maxds/pen/jgeoA
The thing I was having trouble with in phalcon MVC, was that I didn't know I could my java-script, and css in the view of the controller and that's what I did.
I just used the js from that link, into my view file, the same for the css using tag and tag.
And in the function on the controller I wrote the following `
$this->view->tblColumns = [
'one',
'two',
function(tablename $link){
$desc=$link->getDescription();
$html=<<<HTML
<span span class="more"> $desc</span>
HTML;
return $html;
}`
Related
I tried following the information here, editing it to match my needs, but so far it's not working.
I'm trying to hide a parent div with two child elements. The parent div is part of a list, all with the same classes, and each div has two child elements: an input, and an image. Each input has a unique "data-wapf-label" that I'm trying to select so that I can hide the parent div. The HTML is as follows:
<div class="has-pricing wapf-swatch wapf-swatch--image">
<input type="radio" id="wapf-field-61b148f2fc8fe_lzhx7" name="wapf[field_61b148f2fc8fe]" class="wapf-input" data-field-id="61b148f2fc8fe" value="lzhx7" data-wapf-label="Peppermint Mocha" data-is-required data-wapf-pricetype-"fx">
<img src="...">
</div>
There are several pages where this product shows up, and rather than going in and deleting the product field (because I'll just have to add it again next season), I'm trying to create a piece of code that will hide all the divs for all the products that have the above code (since each has a unique "id", I'd have to do it several times for each id using "selectElementById", and I'd like to avoid doing that, obviously).
I installed Code Snippets, but I'm having a bit of trouble with the Javascript. I should add that Code Snippets inserts code to the website via php (so php tags are required with every snippet). I've tried several things, but this is my latest version. It throws a syntax error "unexpected 'hideFlavors' (T_STRING), expecting '('".
Here's my php/Javascript code:
<?php
add_action( 'wp_head', function hideFlavors() { ?>
<script>
if var peppermintMocha = document.querySelectorAll("[data-wapf-label='Peppermint Mocha']") {
peppermintMocha.parentNode.style.display = "none";
}
</script>
<?php } );
I've also tried it with "document.querySelector" (without the "All"), but with the same or similar problem. When I do get the code to actually go through without any errors, it still doesn't fix the problem.
At this point, I feel a little like the guy looking through the tank's periscope on "Independence Day". No matter what I do, "target remains".
<?php
add_action( 'wp_head', function() {
?>
<script>
window.onload = function() {
document.querySelectorAll("[data-wapf-label='Peppermint Mocha']").forEach(function(el) {
el.parentNode.style.display = "none";
});
};
</script>
<?php
});
?>
querySelectorAll returns an array of elements, so you need to loop through each element and hide their parent respectively.
Instead querySelectorAll use querySelector. Then it would be work. But make sure that exists only one input field with the selector [data-wapf-label='Peppermint Mocha'].
I want to populate a jQuery dialog with dynamic content from a getData.php file. That works fine so far via:
$("#buttonGetData").click(function() {
$.get("getData.php", function(data){
$("#dialog").html(data);
$("#dialog").dialog();
return false;
});
});
The getData.php just gives something back like:
<p id="data1" class="data">data1</p>
<p id="data2" class="data">data2</p>
<p id="data3" class="data">data3</p>
My problem now is: How do I add a dynamic click listener to each data row so I can use the clicked data in my site? I want each 'p' be clickable and then use the data inside for setting its content to a 'textarea'.
The problem seems to be, that the new dynamically added rows arent part of the JS from the site, so I can't reach them via a clickListener.
How would this be done correctly? Thank You!
When you get html related data result using Ajax like you used $(get)... , your newly generated html from Ajax cannot be used for jQuery code OR in other word jQuery/JS don't recognized your newly added html elements generated from Ajax. There is a way you can achieve your required result. You can send your jQuery/JS code with html codes to Ajax from your file (getData.php) as String.In your getData.php you can echo like this.
echo '<p id="data1" class="data">data1</p>';
echo '<script>';
echo "$(document).on('click', '#data1', function(){alert('DATA1 Clicked');});"
echo '</script>';
die();
Above may be very straight forward answer so there is another way which may be more convicting. You can also used delegation on based on event handler. Examples:
$("#dialog").on("click","p", function(){
alert("DATA1 Clicked");
// your code to add content of this element to textarea
});
$("#dialog").on("click","#data1", function(){
alert("DATA1 Clicked");
// your code to add content of this element to textarea
});
$(document).on('click', '#data1', function(){
alert("DATA1 Clicked");
// your code to add content of this element to textarea
});
One of them should be able to solve the problem.
I'm not really that familiar with php so hence the question. I have a list of products that is dynamically created via php. When a user clicks one of the generated lists it sorts the products. I also want to move the user to a new part of the page to see the results. I thought I could do this via an smooth scroll using an onchange, but I'm not that sure where to put it. Site is bootstrap so was going to use the scrolling-nav.js.
here is the php generating the list
<?php
echo '<div id="brands">';
// echo $product['name'].'<br>';
echo '<a href="#top-of-products"><input style="display:none"
type="checkbox" data-type="brand" onchange="showlist(this)"
id="b-'.$brand['id'].'" name="'.$brand['name'].'"
value="'.$brand['name'].'"><label id="b-'.$brand['id'].'"
for="'.$brand['name'].'">'.$brand['name'].'</label></a><br>';
}
echo '</div>';
Help much appreciated
You put short stretch of your code, but, I see a } lost before the last line.
I guess you put your code for scrolling a new part of the page in showlist() javascript function.
But, I don't know if onchange method is the better. I would use onclick method
Is the results panel always in the same location on the page? If so, and you're using the jquery library, consider using jquery's scrollTop function:
$('#item).click(function(){
$(html).scrollTop(val); //where val is the number of pixels hidden above the scrollable area when the Results panel is positioned where you want it to be
});
If the vertical position of the Results panel is variable, you can use this to define the "val" variable above:
$('#id-of-rewards-panel').offset().top
You might want to add a few pixels to that, because that will bring your element to the very top of the page
here is the whole code:
<?php foreach($view->brandfromcategory_data as $brand) {
echo '<div id="brands">';
// echo $product['name'].'<br>';
echo '<input style="display:none" type="checkbox" data-type="brand" onchange="showlist(this)" "scrollTo(#buttonreplacement)" id="b-'.$brand['id'].'" name="'.$brand['name'].'" value="'.$brand['name'].'"><label id="b-'.$brand['id'].'" for="'.$brand['name'].'">'.$brand['name'].'</label><br>';
}
echo '</div>';
?>
I have a webpage where admin users can edit the text on the page. But when they insert the text into the mysql database, it sometimes adds more and more white spaces before the acual content.
If you place your cursur before the first word on the page and spam backspace for a while, the whitespace in the database dissappears. But over time, the more you keep editing the page, more and more whitespaces are added again.
I did a lot of trouble shooting, but I just can't figure out what causes the whitespaces to be added. It does not always happen making it really difficult to troubleshoot.
Here's my code:
As my code is pretty long, I tried to translate most of the content to english.
If you want to translate something that in't already translated, the original language is Dutch.
over_ons.php - Shows edit button and page content from the database.
//Active page:
$pagina = 'over_ons'; ?>
<input type='hidden' id='pagina' value='<?php echo $pagina; ?>'> <!--Show active page to javascript--><?php
//Active user:
if(isset($_SESSION['correct_ingelogd']) and $_SESSION['functie']=='admin'){
$editor = $_SESSION['gebruikersnaam']; ?>
<input type='hidden' id='editor' value='<?php echo $editor; ?>'> <!--Show active user to javascript--><?php
} ?>
<!--Editable DIV: -->
<div class='big_wrapper'><?php
//Get eddited page content from the database
$query=mysql_query("SELECT inhoud FROM paginas WHERE naam_pagina='" .$pagina. "'");
while($inhoud_test=mysql_fetch_array($query)){
$inhoud=$inhoud_test[0];
}
//Show Content
?><div id='editedText'><?php echo $inhoud; ?></p></div>
<!--Show edit button-->
<?php
if(isset($_SESSION['correct_ingelogd']) and $_SESSION['functie']=='admin')
{?>
<div id='sidenote'>
<input type='button' value='Bewerken' id='sent_data' class='button' />
<div id="feedback" />
</div>
<?php }
javascript.js - Sents page content to the php file sent_data.php:
//If the system is in edit mode and the user tries to leave the page,
//let the user know it is not so smart to leave yet.
$(window).bind('beforeunload', function(){
var value = $('#sent_data').attr('value'); //change the name of the edit button
if(value == 'Verstuur bewerkingen'){
return 'Are you sure you want to leave the page? All unsaved edits will be lost!';
}
});
//Make content editable and send page content
$('#sent_data').click(function(){
var value = $('#sent_data').attr('value'); //change the name of the edit button
if(value == 'Bewerken'){
$('#sent_data').attr('value', 'Verstuur bewerkingen'); //change the name of the edit button
var $div=$('#editedText'), isEditable=$div.is('.editable'); //Make div editable
$div.prop('contenteditable',!isEditable).toggleClass('editable')
$('#feedback').html('<p class="opvallend">The content from<BR>this page is now<BR>editable.</p>');
}else if(value == 'Verstuur bewerkingen'){
var pagina = $('#pagina').val();
var editor = $('#editor').val();
var div_inhoud = $("#editedText").html();
$.ajax({
type: 'POST',
url: 'sent_data.php',
data: 'tekst=' +div_inhoud+ '&pagina=' +pagina+ '&editor=' +editor,
success: function(data){
Change the div back tot not editable, and change the button's name
$('#sent_data').attr('value', 'Bewerken'); //change the name of the edit button
var $div=$('#editedText'), isEditable=$div.is('.editable'); //Make div not editable
$div.prop('contenteditable',!isEditable).toggleClass('editable')
//Tell the user if the edditing was succesfully
$('#feedback').html(data);
setTimeout(function(){
var value = $('#sent_data').attr('value'); //look up the name of the edit button
if(value == 'Bewerken'){ //Only if the button's name is 'bewerken', take away the help text
$('#feedback').text('');
}
}, 5000);
}
}).fail(function() {
//If there was an error, let the user know
$('#feedback').html('<p class="opvallend">There was an error.<BR>Your changes have<BR>not been saved.<BR>Please try again.</p>');
});
}
});
And finally,
sent_data.php - Get page content from javascript,js and insert into database:
<?php
session_start();
include_once('./main.php');
include($main .'connectie.php');
//Look up which page has to be edited
$pagina=$_POST['pagina'];
//Get the name of the person who eddited the page
$editor=$_POST['editor'];
//Get content:
$tekst=$_POST['tekst'];
$tekst = mysql_real_escape_string($tekst);
$tekst = trim($tekst);
$query="UPDATE paginas SET naam_editer='" .$editor. "', inhoud='" .$tekst. "' WHERE naam_pagina='" .$pagina. "'";
}
if(mysql_query($query)){
echo "<p class='opvallend'>Successfully saves changes.</p>";
}else{
echo "<p class='opvallend'>Saving of changes failed.<BR>
Please try again.</p>";
}
?>
Extra information:
PHP version: 5.5.15
jQuery version: 1.11.1
Testing in browser: Chrome
Database: phpMyAdmin 5.5.39
The content is inserted in a VARCHAR type with space for 10000 caracters
Thanks in advance for you help!
SOLUTION
Thanks to the great help of a lot of people, and especially #avnishkgaur, it is working perfectly now. Here is what I ajusted (also changed it in my code above, so that's working code now).
1. Removed all the white spaces I had in my code between <div id='editable'> and <?php
2. Added $tekst = trim($tekst); to my PHP file to remove white spaces (didn't work)
3. Placed the editable text into another div as the code for getting the data from the database (was in the same div before)
4. Renamed the ID from the editable div to editedText. Also changed the name in the javascript file. This solution made it work perfectly (it was 'editable' before).
This was kind of an unexpected solution, so I think this could help others too.
As to why it is adding extra whitespace, I think it is because you are inserting the text from database into div directly (which contains some white space in html code, which is removed when page is rendered).
One efficient solution would be to insert your content in tag, probably like this:
<div class='big_wrapper'>
<p id='editable'></p>
</div>
Another solution is to trim the text before inserting into db. You can do that either at javascript post stage, or right before inserting in mysql db.
In jQuery, (which you are using) you can implement this :
data: 'tekst=' +$.trim(div_inhoud)+ '&pagina=' +pagina+ '&editor=' +$.trim(editor),
or in sent_data.php, you can use TRIM mysql function in your update query.
First of all, I would strongly suggest to use mysqli or PDO instead of the mysql functions in PHP, as these are deprecated. Please look into this on PHP.net.
As for your problem, I have no tried to reproduce the issue. I suggest you log and check what happens step by step, for example logging the div_inhoud var, are the spaces included at this stage already? And so on.
If you are in a hurry, you could also use the PHP function ltrim on the $tekst var in your sent_data.php, which would trim all spaces on the left side (Or any characters you would want to be trimmed from the string)
Try to add a trim() function in your send_data.php, this will help you to strip white spaces.
$tekst = trim($_POST['tekst']);
My guess is that the newlines after the <div id='editable'> and ?> and the indentation of <?php in over_ons.php is adding the extra whitespace. Specifically, a couple of extra /n's and also spaces from the indentation within the file.
You could trim the whitespace before saving it to your database, or alternatively, before the ajax call, or both.
In php, trim():
sent_data.php
$tekst = trim($tekst);
Or javascript, str.trim():
javascript.js
var div_inhoud = $("#editable").html().trim();
Also, you may want to consider using PHP Data Objects, instead of inserting variables directly into your SQL statements. It's actually really easy to use and in my opinion makes code easier to read and more reusable. There is a fantastic tutorial by Tuts+ that makes it easy to learn and get started. This will ensure you don't accidentally allow SQL injection issues into your application.
I am trying to make an independently working div which has a form inside of it.
I use jquery to calculate the price of a product depending of the user's selections in the form. However the user is able to add multiple items in his 'cart' so the form is duplicated to another div. The problem is that the calculation pattern can't separate these two divs and the calculation will be incorrect. The form is also interactive so it will be generated by the user's input. This is really complex set and renaming every variable by the 'product number' doesn't sound really efficient to me.
I'm kind of stuck here and i don't really know how to solve this problem. I had an idea that what if I put an iframe inside of the div and load my form and its calculation script inside of it, and then use post command to transfer the price of the product to the 'main page' to calculate the total price of all of the products the user wanted.
However it seems that jQuery scripts doesn't work independently inside of these iframes, they still have connection so they broke each other.
i will appreciate any kind of suggestions and help to solve this matter, thank you!
here's the code so far
Heres the body
var productNumber = 1;
<div id="div_structure">
</div>
<button id="newProduct" >Add new product</button><br \>
add new item
<!-- language: lang-javascript -->
$('#newProduct').click(function ()
{
$('<div id="productNo'+productNumber+'">')
.appendTo('#div_structure')
.html('<label onclick="$(\'#div_productNo'+productNumber+'\').slideToggle()">Product '+productNumber +' </label>'+
'<button onclick="$(\'#product'+productNumber+'\').remove()">Remove</button>');
$('<div id="div_product'+productNumber+'" style="display: none;">').appendTo('#product'+productNumber+'');
$('<iframe src="productform.html" seamless frameborder="0" crolling="no" height="600" width="1000">').appendTo('#div_product'+productNumber+'');
productNumber++;
});
it also has a function that allows the user to remove the inserted div.
Here's just few lines from the productform
$(document).ready(function()
{
$('#productCalculation').change(function ()
{
shape = $('input[name=productShape]:checked', '#productCalculation').val();
alert(shape);
});
});
<form id="productCalculation">
<div id="div_productShape" class="product1">
<h1>Select the shape of the product</h1>
<input type="radio" name="productShape" value="r1">R1</input><br \>
<input type="radio" name="productShape" value="r2">R2</input><br \>
<input type="radio" name="productShape" value="r3">R3</input><br \>
</div>
.
.
.
</form>
I translated all of the variables so they may not function correctly since i didn't test the translated version. So the problem is, if i try to make selections in the second generated div it wont even alert() the selected variable
There are two problems with this code: You say somewhere "I translated all of the variables so they may not function correctly since i didn't test the translated version. So the problem is, if i try to make selections in the second generated div it wont even alert() the selected variable". This is because event handlers are attached to elements that are in the DOM at that specific moment. To get it to work for all elements, use event delegation:
$(document).ready(function()
{
$(document).on( 'change', '#productCalculation', function ()
{
shape = $('input[name=productShape]:checked', '#productCalculation').val();
alert(shape);
});
});
Your other question is "My question in a nutshell: Is there a way to restrict jquery to function only in certain div even though i use the same variable names in the second div ". You can use the this variable to access the element the click was invoked on. From this element you can traverse the DOM if needed, for example with .parent().
$('div').on( 'change', function( e ) {
console.log( $(this).val() );
} );