Changing css over if condition - javascript

HTML:
<div id="register_error">
<?php
echo "$error_msg";
?>
</div>
JavaScript:
if(document.getElementById("register_error").innerHTML)
{
document.getElementById("signUpFormBackground").style.display = "block";
}
I want the JavaScript code to check every time the page loads if there is any text in the #register_error div, though my code doesn't seem to work, why is that? What am I missing? If any more information is needed just ask.
EDIT---------------------------------
I've cleared the whitespace as some of you said
<div id="register_error"><?php echo "$error_msg";?></div>
but it didn't helped, I think the problem is that this part of code never gets called,I haven't made it in function,I just wrote it in script tags. Also tried .trim() and .length() methods, but still same response.
EDIT2--------------------------------
I've made
enter code hereif(document.getElementById("register_error").innerHTML)
{
document.getElementById("signUpFormBackground").style.display = "block";
}
else
{
document.getElementById("signUpFormBackground").style.display = "block";
}
and nothing happens,so I guess my problem is that I don't even get my code to start working,I always thought that if I put it in between script tags it'll always run at least once as web loads,so how do I actually run it on windows load,I've already tried this:
<script>
window.onload
{
if (document.getElementById("register_error").innerHTML.length > 0 )
{
document.getElementById("signUpFormBackground").style.display = "block";
}
else
{
document.getElementById("signUpFormBackground").style.display = "block";
}
}
</script>
RESULT-----------------------------
Finally found my mistake,I didn't called the function and thought It'll do stuff without calling it, the code was fine.

Any amount of whitespace can throw off your .innerHTML check, and it looks like you have some already. try this:
<div id="register_error"><?php echo "$error_msg";?></div>
Javascript:
if(document.getElementById("register_error").innerHTML == '')
{
document.getElementById("signUpFormBackground").style.display = "block";
}
You can also check to see if innerHTML.length > 0:
if(document.getElementById("register_error").innerHTML.length > 0)
While not ideal, you can also move your error logic into your php:
<?php
if ($error_msg != '')
{
echo "<style>#signUpFormBackground { display: block;}</style>";
}
?>

You have your php code indented. Thus, the innerHTML has text even if there is nothing output from the PHP code. You should trim() your innerHTML before checking if it is empty
document.getElementById("register_error").innerHTML.trim()
Example

I guess the issue is in the below if condition:
document.getElementById("register_error").innerHTML
Your inner html returns a string, so you must be checking its length as:
if(document.getElementById("register_error").innerHTML.length) {}

Related

Replace text using Javascript on HTML page

I have a php web page with many informations on it, some of them are quite sensitive and I would like hide them and the possibilty to unhide them.
My web page is built like this to show the informations :
echo '<b>Login :</b> ' . $data['Login'] . '<br \>';
echo '<b>MDP :</b>' . decrypt($data['MDP'], $passkey) . '';
So I'm working on a small Javascript code to hide/show the MDP. It's not finished (cause it work only half), it look like this :
<span class="visible">My text to hide</span><br \>
<span class="visible">My other text to hide</span><br \>
<button id="Replace" onclick="replace()">Change content</button>
<script>
window.onload = function(){
document.getElementById("Replace").addEventListener( 'click', replace);
}
var Visible = document.getElementsByClassName('visible');
var HiddenText = document.getElementsByClassName('hiddentext');
var OriginalText = new Array();
for (var k = 0; k< Visible.length; k++){
OriginalText[k] = Visible[k].innerHTML;
}
function replace() {
if (Visible != null){
for (var i = 0; i< Visible.length; i++){
Visible[i].innerHTML = '*****';
Visible[i].className = 'hiddentext';
}
}else{
for (var j = 0; j< HiddenText.length; j++){
HiddenText[j].innerHTML = OriginalText[j];
HiddenText[j].className = 'visible';
}
}
}
</script>
I don't know why it look like it only work once. It replace the text with the stars and the Class change well but when I use it again, nothing happen.
I tried the code separetely (both part of the if) and all work good.
I'm far from an expert to code so I probably missing something, maybe someone can help me on it.
I finally did it in a different way, instead of replacing the text I just don't show it. I used PHP to hide the text, if you clic on the button the text is shown and after a delay a javascript code will redirect to the same page without the POST information that will automaticaly hide the text again.
function mdpviewer($data){
$ShowMdp = false;
if (isset($_POST['ShowMdp']) AND ($_POST['ShowMdp'] == true) AND ($ShowMdp != true)){
$ShowMdp = $_POST['ShowMdp'];
}else{
$ShowMdp = false;
}
if ($ShowMdp == true) {
return $data;
}else{
echo '';
}
}
echo '<form action="MyPage.php" method="post"><input type="submit" value="Show Passwd"><input type=hidden name="ShowMdp" value="true"></form></div>';
echo'<p>My Password : (mdpviewer($data['Psswd'])</p>';
if (isset($_POST['ShowMdp']) AND ($_POST['ShowMdp'] == true)){
echo '<script>setTimeout(function() { window.location.href = "MyPage.php";}, 30000);</script>';
}
It's probably not optimized and a bit messy but it's working great !
If someone found how to do it with replacing the text on javascript I will be glad to see it
maybe you could apply your logical differently. You could create php files whose purpose is returns data only in json format. This is simutale web service. So, when load page finished, by javascript you could request fetch to .php file endpoint, and manage response and make DOM modifications, another recommendation is you study es6 to do best practices! But is a tip, congratulations for resolve problem and my apologies if my english is bad, but im learning, cheers!

