comparing HTML text content with jQuery - javascript

I have a page where a specific div shows the ID for the user's "system role" like so:
<div id="systemRoleIndicator" style="display: none;">
<p>Z</p>
</div>
I can detect the value fine with jQuery, but I can't seem to actually use it for anything. For instance, I never receive the completion message in this code:
<script src="/scripts/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
var role = $("#systemRoleIndicator").text();
alert("Your role is: " + role); //displays proper value
if (role == "Z") {
alert("Code completed!");
}
</script>
Why might this be? Am I missing something about comparing strings?

Text for #systemRoleIndicator will also return leading and trailing space near p node. which returns text " Z " and not "Z".You need to either compare with the text of p element.:
var role = $("#systemRoleIndicator p").text();
or trim the text content of #systemRoleIndicator:
var role = $("#systemRoleIndicator").text().trim();

Related

javascript arrays and looping

I'm jessi and I'm a web development student. I'm trying to write a program with arrays and I'm stuck. I have an array of phrases and when a user enters a number between 1 and 10 it is supposed to show that many phrases on the screen but I'm stuck. I don't know how to display multiple results on the screen. I'd really appreciate any help. Thanks.
<!DOCTYPE html>
<html>
<head>
<title>Get A Response</title>
</head>
<body>
<form>
<h1>Select how many phrases you want displayed.</h1>
<input type="number" class="userInput"></input>
<button type="submit" value="submit" onclick="showme()"></button>
</form>
<div class="myphrases">
</div>
<script src="js/main.js"></script>
</body>
</html>
////////////////// Javascript
function showme() {
var number = document.querySelector('.userInput').value;
var display = "";
var phrases = [
"Hello there",
"What's up Doc",
"Because I said so",
"Say it again",
"It's a celebration",
"Enjoy yourselves",
"Welcome",
"Where did you go", "Why you crying", "Stop playing"];
var random = Math.floor(Math.random() * phrases.length);
for(var i = 0; i < phrases.length; i++) {
}
}
First, you should set up an HTML element that will serve as your output area. An empty div element is a good choice. You've already done that with: <div class="myphrases"></div>.
Next, the HTML input element does not get a closing tag (</input>) and instead of using a submit button, just use a regular button (since you are not actually submitting data anywhere).
Also, don't use inline HTML event handling attributes (onclick, onmouseover, etc.) as they:
Create spaghetti code that leads to duplication and makes the code harder to read.
Causes global anonymous wrapper functions to be created around your attribute's value and change the this binding in your callback functions.
Don't follow the W3C Event standard of using .addEventListener().
Next, don't have your loop go over every phrase (phrases.length). Only have it go for the amount of times the user has entered.
Finally, you can update the div output area by adjusting its innerHTML to be a string that you build up from your loop:
// Get reference to the text box, the button and the output area
var number = document.querySelector('.userInput');
var btn = document.querySelector("button");
var output = document.querySelector(".myphrases");
// Set up the event handling function for the button
btn.addEventListener("click", showme);
function showme() {
var display = "";
var phrases = [
"Hello there",
"What's up Doc",
"Because I said so",
"Say it again",
"It's a celebration",
"Enjoy yourselves",
"Welcome",
"Where did you go", "Why you crying", "Stop playing"];
// String to hold loop results
var result = "";
// Set up the upper limit for the loop.
// If the entered value is greater than the length of the array, use the length
// of the array. If not, use the value entered by the user
var count = number.value > phrases.length ? phrases.length : number.value;
for(var i = 0; i < count; i++) {
var random = Math.floor(Math.random() * phrases.length);
result += phrases[random] + "<br>";
}
// Inject the string into the output area
output.innerHTML = result;
}
<form>
<h1>Select how many phrases you want displayed.</h1>
<input type="number" class="userInput">
<button type="button">Submit</button>
</form>
<div class="myphrases"></div>

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();
}

Replace a part of text in textbox while typing text in it

