How to display the value of a variable within javascript? - javascript

Here I want to trap and alert or echo the value of var thisCount
The problem is I can't display the value.I'd tried many ways but no luck.
$(document).on("click", ".open-dialog", function () {
var thisCount = $(this).data('count');
//this place the code
$(".modal-body #count").val( thisCount);
});

Your question doesn't really clarified what you've tried or where you want the value displayed, but common answers are:
1) Console. This will output to your browsers log.
console.log(thisCount);
2) If you want to put it into an HTML tag, you can use classic javascript
document.getElementById('yourTagsId').innerHTML += thisCount;
// You can use = instead of += as well
3) You could also use an alert or a confirm
alert(thisCount);
confirm(thisCount, function(){return true;});
// confirm takes both a displayed value, and a function which will be performed when the user presses the 'Ok' button

If you need ah dataattribute like this below .alert console.log both are working
$(document).on("click", ".open-dialog", function () {
var thisCount = $(this).data('count');
$("#count").val( thisCount);
console.log(thisCount)
alert(thisCount)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="open-dialog" data-count="hello">click</button>
<input type="text" id="count">

Maybe you should verify if the jquery library is properly imported
Also, you can use the Chrome Developer tools (Ctrl +Shift+ i) and verify the value in the javascript console. Just to see if you can see the value in the debugger.

Related

Get true value of textarea

Recently I encountered an issue with the textarea. If I have a textarea likeso,
<textarea>Hello World</textarea>
And I get the contents of it with JS,
var textareaText = document.getElementsByTagName('textarea')[0].value
The variable textareaText is Hello World. But if I were to change the value of the textarea and re-run the JS. It would still result in Hello World despite the true current value being something else. I've looked this up and seen +5 answers but all of them use jQuery which is something I don't use or know (to translate) and none pure JS. If anyone could help me out it would be greatly appreciated. Also some of the answers seemed to be just for one textarea. In my project I'd have +1,000 so I'd like to avoid that.
This should work, no matter how many <textarea>'s you use, this should work:
<textarea id="textarea1">hello</textarea>
<textarea id="textarea2">goodbye</textarea>
<button id="button">button</button>
<script type="text/javascript">
var button = document.getElementById("button");
button.onclick = function() {
alert(document.getElementById("textarea1").value + "\n" + document.getElementById("textarea2").value);
};
</script>
I just tested it and it works, no matter which values I change, and even if I change both. The trick is to not store the values, as they aren't updated, so you should get the value on-the-spot.
Although it was against the questions guidelines, with "1000+" textareas, setting a JavaScript variable for each one might slow down loading times. May I suggest jQuery, with the same HTML?
<script type="text/javascript">
$("#button").on("click", function () {
alert($("#textarea1").val() + "\n" + $("#textarea2").val());
});
</script>
Of course, feel free to mix up and change up the code provided above. Hope this helps!
It works fine in my computer:
function getText(){
var textareaText = document.getElementsByTagName('textarea')[0].value;
console.log(textareaText);
};
<textarea>Hello World</textarea><br>
<button type="button" onclick="getText();">Get text</button>
May be?
<textarea id="text-area">Hello World</textarea>
var el = document.getElementById("text-area");
var textareaText;
el.addEventListener("input", function(e) {
textareaText = e.target.value;
console.log(e.target.value);
});

JavaScript and WordPress: button click not found by addEventListener

To prevent answers like: 'is the JavaScript file loaded?' -> Yes, it is loaded, at the footer part of the page! I have checked that with a simple message to the console, which is displayed!
But:
I've got a page with a button:
<button id="portfolio-posts-btn">Load portfolio related blog posts</button>
And a file main.js:
var portfolioPostsBtn = document.getElementById('portfolio-posts-btn');
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
if (portfolioPostsBtn) {
portfolioPostsBtn.addEventListener("click", function () {
console.log("the button was clicked!");
});
}
The text the button was clicked! should be displayed in the console, but it stays empty!
Apparently, the button click is not recognized, and thus, the var portfolioPostsBtn is false, or NULL... -> the method addEventListener() is not fired ?
I don't see the cause for this; I checked the spelling, should I use single or double quotes? Please help?
Thank you!
I've had this happen to me before, since theres two ways to do this I just used the other.
The first is onclick="function()", this is used as an attribute inside the element. Ex:
function clicked(){
alert("button clicked");
}
<button onclick="clicked();">Press me</button>
exaplaination: When you add this attribute to this element and I do believe some others when the button is clicked the specified code inside the quotes of the attibute will run. It doesn't have to be a number, e.g. onclick="alert(12+4/2);". But this is more of HTML than JavaScript using this version
The other way is using what you've got which (to me) is a lot more difficult then it needs to be. Heres my example
var b = document.getElementById("btn");
b.addEventListener("click", blogged);
function blogged(){
alert("this post has been blogged");
}
<button id="btn">Blog it</button>
This side of things has more to do with JavaScript and Event listeners. But the problem with you're code is that you're putting the event listener after you call the if statement. Here's my solution
var portfolioPostsBtn = document.getElementById('portfolio-posts-btn');
portfolioPostsBtn.addEventListener("click", function(){
check();
});
function check(){
if(portfolioPostsBtn){
console.log("posted");
}
}
<button id="portfolio-posts-btn">press this to post<button>
Presumably you have made a decision not to use jQuery. You'll need to wrap your code in an event listener so that the code is executed when the DOM is ready.
document.addEventListener("DOMContentLoaded", function(event) {
var portfolioPostsBtn = document.getElementById("portfolio-posts-btn");
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
if (portfolioPostsBtn) {
portfolioPostsBtn.addEventListener("click", function () {
console.log("the button was clicked!");
});
}
});
The answer is found in the uploading of the file page-portfolio.php!
I found out that the id="portfolio-posts-btn", added later, was not updated - could be my mistake, or the SFTP upload extension in Brackets - I did not see an error message!
Anyway, the issue is solved!
One more question: "are there methods to check if an id exists?". That could make live easier!
All contributors, thank you for your answers!

Getting the contents of a span to change as I change a number input

I had a more complicated form working a couple of days ago, but suddenly it stopped working and I'm rubbish at saving versions, so I've taken it right back to basics, and I can't get it to work. What am I doing wrong? Am I using onInput incorrectly?
<input type="text" id="number-of-copies-value" onInput="quote()" value="500">
<span id="total-cost-value">0.00</span>
And here's the Javascript:
function quote() {
var totalcostvalue = document.getElementById("total-cost-value");
var numberofcopiesvalue = document.getElementById("number-of-copies-value").value;
var totalcost = (+numberofcopiesvalue);
totalcostvalue.innerHTML=totalcost.toFixed(2);
}
quote();
https://jsfiddle.net/tod0wusv/1/
Your HTML expects the quote() function to be globally available. Make sure that is the case.
If I change your fiddle to have quote() available on global window object like,
window.quote = function quote() {
// ...
};
the fiddle starts working again.
WORKING FIDDLE
If I create a local HTML file with your content, it works right away, which makes sense since quote() is defined on global scope.
Looks like JSfiddle executes the JavaScript in a function scope which breaks your quote() call.
If you care about browser compatibility I would suggest using the onkeydown event with a setTimeout function as described here Detecting "value" of input text field after a keydown event in the text field?
To make this work in JSFiddle, change the javascript "load type" setting in your JavaScript settings to one of the "no wrap" options.
HTML
<input type="text" id="number-of-copies-value" onkeydown="window.setTimeout(function() { quote(); }, 1)" value="500">
<span id="total-cost-value">0.00</span>
JavaScript:
function quote() {
var totalcostvalue = document.getElementById("total-cost-value");
var numberofcopiesvalue = document.getElementById("number-of-copies-value").value;
var totalcost = (+numberofcopiesvalue);
totalcostvalue.innerHTML = totalcost.toFixed(2);
}
quote();
I've updated your JSFiddle...
https://jsfiddle.net/tod0wusv/6/

Div does not refresh when last character is deleted from input

I'm currently making a search function using a onkeyup="Search();" like this:
<input type="text" id="IDsearch" onkeyup="Search()" autofocus>
The function for it is:
<script type="text/javascript">
function Search() {
var inputVal = $('#IDsearch').val();
$.post('searchTest.php', {postname: inputVal},
function (data) {
$('#IDsearch').val(data)
});
$('#divRefresh').load('searchTest.php');
}
</script>
Yes, I am using the same file to both put the value in a php $_SESSION['value']; AND to store the new div data. That's no problem, it works, it does fine.
But when I delete my last character from my search box, I need to press backspace twice in order for my div to update.
Say I had a textbox with "a" in it. I will press backspace to update the a, and nothing will happen. Once I press backspace again, my div will update and post all the original values again.
Am I missing something obvious?
It's supposed to work the same way http://www.datatables.net/ does.
I have asked a question about this program before, but not about this issue, I hope it's not a problem.
I would go throught $("#IDsearch").keyup(function(){});
Tried your code with the function and didn't work, even with $("#divRefresh").html(theInputOfYours); The other way I mention to you works perfectly, even with backspace.
$(document).ready(function() {
$("#IDsearch").keyup(function() {
var value = $(this).val();
var posting = $.post("your_php_file.php", {val: value})
posting.done(function( data ) {
$( "#divRefresh" ).html(data);
});
});
});
The posting is a very basic example I can give, I use to go with $.ajax() function
Unfortunately, the behavior of keyup/keypress/keydown can be finicky sometimes, especially across different browsers.
A possible solution to ensure changes are tracked would be a listener that would track changes via a setInterval function that runs at an interval you specify.

Prevent closure in jQuery/JavaScript

I'm trying to do something that seems (to me, at least) to be a fairly easy, common thing to do.
Here's the HTML for what I've got on a web page:
<div class="allergiesDiv">
<div>
<span class="editButton">Allergies</span><br />
</div>
<span>Allergies</span>
</div>
</div>
I turn the first <span> into a jQuery button with $('.editButton').button().
(I have many of these pairs on the page.)
What I am trying to do is the following:
When the button is clicked, it loads a jQuery Dialog with the value of the span that follows it loaded into a <textarea>. (BONUS: When the dialog is loaded, I'd like the <textarea> to be focused and all text inside highlighted.)
The user is able to edit the value and then click 'OK'.
When the user clicks 'OK', the Dialog is dismissed and the new value that was entered is used to replace the old value for the span.
Here's the code I'm trying to use (this works OK in IE, but breaks in Mobile Safari and Chrome for PC):
NOTE: I've been chopping the code up some to try to get each problem isolated. I have had this working, at least in IE.
// How I get the button and bind to the click event
$('.editButton')
.button({icons: {primary:'ui-icon-pencil'} })
.click(EditClicked);
// 'Edit' button click handler
function EditClicked() {
var span = $(this).parent().next().children().first();
var text = span[0].innerText;
var dialog = $('<div>').prop('title', 'Edit: ' + $(this).text());
var textArea = $('<textarea>').css('width', '98%').prop('rows', '4').html(text);
textArea.appendTo(dialog);
var windowWidth = $(window).width();
var buttonTop = $(this).button().offset().top;
$(dialog).dialog({
modal: true,
minWidth: windowWidth / 2,
position: ['center',buttonTop],
buttons: {
'Ok' : function () {
OKClicked(span);
},
'Cancel' : function () {
$(this).dialog('close').remove();
}
}
});
textArea.focus().select();
}
// Dialog 'OK' button click handler
function OKClicked(span) {
var text = $(this).find('textarea')[0].innerText;
span.html(text);
$(this).dialog('close').remove();
}
This is currently broken when it gets to var buttonTop..., with the error message of "button is undefined". I haven't yet figured out why that is (I used to have a variable in that method named 'button', but it's gone now. Not sure if that's a caching issue.)
Other than that, can anyone see what's wrong with my process? It seems like I've got some kind of misunderstanding with closure, but I'm not yet good enough with JavaScript to understand how to get the kink out of this code.
what about
var buttonTop = $(this).offset().top;
I am not sure, that $('<div>') is properly syntax for jQuery. Try to use $('div') instead.
When you use $(this).button() - you try to call button method of $(this) object. Seems like a bug.

Categories