Get value from jQuery editor to PHP

I'm using this jquery plugin to create a wysiwyg text editor,
I created a textarea in PHP where:
<textarea name="body" id="body"><?php echo $body?></textarea>
and
<script type="text/javascript">
$(document).ready( function() {
$("#body").Editor();
});
</script>
Now i need to get value of this area for send it to SQL
if (isset($_POST['add-article'])) {
unset($_POST['add-article']);
$_POST['user_id'] = $_SESSION['id'];
$_POST['username'] = htmlentities($_SESSION['username']);
$_POST['published'] = isset($_POST['published']) ? 1 : 0;
// I need this line
$_POST['body'] = htmlentities($_POST['body']);
When I put text into this editor, it doesn't enter (value) into the textarea.
I have to have value before I press the add-article button, beacuse now it gives me an empty text.
I found something like this
function displayText(){
alert($("#body").Editor("getText"));
}
This causes it to return text ( i think only display by JS ) but i completely dont know how to use in my PHP scripts.
Second thing is when i write article and make a mistake something like ( Article title already exist ) ( in one session ) text in textarea stayed, but now doesn`t work it.
I think about if there is an error for example "Title already exist" follows:
} else {
$title = $_POST['title'];
$body = $_POST['body'];
$category_id = $_POST['category_id'];
$published = isset($_POST['published']) ? 1 : 0;
}
In my honest opinion i need something like:
add-article.addEventListener('click', function {
$body (from PHP) = alert($("#body").Editor("getText"))(from JS);
}
Thank you in advance for help.
On the plugin page you referenced, I see this is one of the recommendations. Capture the value you want when the click button is pressed, before the form submits.
Add a script to your form submit to put the texteditor content into this element
<form onsubmit='return getItReady()'>
Add an element to the form you'll use as a proxy element and keep it hidden, something like
<textarea id='txtEditorContent' name='txtEditorContent' style='visibility:hidden;height:0px' tabindex="-1"></textarea>
Then add the script to prepare it
<script>
function getItReady() {
console.log('The content:', $('#body').Editor("getText"));
$('#txtEditorContent').val($('#body').Editor("getText"));
return true;
}
</script>
Then in your PHP, it will come through as $_POST['txtEditorContent'].

HTML onfocus not calling Javascript function

So I'm making a kind of like a telltale game using readonly inputs. I'm using onfocus to call a javascript function, but it won't run the function. I'm new to stackoverflow so if you can't see my code, please tell me. Also, I'm coding on Chromebook so the links to the CSS file and JS file are drive links.
EDIT: I think this is a problem on my computer's end since it's working perfectly fine when I run it on here.
EDIT 2: MY GOD I'M AN IDIOT! I misspelled something in the javascript section, something that DIDN'T EVEN MATTER TO MY GAME was MISSPELLED.
var meep = 0;
function changeText() {
document.getElementById("startInput").blur();
if (meep === 0) {
document.getElementById("startInput").value = "'Why are you here?'";
} else if (meep === 1) {
document.getElementById("startInput").value = "'I'm not who I used to be...'";
} else if (meep === 2) {
document.getElementById("startInput").value = "'I'm looking for Malya,' you say.";
} else if (meep === 3) {
document.getElementById("startInput").value = "'I assume that is you.'";
} else if (meep === 4) {
document.getElementById("startInput").value = "...";
}
meep++;
}
<link rel="stylesheet" href="file:///media/fuse/drivefs-ba3df23145370ebbe0addbed7174e8b0/root/html/New%20Website/style.css">
<script src="file:///media/fuse/drivefs-ba3df23145370ebbe0addbed7174e8b0/root/html/New%20Website/code.js"></script>
<body>
<input type="text" class="no-outline" value="'Who are you?'" id="startInput" onfocus="changeText()" readonly>
<input type="text" class="tutorial" id="tutorial" placeholder="Click on text to change it." readonly>
Yeah, something that didn't matter to my game, I took out of the code for stackoverflow and OF COURSE it was misspelled. So the solution, when making a random variable you don't even need, do NOT spell document as doument.
This works just fine.
If it doesn't work on your machine, please check out the console do you have any errors, because the line
<script src="file:///media/fuse/drivefs-ba3df23145370ebbe0addbed7174e8b0/root/html/New%20Website/code.js"></script>
could create problems if the script doesn't work right.

If a parameter of event handler contains certain characters, JavaScript does not execute properly

php:
$str1 = "AAA\r\nBBBB\\CCC";
echo"<textarea id='aa1' onfocus='erase(\"".$str1."\", \"aa1\");'></textarea>";
$str2 = "AAABBBB\\CCC";
echo"<textarea id='aa2' onfocus='erase(\"".$str2."\", \"aa2\");'></textarea>";
$str3 = "AAABBBB\CCC";
echo"<textarea id='aa3' onfocus='erase(\"".$str3."\", \"aa3\");'></textarea>";
$str4 = "AAABBBBCCC";
echo"<textarea id='aa4' onfocus='erase(\"".$str4."\", \"aa4\");'></textarea>";
javascript:
function erase(str, id)
{
alert("good");
var field = document.getElementById(id);
if(field.value == str)
{
field.value = '';
}
}
If I click on textarea id='aa1', nothing happens.
If I click on textarea id='aa2' or textarea id='aa3', 'good' is printed but nothing happens to field.value.
If I click on textarea id='aa4', 'good' is printed and field.value is ''.
I want a string like AAA\r\nBBBB\\CCC to work like textarea id='aa4.
How can I do that?
I read the post below but it does not seem to help my situation:
Javascript parameter
Javascript Line Break Textarea
update:
I've replaced $str1 with json_encode($str1), So alert(); works fine now. (Thanks to Jordan Running.)
But the field.value part still does not work.
code refactoring is too hard in my situation... Is there any way to handle the field.value problem without code refactoring?
If quotes corrupt my HTML, I can putting $str1 in htmlspecialchars() and displaying it in <textarea>.
Generally speaking it's a bad idea to use string concatenation to build JavaScript. Your PHP code produces the following HTML:
<textarea id='aa1' onfocus='erase("AAA
BBBB\CCC", "aa1");'></textarea>
That's valid HTML, but the code in your onfocus attribute is not valid JavaScript. In JavaScript, you can't have a line break in the middle of a string literal. You can have a line break in a template literal (i.e. `one of these`), but that's not the right solution here.
A quick but short-sighted fix
When you need to "inject" some data into a block of JavaScript, you should always use json_encode:
$str1 = "AAA\r\nBBBB\\CCC";
echo "<textarea id='aa1' onfocus='erase(" . json_encode($str1) . ", \"aa1\");'></textarea>";
Make careful note of the quotation marks above. Because json_encode wraps strings in quotation marks, you don't need additional quotes around . json_encode($str1) ..
This will produce the following HTML:
<textarea id='aa1' onfocus='erase("AAA\r\nBBBB\\CCC", "aa1");'></textarea>
...whose onfocus handler works correctly, as you can see in this snippet:
function erase(...args) { console.log('erase called with', args); }
<textarea id='aa1' onfocus='erase("AAA\r\nBBBB\\CCC", "aa1");'></textarea>
A better way
The above is still fragile. What if your data has a ' in it? That'll break your HTML. The correct solution is to move your data out of the HTML entirely. Consider if you refactored your code to look something like this:
<textarea id="aa1"></textarea>
<textarea id="aa2"></textarea>
<textarea id="aa3"></textarea>
<textarea id="aa4"></textarea>
<?php
$erase_map = [
'aa1' => "AAA\r\nBBBB\\CCC",
'aa2' => "AAABBBB\\CCC",
'aa3' => "AAABBBB\CCC",
'aa4' => "AAABBBBCCC",
];
?>
<script>
const ERASE_MAP = <?php echo json_encode($erase_map); ?>;
function erase(event) {
if (event.target.value == ERASE_MAP[event.target.id]) {
event.target.value = '';
}
}
document.querySelectorAll('textarea').forEach(textarea => textarea.addEventListener('focus', erase));
</script>
In the above code, all of the data is in one place—a single associative array—instead of scattered around your HTML. It generates HTML code with a <script> tag into which the data is injected as a JSON object and assigned to a JavaScript variable:
<textarea id="aa1"></textarea>
<textarea id="aa2"></textarea>
<textarea id="aa3"></textarea>
<textarea id="aa4"></textarea>
<script>
const ERASE_MAP = {"aa1":"AAA\r\nBBBB\\CCC","aa2":"AAABBBB\\CCC","aa3":"AAABBBB\\CCC","aa4":"AAABBBBCCC"};
function erase(event) {
if (event.target.value == ERASE_MAP[event.target.id]) {
event.target.value = '';
}
}
document.querySelectorAll('textarea').forEach(textarea => textarea.addEventListener('focus', erase));
</script>

Include IF statement in Javascript

I have written the script below with some help. I am now trying to combine with an IF Statement. Here is what I am trying to accomplish, if %%GLOBAL_Availability%%is empty, then do not display the button. Else, display the button and run the script.
I did some research and came up with the below:
if (%%GLOBAL_Availability%% ==""){
<div><input id="ShopButton" style="display: none";></div>
}
else {
<!--Amazon Shopping button-->
<div><input id="ShopButton" </div>
<script>
document.querySelector("#ShopButton").addEventListener("click",function(){
window.location.href='%%GLOBAL_Availability%%';
},false);
</script>
}
It did not work at all. I am VB.net, and just learning this hard way.
Any suggestions?
Thanks.
I'm assuming that your variable %%GLOBAL_AVAILABILITY%% is a string since you're testing that it's empty via testing that it's equal to a blank string.
In javascript I'd offer 2 tips for testing if a string exists or is empty.
1 - use the .length property of the String object.
2 - to check that it exists check that the type of %%GLOBAL_AVAILABILITY%% is a string use the identity operator === to check that the variable is of type string.
Your if statement should look like the below:
if(typeof %%GLOBAL_AVAILABILITY%% === typeof string && %%GLOBAL_AVAILABILITY%%.length > 0){
//execute code
}
Secondly, javascript is made to manipulate the DOM, so there's no need to insert new HTML based on a condition, you can just manipulate the properties of the existing HTML - in this case, setting the display property of '#ShopButton' to none.This can be achieved like this:
document.getElementById('ShopButton').style.display = "none";
So, your code should look like this:
if(typeof %%GLOBAL_AVAILABILITY%% === typeof string && %%GLOBAL_AVAILABILITY%%.length > 0){
document.getElementById('ShopButton').style.display = "none";
} else{
document.getElementById('ShopButton').style.display = ""; //MAKE VISIBLE
document.getQuerySelector('#ShopButton').addEventListener('click', function(){
document.location.href = '%%GLOBAL_AVAILABILITY%%';
});
}
It seems you want the input to be "display: none;" if the variable is empty, in which case you can just change the style attribute based on the variable. Something like:
<div><input id="ShopButton" style="display: none";></div>
<script>
if (%%GLOBAL_Availability%% == "") {
document.getElementById("ShopButton").style.display = "block";
document.querySelector("#ShopButton").addEventListener("click",function(){
window.location.href='%%GLOBAL_Availability%%';
},false);
}
</script>
This will simply render the element as invisible and then the script will make it visible if the variable isn't empty.
<div>
<input id="ShopButton" style="display: none";>
</div>
<script>
if (%%GLOBAL_Availability%% == "") {
document.getElementById("ShopButton").style.display = "block";
document.querySelector("#ShopButton").addEventListener("click",function(){
window.location.href='%%GLOBAL_Availability%%';
},false);
}
</script>
Is this what you're trying to do maybe?

Categories

Resources