alert()/datalayer.push are different - javascript

I'm not very experienced so hopefully this is an easy question for one of you. I'm using google tag manager to track any time a span element is opened or closed on a word press site(or trying to at least). This is the relevant code and the problem.
<script type="text/javascript">
dataLayer.push({
eventAction: text
});
var text = jQuery('span').click(function(){
var t = jQuery(this).text();
alert(JSON.stringify(t));
});
</script>
This is triggered by any click that contains ac_title_class.
the html class im targeting follows
<span class="ac_title_class">
Purpose </span>
The problem is that this code send [object object] to google analytics instead of sending what the alert message says which is "/t/t/t/t/t/t/ Purpose /t/t/t/t/t"(that inst exactly what it says but close). I have tried countless different approaches and cant seem to figure it out. I greatly appreciate the help in advance.
Note: "ac_title_class" is part of a plugin.

You can push the data layer with your data by passing variable name and its value for eg. dataLayer.push({'variable_name': 'variable_value'});
For now you check my code below
<script type="text/javascript">
var text = jQuery('span.ac_title_class').click(function(){
var t = jQuery(this).text();
dataLayer.push({eventAction: t });
});
</script>

Related

How can I getting textarea value using javascript and ckeditor4 [duplicate]

I'm a learner as far as JS goes and although I've spent a good few hours reading through tutorials which has helped lots but I'm still having problems figuring out exactly how I find out what a user is typing into a ckeditor textarea.
What I'm trying to do is have it so that when someone types into the textarea, whatever they type appears in a div in a different part of the page.
I've got a simple text input doing that just fine but because the text area is a ckEditor the similar code doesn't work.
I know the answer is here: ckEditor API textarea value but I don't know enough to figure out what I'm meant to do. I don't suppose anyone fancies helping me out?
The code I've got working is:
$('#CampaignTitle').bind("propertychange input", function() {
$('#titleBar').text(this.value);
});
and
<label for="CampaignTitle">Title</label>
<input name="data[Campaign][title]" type="text" id="CampaignTitle" />
and
<div id="titleBar" style="max-width:960px; max-height:76px;"></div>
I'm still having problems figuring out exactly how I find out what a
user is typing into a ckeditor textarea.
Ok, this is fairly easy. Assuming your editor is named "editor1", this will give you an alert with your its contents:
alert(CKEDITOR.instances.editor1.getData());
The harder part is detecting when the user types. From what I can tell, there isn't actually support to do that (and I'm not too impressed with the documentation btw). See this article:
http://alfonsoml.blogspot.com/2011/03/onchange-event-for-ckeditor.html
Instead, I would suggest setting a timer that is going to continuously update your second div with the value of the textarea:
timer = setInterval(updateDiv,100);
function updateDiv(){
var editorText = CKEDITOR.instances.editor1.getData();
$('#trackingDiv').html(editorText);
}
This seems to work just fine. Here's the entire thing for clarity:
<textarea id="editor1" name="editor1">This is sample text</textarea>
<div id="trackingDiv" ></div>
<script type="text/javascript">
CKEDITOR.replace( 'editor1' );
timer = setInterval(updateDiv,100);
function updateDiv(){
var editorText = CKEDITOR.instances.editor1.getData();
$('#trackingDiv').html(editorText);
}
</script>
At least as of CKEDITOR 4.4.5, you can set up a listener for every change to the editor's contents, rather than running a timer:
CKEDITOR.on("instanceCreated", function(event) {
event.editor.on("change", function () {
$("#trackingDiv").html(event.editor.getData());
});
});
I realize this may be too late for the OP, and doesn't show as the correct answer or have any votes (yet), but I thought I'd update the post for future readers.
Simply execute
CKEDITOR.instances[elementId].getData();
with element id = id of element assigned the editor.
You could integrate a function on JQuery
jQuery.fn.CKEditorValFor = function( element_id ){
return CKEDITOR.instances[element_id].getData();
}
and passing as a parameter the ckeditor element id
var campaign_title_value = $().CKEditorValFor('CampaignTitle');
i found following code working for ckeditor 5
ClassicEditor
.create( document.querySelector( '#editor' ) )
.then( editor => {
editor.model.document.on( 'change:data', () => {
editorData = editor.getData();
} );
} )
.catch( error => {
console.error( error );
} );
Well. You asked about get value from textarea but in your example you are using a input. Anyways, here we go:
$("#CampaignTitle").bind("keyup", function()
{
$("#titleBar").text($(this).val());
});
If you really wanted a textarea change your input type text to this
<textarea id="CampaignTitle"></textarea>
Hope it helps.
you can add the following code :
the ckeditor field data will be stored in $('#ELEMENT_ID').val() via each click. I've used the method and it works very well. ckeditor field data will be saved realtime and will be ready for sending.
$().click(function(){
$('#ELEMENT_ID').val(CKEDITOR.instances['ELEMENT_ID'].getData());
});
var campaignTitle= CKEDITOR.instances['CampaignTitle'].getData();

