Include IF statement in Javascript - 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?

Related

Problem showing table with Javascript condition

I have a Sprinv MVC Controller, when I submit a form I return the same page but with some objects and a String called hidden that has the value False. When I submit the form I have a window.onload function that gets the value of the this string and checks if it has the string value "false" to display 3 divs that were hidden but they didn't.
I'm struggling where is the problem because I tried a lot of things.
This is my HTML Form.
<form class="forms-sample" action="Buscar.do" method="POST" >
<div class="form-group">
<label>client:</label>
<input type="text" class="form-control" id="id" name="identificador" placeholder="DNI/NIF">
</div>
<button type="submit" class="btn btn-gradient-primary btn-gradient-aj mr-2">Obtenir Autoritzacions</button>
</form>
And here's the javascript code.
<script>
window.onload = function showTable() {
var z = ${hidden}
if(z.localeCompare("false") == 0){
var x = document.getElementById("Prueba");
var x2 = document.getElementById("Prueba2");
var x3 = document.getElementById("Prueba3");
x.style.display = "block";
x2.style.display = "block";
x3.style.display = "block";
}
}
</script>
I checked with innerHTML and the value Im getting is false so they localeCompare should do the If condition, I think the problem is in the if because i tried withouth the if and it works. Also I didnt post the divs Prueba/Prueba2/Prueba3 becasue they're not important, i mean they could be only a text.
SOLVED
I created a input type hidden with that the MVC controller returns and get it by javascript with z = document.getElementById('form1').elements[1].value . Thanks to #kemicofa for the tip.
I'm not familiar with Spring, but from the syntax in your js code, I'm assuming it replaces things with ${} with their Spring variables. I know with PHP or Handlebars, you need to provide the quotes yourself, so try replacing ${hidden} with "${hidden}".
The spring expression needs to be within single quotes;
var z = '${hidden}';

how do i make js dectect whats typed in a input box

I'm trying to make js detect whats in a input box, and if the user typed in a code, something will happen so far I got this
function input() {
document.getElementById('hehe').value
if (value == "hello") {
window.alert("SOMETHING");
} else {
window.alert("SOMETHING");
}
}
<input id="hehe" type="text" oninput="input()">
but it's not working for some reason and I can't see why
you have to save the value before you can use it. document.getElementById('hehe').value RETURNS the value of the input textfield but in the next line you're using the non existing variable value.
just change it to:
function input() {
var value = document.getElementById('hehe').value
if (value == "hello") {
window.alert("SOMETHING");
} else {
window.alert("SOMETHING");
}
}
or use it directly:
function input() {
if (document.getElementById('hehe').value == "hello") {
window.alert("SOMETHING");
} else {
window.alert("SOMETHING");
}
}
You are not assigning the DOM element value to a variable. You should write:
var value = document.getElementById('hehe').value;
Or, using jQuery:
var value = $('#hehe').val();
However, another automated way to detect entered text, using KnockoutJS library, is data-bind. It automatically synchronizes the DOM element with your Model after applying the binding to your ModelView.
Here is an example: (jsfiddle)
HTML:
<p>Name: <input data-bind="textInput: name"></p>
<h1>The typed name is: <span data-bind="text: name"></span>.</h1>
JavaScript:
ko.applyBindings({
name: ko.observable("SOMETHING")
});
Use onkeypress instead of oninput.
http://jsfiddle.net/VDd6C/8/

Hide a row if value returned is empty

I feel a little stupid asking this question but for some reason I cant for the life of me think on how to do what I want.
I have a <div class="row"> which has my field label and field in it.
I want to completely hide this row if the value of my field is returned as empty.
HTML (Held in my CMS system):
<div id="rollNumber" class="row">
<label class="col-sm-offset-2 col-sm-3 control-label">[!RollNumberLabel]</label>
<div class="col-sm-2 form-control-static">[!RollNumber]</div>
</div>
View code:
if (newBankdetails.RollNumber != null && newBankdetails.RollNumber != "")
{
template.Nvc.Add("[!RollNumberLabel]", "Roll number");
template.Nvc.Add("[!RollNumber]", newBankdetails.RollNumber);
}
I tried doing:
template.Nvc.Add("[!RollNumberLabel]", "");
template.Nvc.Add("[!RollNumber]", "");
but this adds white space between the row above and below this row.
I'm up for any suggestions whether it be JavaScript, JQuery, CSS or if can be done, using HTML (although I don't think it can be done this way).
I can't add any code to my CMS so it needs to be done in my code.
My site is using Twitter Bootstrap
You can test if label text is empty or not.
$(function() {
$(".row").each(function() {
if ($("label", this).text() == "" ) {
$(this).hide();
}
});
});
Working demo: http://jsfiddle.net/m7nytbw4/
I have created an example for you http://jsfiddle.net/gon250/x8m6jLLo/
$(".row").each(function(){
var $row = $(this);
var $childern = $row.children();
if($childern.length > 1) {
if($childern[0].innerText === "" && $childern[1].innerText === "") {
$row.hide();
}
}
});
basically what I'm doing is check all the children of the rows and if both are empty hide the row.
Hope it's helps!
Use CSS display style property to hide the row.
$("#rollNumber").css("display", "none");
I am not sure if this is a overkill solution for your problem, but with jQuery and regex you could do something like this:
$('.row').each(function(){
var row = $(this);
if(! /^[a-zA-Z0-9]+$/.test(row.find('label'))){
// No alphabetical characters found
row.css('display','none');
}
});

check whether any html tags entered in textarea using javascript

I'm having a simple commenting system, where i want the user should not type any html special chars, if they done like that they should give an alert of "html tags not allowed". How to do it?
while submitting, a ajax call is passed to another page to store it in db.
So in the javascript itself(before ajax call), how to find is there any html tags in the entered comment.
Any suggestion.
To check you can create an element in the DOM, inject the comment into it and use [element].getElementsByTagName('*') to check for any html element. If its length is not 0, there are html elements in the comment. Something like:
document.querySelector('#check').addEventListener('click', doCheck);
function doCheck(e) {
var chkEl = document.createElement('div'),
isok,
report,
value = document.querySelector('#testing').value;
if (!value.length) {return true;}
chkEl.innerHTML = value;
report = document.querySelector('[data-report]');
isok = !chkEl.getElementsByTagName('*').length;
report.setAttribute( 'data-report',
!isok
? 'you can\'t enter html here!'
: 'text looks ok' );
report.style.color = isok ? 'green' : 'red';
}
[data-report]:before {
content: attr(data-report);
}
<textarea id="testing" placeholder="type some stuff"></textarea>
<span data-report=""></span>
<br>
<button id="check">check for html</button>
Disclaimer: you should always check server side too.
You can use the following statement with regex:
if (/<[a-z][\s\S]*>/i.test(textareaContent)) {
alert("html tags not allowed");
}
Kooilnc is right. You should always check user input on server side as well.
Please see this question Check if a string is html or not
removing html tags in comment
function sanitizeString(str) {
str = str.replace(/[^a-z0-9áéíóúñü \.,_-]/gim, " ");
return str.trim();
}

Changing css over if condition

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) {}

Categories

Resources