The format of text in the text box is like this:
login -u username -p password
While typing this text I want to replace 'password' with number of '*' equal to its length. So if I type:
'login -u abc#abc.com -p abc' in text box it should display like this:
login -u abc#abc.com -p ***
And also I need to store the actual password which is being replaced.
Is there a possible way? Thank you in advance
You should parse the input value using regular expression, i.e.
<input type="text" id="inputText" />
<input type="hidden" id="actualPassword" /> <!-- Another element to store actual password -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
// Function to repeat string n times */
var StringUtilities = {
repeat: function(str, times) {
return (new Array(times + 1)).join(str);
}
};
$(function(){
$('#inputText').keyup(function(){
var test = /(login[\s]+\-u[\s]+[a-zA-Z0-9#\.\s]+\-p[\s]+)(.*)/i.exec( $(this).val() ); //'login -u user123 -p password123'
if(test !== null)
{
if( $('#actualPassword').val().length < $.trim(test[2]).length )
$('#actualPassword').val( $('#actualPassword').val() + test[2].slice(-1) );
else
$('#actualPassword').val($('#actualPassword').val().slice(0, test[2].length));
$(this).val( test[1] + StringUtilities.repeat( '*', test[2].length) );
}
});
});
</script>
JS FIDDLE: http://jsfiddle.net/nmx04h1o/3/
You can use multiple text boxes and still make it look like one, command prompt. Using CSS you remove left, right borders and join them close enough. On keypress event of each textbox, check if the user typed space and change the focus to next textbox. This solution works provided you have some fixed format of input to be taken.
The way you need to look at your requirement needs to be change. Why you need to get data from user with nly one input?
You need to collect username and password differently and then you can merge the same on form submit.
$("#submit").click(function(){
$output = "login -u " + $("#username").val() + " -p " + $("#password").val();
alert($output);
return false;
});
http://jsfiddle.net/kiranvarthi/j8gL9mvx/1/
Do not do it. You can see what i've tried at the bottom of my answer.
I played around with this problem a littlebit, but when i did a facing myself another problems.
There are 2 method to do this. 1st is, when a user enter a character, you need to use the keyup function.
So, you can write a regular expression, what is catching the -p andsomecharactersherewhileitsnotspace.
Ok, the first method is to catch the last character of users password, and contcat it to a hidden field. Me and Apul Gupta tried this.
For some reason, both of our code is mess up the password, because for some reason, what i do not know, there will be * characters if you are typing to fast. I tried to replace those * characters, but in this case, some characters are lost from the password.
The other way is to get the character from keyup event. This is bad, because String.fromCharCode is returning always uppercase characters, since, keyup do not know, is there a SHIFT or CAPS LOCK happens. Maybe now you think, you can handle it, but you can not. SHIFT is simple, but you don't know, was the CAPS LOCK was turned on befor or not.
A solution could be for this, if you allow users only lowercase or only uppercase passwords, but this is bad because weekening the password.
So, think a littlebit more. Let's say, somehow we can use one of the solution. Then this whole things turn to a very complex thing, what are too expensive i think. Because, you should handle, what happens, if a user just SHIFT, LEFT ARROW, DELETE the password. You need to check, what selected with that combination of keyperss, where was the cursor, etc...
I suggest you to forget this, or try to find another way to do it.
Kiran Varthis answer is the best option i think.
What i've tried:
<input type="text" name="userInput" id="userInput" value="" />
<input type="hidden" value="" name="hiddenPassword" id="hiddenPassword" />
<script type="text/javascript">
$(function() {
String.prototype.repeat = function(num) {
return new Array(num + 1).join(this);
}
//46 = delete key
$("#userInput").keyup(function(e) {
var match = $("#userInput").val().match(/-p([\s]+)(.+)/i);
if (e.keyCode === 8) {
var deleted = $('#hiddenPassword').val().substring(0, $('#hiddenPassword').val().length - 1);
$('#hiddenPassword').val(deleted);
} else {
if (match !== null && match[2] && String.fromCharCode(e.keyCode).match(/[a-zA-Z0-9]/)) {
//Alphanumeric
$('#hiddenPassword').val($('#hiddenPassword').val() + $("#userInput").val().substring($("#userInput").val().length - 1));
$("#userInput").val(($("#userInput").val().replace(/-p (.+)/, "-p " + "*".repeat(match[2].length))));
}
}
if (match !== null && match[2]) {
console.log("Password is: " + $('#hiddenPassword').val());
}
});
});
</script>

displaying user content as typed in

When a user types in some value in a text box it should be displayed in a td as it is.
This is the code I've tried with a div,
<input type="text" name="userStr" id="userStr" onKeyUp="processValue()"/>
<div id="disp">
</div>
<script type="text/javascript" >
function processValue() {
var userval = document.getElementById("userStr").value;
//alert('userval'+userval);
document.getElementById("disp").innerHTML = userval;
}
I enter the value, &lt&gt &#40 &#41 &#35 &#38 , but it is showing as <> ( ) # &
instead of the original string (&lt&gt &#40 &#41 &#35 &#38 )
What is the standard way to do this.
While I typed stackoverflow showed exactly the same, I'll now view the source, but looking for insights from you.
Thanks.
Try:
document.getElementById("disp").innerHTML = userval.replace(/&/g, '&').replace(/</g, '<');
Alternatively, you could set the element text, but you'd have to deal with browser variation.

Javascript: help with replacing '<div>' with '<br>' of an innerHTML!

I have an editable div where the user writes. As he writes, a javascript function adds the div html to a textarea. When the user presses SHIFT+Enter, the div gets a <br>. This is good.
But when the user presses Enter alone, the div gets <div></div> tags.
Therefore I try to make it so that when Enter is pressed, javascript scans the div's html to eliminate the </div> and change the <div> for <br>. The result will be that regardless of whether the user presses SHIF+Enter or Enter, the div's html will end up using only <br> for linebreaks.
<head>
<script type="text/javascript">
function doStuff(e){
if (window.event.keyCode == 13) {
var s=document.getElementById("divv").innerHTML;
s.replace("<div>", "<br>");
s.replace("</div>", "");
document.getElementById("divv").innerHTML=s;
}
document.getElementById("txtt").value = document.getElementById("divv").innerHTML;
}
</script>
</head>
<body>
<div contenteditable="true" id="divv" onKeyUp=doStuff(event);">
write here! Then press enter!
</div>
<textarea id="txtt" rows="30" cols="100">
</textarea>
</body>
My code doesn't work. When Enter is pressed, The textArea still shows div tags.
I'm not sure what I'm doing wrong. Please help.
The replace() method does not modify the string it's called on, it returns a new string with the occurrences replaced.
You can do something like:
var divv = document.getElementById("divv");
divv.innerHTML = divv.innerHTML.replace("<div>", "<br>").replace("</div>", "");
Usually browsers will have innerHTML store tags as <DIV> and </DIV> - you could try using:
s = s.replace(/<div>/ig,"<br>");
s = s.replace(/<\/div>/ig,"");
Firstly, if you use xhtml, you must use tag "< br / >".
Also draw attention on str.replace: it replaces only once.
js> var x = "hello";
js> x.replace("l", "L");
heLlo
Make your replace implementation:
js> function myreplace(str, pattern, change_to) {
var s = str;
var s2 = s;
do {
s2 = s;
s = s.replace(pattern, change_to);
} while (s2 != s);
return s;
}
js> myreplace("helllllo", "l", "L");
heLLLLLo

Categories

Resources