Removing everything after first word JS

The title is a little bland but my problem is explained below.
At the moment I currently have a live search:
This does what I want it to do, but of course, that's only possible with a little bit of JS.
Now when you click one of the options it gives you from your search it'd usually take you to a link, but I added the below JS so that it removes all HTML code from it and it appends the selected username from the drop down into a text box.
<script type="text/javascript">
$(document).ready(function(){
$("#livesearch").click(function(){
var value = $(this).html();
var input = $('#append_value');
var content = value;
var text = $(content).text(); //removes all HTML
input.val(text);
});
});
</script>
Now, this is all perfect and everything but there's a problem. When you select one option from the drop down it appends both options to the text box:
Now, this may have something to do with the code above, but I just want whichever option the user has selected to be appended to the text box.
So, for example, I search for the battlefield and I get a result of battlefield1 and battlefield2. If the user selected battlefield2 I want battlefield2 to be placed in the textbox, and vice versa.
I've been trying to do this since 1pm EST so you can trust me when I say I've looked plenty of times for a solution.
Thank you in advance for your help. :)
Edit:
What I'm doing the search with (yes I realize SQL is deprecated):
index.html
<script type="text/javascript">
function lightbg_clr() {
$('#qu').val("");
$('#textbox-clr').text("");
$('#search-layer').css({"width":"auto","height":"auto"});
$('#livesearch').css({"display":"none"});
$("#qu").focus();
};
function fx(str) {
var s1=document.getElementById("qu").value;
var xmlhttps;
if (str.length==0) {
document.getElementById("livesearch").innerHTML="";
document.getElementById("livesearch").style.border="0px";
document.getElementById("livesearch").style.display="block";
$('#textbox-clr').text("");
return;
}
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttps=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttps=new ActiveXObject("Microsoft.XMLHTTPS");
}
xmlhttps.onreadystatechange=function() {
if (xmlhttps.readyState==4 && xmlhttps.status==200) {
document.getElementById("livesearch").innerHTML=xmlhttps.responseText;
document.getElementById("livesearch").style.display="block";
$('#textbox-clr').text("X");
}
}
xmlhttps.open("GET","scripts/search_friends.php?n="+s1,true);
xmlhttps.send();
}
</script>
<input type="text" onKeyUp="fx(this.value)" autocomplete="off" name="qu" id="qu" class="form-control" placeholder="Name of the person or group">
<div class="list-group" id="livesearch"></div>
<input type="text" id="append_valueq">
<script type="text/javascript">
$(document).ready(function(){
$("#livesearch").click(function(){
var value = $(this).val();
var input = $('#append_valueq');
var content = value;
var text = $(content).text();
input.val(text);
});
});
</script>
search_friends.php
<?php
include('../Connections/ls.php'); //script to connect to DB
$s1=$_REQUEST["n"];
$select_query="SELECT * FROM users WHERE Username LIKE '%".$s1."%'";
$sql=mysql_query($select_query) or die (mysql_error());
$s="";
while($row=mysql_fetch_array($sql))
{
$s=$s."
<a href='javascript:void(0)'>".$row['Username']."</a>
" ;
}
echo $s;
?>
This ultimately gives me the result you see in the first image.
I'm realizing now that the problem I'm having is the fact that div has an id of livesearch (<div class="list-group" id="livesearch"></div>), so it's selecting the whole div instead of the actual options in the dropdown...
Try using .val() instead of html() while fetching the value.
There is actually a really simple way to do this.
Since you haven't provided your HTML code, I'll show what I would have done.
You can get the value of the click with:
document.getElementById("dropdown").value();
Make sure you don't include the hashtag/pound sign in the id.
Then, you can apply this value, let's say you call it val, this way:
document.getElementById("textbox").value = val
I've created a JSFiddle that kind-of shows the concept. See if you can get it to work with your own code: https://jsfiddle.net/1j4m1ekc/7/
If the problem persists, just let me know. I'd also like to see your html.
I don't need a solution right away for this as I've found another alternative to do what I want to do, but it would be greatly appreciated in case someone else from the Stackoverflow community has a question similar to this and need a solution. The solution I found is below.
This is still considered a live search but, I created a scrollable container and listed all of the users in that container, so it now looks like this.
Now from that container I found a script online that will filter out any and all users that do not match the input from the search box. The script I found is from here: Live Search and if you want to take a look at a demo as to how the script works, View Demo. So now when I enter a search term into the text box it looks like this
This may not be the greatest solution but it works for me and does what I want it to do. Maybe it'll work for you as well :)

