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

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>

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

alert()/datalayer.push are different

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>

javascript set variable from .text method

I'm new in javascript development and I want to ask how to set variable from text method.
Example: in this code have a text method
$('.phone').text(theRestaurant.phone);
$('.location').text(theRestaurant.location);
$('.info').text(theRestaurant.info);
in the Html file, when I create any class from these will print the value from JSON file.
Example :
<div class='phone'></div>
Output: (000)000-9999
source code:
<div class='phone'>(000)000-9999</div>
I try to set this in variable but it doesn't work.
My try:
var phone = theRestaurant.phone
I want to set it in variable because I need to put it inside href value like so:
<script>
var phone = 'tel:' + phone
document.getElementById("phone").href = phone;
</script>
I hope everything clear. and If have an other solution please tell about it.
Thanks
Have you wrapped your jQuery code in a document.ready() wrapper?
If not, then the javascript might run before the page has had time to create the elements in the DOM, and nothing will work.
<script>
$(document).ready(function(){
//all javascript/jQuery code goes in here
});
</script>
Also, see my comment above about mixing up "ByClassName" and "ByID"
Answer came from #itsgoingdown
this code in main javascript file:
var phone=document.getElementById('phone').innerHTML; document.getElementsByClassName("phone")[0].href = phone;

JS - Dynamic Href Change

Ive tried many way but im new to JS, I mainly do PHP.
Anyway the code:
<script>
var userinput = $('input[name="imdbid"]');
userinput.change(
function(){
$('#userimdb').attr('href')+$('input[name="imdbid"]').val();
}
);
</script>
Basically, the imdbid is gotten from a input tag, basically I want to append whatever the user types to a href of a tag, This doesnt seem to work doe. When I alert() it, it seems to give me the output of what its meant to but when I remove alert() it doesnt seem to change the href, I also tried .setAttribute() but that also just did nothing.
Please help me out im going insane right now.
Try this:
You need to assign it to href attribute..
var userimdb=$('#userimdb');
var baseURL=userimdb.attr('href');
$('input[name="imdbid"]').change(function()
{
var userimdb=$('#userimdb');
userimdb.attr('href', baseURL + $(this).val());
});
You're not setting the attribute right now, only accessing it. In addition, you need to store the original href attribute somewhere so you're not adding the same text repeatedly. Here's the updated code:
var userinput = $('input[name="imdbid"]');
var orighref = $('#userimdb').attr('href');
userinput.change(function(){
$('#userimdb').attr('href', orighref + userinput.val());
});

How to save an image's attribute id to a variable?

UPDATE - Sorry I tried to keep the code minimal, but looks like more detail is needed. I've created a non production jfiddle here with some notes to help explain what I'm trying to solve.
Hopefully this provides you with all details
http://jsfiddle.net/d86tm/5/
From looking at Google and SO nothing quite answers my answer...
After a user clicks an image I'd like to capture the attribute id assigned to the image and save it within a variable, something like
var friendRequestId = $(e.source).data("UserForBadge");
At the moment I have. But I'm not certain this is correct and its certainly returning an error
Uncaught ReferenceError: friendRequestId is not defined
Just looking for guidance/best practice example on how to complete this.
$(document).ready(function() {
$('.UserForBadge').css('cursor', 'pointer');
$('.UserForBadge').click(function(e) {
$(this).appendTo('friendRequestId');
// Nothing to worry about this part at the mo/////////
return false;
});
});
From what I understood by the question you wanted the id on the click of the image using jquery. Please find the fiddle
The code snippet used is:
e.target.id
if i understood correctly. your markup should be:
<img id="someId" onclick="imgClick(this)" />
and your js function:
function imgClick(sender){
var $img = $(this); //creates jQuery object from the DOM object
var id = $img.attr('id'); // extracts the id attribute
//your code...
}

Categories

Resources