I added some text to div like this:
document.getElementById("" + choice).innerHTML += "e";
But later in my script I want to check if that div contains my text. I have tried the below code:
if (document.getElementById("" + choice).innerHTML === "e") {
alert('yep!');
}
But it doesn't work, I don't get the "yep!' alert. How do I fix it?
You are appending the text using += operator and not completely setting it to e.
Thus, if the innerHTML was foo it would be fooe.
What you might want to do is:
if ((document.getElementById("" + choice).innerHTML).indexOf("e") !== -1) {
alert('yep!');
}
You should use :
if (document.getElementById("hello").innerHTML.includes("e")) {
alert('yep!');
}
<div id="hello">hello world</div>
Because in this code:
document.getElementById("" + choice).innerHTML += "e";
you are adding "e" to innerHTML
use document.getElementById("" + choice).innerHTML.contains("e")
You can do it this way:
var myContent = "e"
document.getElementById("" + choice).innerHTML += myContent;
if (document.getElementById("" + choice).innerHTML.includes(myContent)) {
alert('yep!');
}
If you did intend to use the += operator instead of =. You might have whitespace in your div. You can use the trim function to get rid of that like in this snippet.
If you change the operator to = you can still use the check without trim.
document.getElementById("test").innerHTML += "e";
console.log('innerHTML value: "' + document.getElementById("test").innerHTML + '"');
if (document.getElementById("test").innerHTML === "e") {
console.log('passed');
}
if (document.getElementById("test").innerHTML.trim() === "e") {
console.log('passed with trim');
}
<div id="test"> </div>
+= means concat new value to current value. i guess if you want to replace the div's innerHTML to "e", youshould replace "+=" in
document.getElementById("" + choice).innerHTML += "e";
to "=".
else if you'd like to append string to div's innerHTML, you should replace '===' in
if (document.getElementById("" + choice).innerHTML === "e") {
alert('yep!');
}
to includes function.
Related
I am using this code which essentially types text onto the screen. I am unsure how to add a new line to the string which is being displayed.
I have already tried \n for those posting their answers. This does NOT work. A new line is not started in my HTML
Code:
var myString = "public class MyResume implements Resume{" +
/*this is where I want the new line*/ "...." ;
var myArray = myString.split("");
var loopTimer;
function frameLooper() {
if(myArray.length > 0) {
document.getElementById("myTypingText").innerHTML += myArray.shift();
} else {
clearTimeout(loopTimer);
return false;
}
loopTimer = setTimeout('frameLooper()',70);
}
frameLooper();
<div id="myTypingText"></div>
You can also use <br>.Just like"your string.<br> new line"
Here's an overly simplistic approach with full code. Use a tilde ~ and then watch for it in your frameLooper to insert a like this:
<html>
<body>
<div id="myTypingText"></div>
<script>
var myString = 'public class MyResume implements Resume{~....' ;
var myArray = myString.split("");
var loopTimer;
function frameLooper() {
if(myArray.length > 0) {
var char = myArray.shift();
if (char === '~')
{ document.getElementById("myTypingText").innerHTML += '<br/>'; }
else
{ document.getElementById("myTypingText").innerHTML += char; }
} else {
clearTimeout(loopTimer);
return false;
}
loopTimer = setTimeout('frameLooper()',70);
}
frameLooper();
</script>
</body>
</html>
Simply adding <br> to myString doesn't work because you're inserting each character at one time. When a character gets added with innerHTML, JavaScript encodes it:
$('element').innerHTML += "<";
> "string<"
If you did this for each character in <br>, you'd end up with
>"string<br<"
You need some way to tell your script to add the entire element when you reach a "break character". You could use an uncommon character like a pipe | or you could add a method which looks ahead to make sure that the next few characters don't spell out <br>.
To add string to a new line, you need the \n in your string. For example:
var string = 'This is the first line \nThis is the second line'
console.log(string)
This would output
This is the first line
This is the second line
Why don't you just append ul>li or p to your text, something like this:
document.getElementById("myTypingText").innerHTML += "<p>" + myArray.shift() "</p>";
or
document.getElementById("myTypingText").innerHTML += "<li>" + myArray.shift() "</li>";
with:
<ul id="myTypingText"></ul>
I am trying to replace the selected text in the p tag.I have handled the new line case but for some reason the selected text is still not replaced.This is the html code.
<p id="1-pagedata">
(d) 3 sdsdsd random: Subject to the classes of this random retxxt wee than dfdf month day hello the tyuo dsds in twenty, the itol ghot qwerty ttqqo
</p>
This is the javascript code.
function SelectText() {
var val = window.getSelection().toString();
alert(val);
$('#' + "1-pagedata").html($('#' + "1-pagedata").text().replace(/\r?\n|\r/g,""));
$('#' + "1-pagedata").html($('#' + "1-pagedata").text().replace(/[^\x20-\x7E]/gmi, ""));
$('#' + "1-pagedata").html($('#' + "1-pagedata").text().replace(val,"textbefore" + val + "textAfter"));
}
$(function() {
$('#hello').click(function() {
SelectText();
});
});
I have also created a jsfiddle of the code.
https://jsfiddle.net/zeeshidar/w50rwasm/
Any ideas?
You can simply do $("#1-pagedata").html('New text here');
Since your p doesn't content HTML but just plain text, your can use both html() or text() as getter and setter.
Also, thanks to jQuery Chaining you can do all your replacements in one statement. So, assuming your RegExp's and replacement values are correct, try:
var $p = $('#1-pagedata');
$p.text($p.text().replace(/\r?\n|\r/g,"").replace(/[^\x20-\x7E]/gmi, "").replace(val,"textbefore" + val + "textAfter"));
Im trying to create a simple function that create span's with an class that equals whatever is piped into the function. These spans fill inside a parent div. I also want to ensure that once a span has been added that another span is not add with that id/class, unless my multiSearchEnabled boolean is true.
Here is some code i've
function createBadge(badge_type) {
var badge_parent_div = $("#badge-column-div");
var badge = "<span class='badge-text " + badge_type + "'>" + badge_type + "</span>";
if (!$(badge_parent_div.find("span").hasClass(badge_type))) {
badge_parent_div.append(badge);
} else {
if (multiSearchEnabled) {
badge_parent_div.append(badge); // Add another Badge, since search contains multiples
}
}
}
However this doesnt seem to work, this function will be ran onKeyUp therefore is why i need to detect if the span already exists for this type, so i dont duplicate it.
Updated based on suggestions
function createBadge(badge_type) {
var badge = "<span class='" + badge_type + "'>" + badge_type + "</span>";
var bHasBadge = $("#badge-column-div").has('.' + badge_type);
if (bHasBadge == false || (bHasBadge && multiSearchEnabled == true))
{
// add it
$("#badge-column-div").append(badge);
}
}
However with the following code, nothing ever get's added. I need it add a badge initially, then only if the multiSearchEnabled boolean is true to add more than one.
has() checks for child controls matching a selector.
function createBadge(sBadgeType)
{
var oBadgeParent = $("#badge-column-div");
var bHasBadge = oBadgeParent.has("span." + sBadgeType)
if (bHasBadge == false || bMultiSearchEnabled)
oBadgeParent.append
(
$("<span class='badge-text " +sBadgeType+ "'>" +sBadgeType+ "</span>")
);
}
I have such a script (changed and easyfied for better understanding):
$(document).ready(function() {
var summary;
function validateSteps(stepnumber){
if(stepnumber == 1){
...
var resultStep1 = '<b>Shape1: </b>' + $('#chooseshape1').val();
summary = resultStep1;}
if(stepnumber == 2){
...
var resultStep2 = '<b>Shape2: </b>' + $('#chooseshape2').val();
summary += resultStep2;}
if(stepnumber == 3){
...
var resultStep3 = '<b>Shape3: </b>' + $('#chooseshape3').val();
summary += resultStep3;}
}
$('#resultSteps').val(summary);
}
I get no output for #resultSteps
Only when I write $('#resultSteps').text(summary); I get output in that div but it looks like:
<b>Shape1: </b>round, <b>Shape2: </b>square<b>Shape3: </b>rectangle
But I want output like this:
Shape1: round Shape2: sqaure Shape3: rectangle
How to achieve this?
$("#resultSteps").html(summary);
Use .html which outputs the elements as they should be, so <b>text</b> would become text.
$("#resultSteps").html(summary);
.val wouldn't work as I presume #resultSteps is not an input-field.
.text would probably remove the tags (<b>).
Docs
I have a jQuery function that is executed by two different buttons.
$("#btnSearch, #btnDirectorSearch").click(function () {
Part of the html that this function builds depends on which button was hit. I am using data- attributes to store my variables like this:
var div = $(this).data("str");
And the html string I am building depends on what value the variable "div" is. Is there a way to do an inline if/else statement in jQuery?
if div = "choice1" {
html += '<tr data-str = "str1" data-dataItem = "dataItem1" data-result-title = "' + name + '" data-result-id="' + sel + '">';
} else {
html += '<tr data-str = "str2" data-dataItem = "dataItem2" data-result-title = "' + name + '" data-result-id="' + sel + '">';
}
That seems cumbersome and I'm hoping there is a better jQuery way of doing this.
Thanks!
you have a syntax error
if div = "choice1"
should be
if (div == "choice1")
Anyway, the pattern you're looking for is:
div == "choice1" ? <code for true> : <code for false>
you can use condition ? code when true: code when false
but i would suggest you to stick with curley braces only, as it looks better and easier to debug.
one more thing , do it as below
if(div==="choice1"){
}
else{
}
use ===
Since it's only the number that changes in the output, you could do this:
var num = div == "choice1" ? 1 : 2;
html += '<tr data-str="str'+num+'" data-dataItem="dataItem'+num+'" data-result-title="'+name+'" data-result-id="' + sel + '">';
If your choices are limited, you could add a small lookup array:
var choices = {
choice1: {
str: "str1",
data: "dataItem1"
},
choice2: { ... }
};
html += '<tr data-str="' + choices[div].str
+ '" data-dataItem="' + choices[div].data
+ '" data-result-title="' + name + ... etc;