Why am I not getting a value from my getElementById()?

I want to take in a value from the URL, add it to a span tag on my slots.html so the user can read it, then pull that same value into another JS file to alter it as the game progresses. The Url code works fine and I get the appropriate value:
elId("wallet").textContent = (values["bank"]); which returns for example 1234.
<p>Player Bank: <span id="wallet"></span></p> which displays 1234 properly
but when I try to get the value from my html (var elWallet=elId("wallet");)to another JS page it returns <span id="wallet"></span> instead of 1234.
Could someone please explain to me what I am doing wrong, and how to improve my understanding of this. Any help would be appreciated!
EDIT: var elId = function(id) {return document.getElementById(id); } is the function I wrote to make writing document.get easier.
EDIT 2: Well I found the issue, talking through with a friend, thanks anyways for all the help.
Could please try using innerHTML to get the values.
elWallet.innerHTML will return the value inside your span tag.
Update:
This works for me. may be you might have put wallet element after the script tag.
Player Bank: 1234
<script>
var elId = function(id) {return document.getElementById(id); }
var elWallet=elId("wallet");
console.log(elWallet.textContent);
console.log(elWallet.innerHTML);
</script>
</body>
</html>

JavaScript - writing html elements that don't show up?

I'm trying to write some code in javascript that uses a user's cookies to display a box containing some information. The page opens with some boxes containing news articles from Google News RSS feeds. I'm using a 3rd party app for the RSS; the feed is included in the HTML code as such:
<script language="JavaScript" src="http://www.feedroll.com/rssviewer/feed2js.php?src=http%3A%2F%2Fnews.google.com%2Fnews%3Fq%3Dbarack%2Bobama%26output%3Drss&num=4&date=y&targ=y&utf=y&css=feed" charset="UTF-8" type="text/javascript"></script>
The user can move the boxes around, and I want to store the box locations using cookies so that if a user revisits the page, the boxes will be in the same location. However, when I try to load the page from the information in the cookies, the boxes are blank. This is an example of what my code looks like (RSS feed for news using keyword "Barack Obama"):
// Render boxes into HTML
function renderItem(container) {
var wrapper = document.getElementById(container);
var div_box = document.createElement('div');
var feed_url = 'http://www.feedroll.com/rssviewer/feed2js.php src=http%3A%2F%2Fnews.google.com%2Fnews%3Fq%3Dbarack%2Bobama%26output%3Drss&num=4&date=y&targ=y&utf=y&css=feed';
var div_box_feed = document.createElement('div');
var feed_script = document.createElement('script');
feed_script.setAttribute('language', 'JavaScript');
feed_script.setAttribute('src', feed_url);
feed_script.setAttribute('charset', 'UTF-8');
feed_script.setAttribute('type', 'text/javascript');
div_box_feed.appendChild(feed_script);
div_box.appendChild(div_box_feed);
wrapper.appendChild(div_box);
}
When the page loads, the box appears but the news articles from the RSS feed are not there and the box is empty. When I look at the source code, however, it is identical to the code of the initial boxes (which did display the news articles).
Does anybody know what's wrong?
Thanks!
You never declared column_div here:
wrapper.appendChild(column_div);
Did you mean:
wrapper.appendChild(div_box);
?
I believe that by default script elements created in this manner have their async attribute set to true, so the rest of your code will execute before your JS has been retrieved.
Where does the column_div variable come from?
You're missing a question mark to separate the post variables from the URL, so the URL is resolving to
var feed_url = 'http://www.feedroll.com/rssviewer/feed2js.php%20src=http%3A%2F%2Fnews.google.com%2Fnews%3Fq%3Dbarack%2Bobama%26output%3Drss&num=4&date=y&targ=y&utf=y&css=feed';
It should be
var feed_url = 'http://www.feedroll.com/rssviewer/feed2js.php?src=http%3A%2F%2Fnews.google.com%2Fnews%3Fq%3Dbarack%2Bobama%26output%3Drss&num=4&date=y&targ=y&utf=y&css=feed'

Getting the textarea value of a ckeditor textarea with javascript

I'm a learner as far as JS goes and although I've spent a good few hours reading through tutorials which has helped lots but I'm still having problems figuring out exactly how I find out what a user is typing into a ckeditor textarea.
What I'm trying to do is have it so that when someone types into the textarea, whatever they type appears in a div in a different part of the page.
I've got a simple text input doing that just fine but because the text area is a ckEditor the similar code doesn't work.
I know the answer is here: ckEditor API textarea value but I don't know enough to figure out what I'm meant to do. I don't suppose anyone fancies helping me out?
The code I've got working is:
$('#CampaignTitle').bind("propertychange input", function() {
$('#titleBar').text(this.value);
});
and
<label for="CampaignTitle">Title</label>
<input name="data[Campaign][title]" type="text" id="CampaignTitle" />
and
<div id="titleBar" style="max-width:960px; max-height:76px;"></div>
I'm still having problems figuring out exactly how I find out what a
user is typing into a ckeditor textarea.
Ok, this is fairly easy. Assuming your editor is named "editor1", this will give you an alert with your its contents:
alert(CKEDITOR.instances.editor1.getData());
The harder part is detecting when the user types. From what I can tell, there isn't actually support to do that (and I'm not too impressed with the documentation btw). See this article:
http://alfonsoml.blogspot.com/2011/03/onchange-event-for-ckeditor.html
Instead, I would suggest setting a timer that is going to continuously update your second div with the value of the textarea:
timer = setInterval(updateDiv,100);
function updateDiv(){
var editorText = CKEDITOR.instances.editor1.getData();
$('#trackingDiv').html(editorText);
}
This seems to work just fine. Here's the entire thing for clarity:
<textarea id="editor1" name="editor1">This is sample text</textarea>
<div id="trackingDiv" ></div>
<script type="text/javascript">
CKEDITOR.replace( 'editor1' );
timer = setInterval(updateDiv,100);
function updateDiv(){
var editorText = CKEDITOR.instances.editor1.getData();
$('#trackingDiv').html(editorText);
}
</script>
At least as of CKEDITOR 4.4.5, you can set up a listener for every change to the editor's contents, rather than running a timer:
CKEDITOR.on("instanceCreated", function(event) {
event.editor.on("change", function () {
$("#trackingDiv").html(event.editor.getData());
});
});
I realize this may be too late for the OP, and doesn't show as the correct answer or have any votes (yet), but I thought I'd update the post for future readers.
Simply execute
CKEDITOR.instances[elementId].getData();
with element id = id of element assigned the editor.
You could integrate a function on JQuery
jQuery.fn.CKEditorValFor = function( element_id ){
return CKEDITOR.instances[element_id].getData();
}
and passing as a parameter the ckeditor element id
var campaign_title_value = $().CKEditorValFor('CampaignTitle');
i found following code working for ckeditor 5
ClassicEditor
.create( document.querySelector( '#editor' ) )
.then( editor => {
editor.model.document.on( 'change:data', () => {
editorData = editor.getData();
} );
} )
.catch( error => {
console.error( error );
} );
Well. You asked about get value from textarea but in your example you are using a input. Anyways, here we go:
$("#CampaignTitle").bind("keyup", function()
{
$("#titleBar").text($(this).val());
});
If you really wanted a textarea change your input type text to this
<textarea id="CampaignTitle"></textarea>
Hope it helps.
you can add the following code :
the ckeditor field data will be stored in $('#ELEMENT_ID').val() via each click. I've used the method and it works very well. ckeditor field data will be saved realtime and will be ready for sending.
$().click(function(){
$('#ELEMENT_ID').val(CKEDITOR.instances['ELEMENT_ID'].getData());
});
var campaignTitle= CKEDITOR.instances['CampaignTitle'].getData();

Categories

Resources