Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am testing a line of code where it checks a variable if it is empty or not. If its empty a prompt pops up. But even if the variable has something, the prompt still pops up.
function myFunction(){
if (site == null || variable == undefined) {
var site = prompt("Please enter a valid url:", "http://");
document.cookie = 'Your bookmark is: '+ site;
alert(unescape(document.cookie));
document.getElementById("p1").innerHTML = '<a class="txt2" href="' + site + '" target="myframe">' + site + '</a>';
}
else {
alert('yey its working');
}
}
<a class="txt2" id="p1" onclick="myFunction()">Button</a>
The code works it's just after the variable is set the prompt pops up again before it loads the page.
It is because variable is undefined (we are not setting it anywhere), the if block always runs.
Also, if site variable seems defined in the scope of myFunction -
Variables declared within a JavaScript function, become LOCAL to the
function
Ideal way is to check for document.cookie instead of variables -
function myFunction(){
if ( document.cookie == '') {
var site = prompt("Please enter a valid url:", "http://");
document.cookie = 'Your bookmark is: '+ site;
alert(unescape(document.cookie));
document.getElementById("p1").innerHTML = '<a class="txt2" href="' + site + '" target="myframe">' + site + '</a>';
}
else {
alert('yey its working');
}
}
myFunction();
Check it working in JSFiddle
Your if statement evaluates two variables which only either one has to be true in order for the if statement to be true.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 months ago.
Improve this question
I've searched the jQuery docs and here and can't find an answer to my exact problem...
With a DRY spirit, I want to use javascript to add a character object countdown helper to any textarea element with maxlength and aria-describedby attributes.
Obviously I also need to use javascript to monitor keyup events to update the counter. I'm using jQuery 3.6.0. However, I can't seem to get the countdown method to recognize the newly-added "helper" div element. Here's what I have so far:
$(document).ready(function () {
// "characters remaining" countdown
function textCounter(field) {
var charLimit = field.attr("maxlength");
console.log("charLimit=" + charLimit);
// hack to *double-count* '\r\n' (client/DB discrepency)
var numLines = (field.val().match(/\n/g) || []).length;
var charLength = field.val().length + numLines;
console.log("charLength=" + charLength);
var charDiff = charLimit - charLength;
console.log("charDiff=" + charDiff);
if (charLength > charLimit - numLines)
field.val(field.val().substring(0, charLimit - numLines));
var count = $("#" + field.attr("aria-describedby") + " .count");
console.log(count.html());
count.html(Math.max(0, charDiff));
}
// add countdown helper div
$("textarea[maxlength]").each(function (e) {
var helpID = "#" + $(this).attr("aria-describedby");
var helpDiv = $('<div id="' + helpID + '"><span class="count"></span> characters left.</div>')
$(this).after(helpDiv);
textCounter($(this));
})
// update counter on keyup events
$("textarea[maxlength]").keyup(function () { textCounter($(this)); })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea maxlength="2000" aria-describedby="content-help" id="content" name="content"></textarea>
I can confirm that:
The helper div element is getting added
Via the console.log statements, the textCounter() method is getting called, but the count object resolves to undefined (even though it is clearly there), and
If the element is hardcoded in HTML (i.e., not dynamically added) the counter works as expected.
Other searches suggest that .delegate() or .on() are part of the answer, but everything I've tried has the exact same behavior as above. :( Every other Q/A I've come across is, for example, binding a click/hover event to the newly-added element, but here it's the textarea that needs monitoring (not the new helper element, although it will be updated), if that makes sense...
Note that I want the solution to work on pages that have multiple textareas, each with potentially different maxlength attributes.
Any thoughts how to accomplish this?
The line:
var helpID = "#" + $(this).attr("aria-describedby");
means that your selector:
var count = $("#" + field.attr("aria-describedby") + " .count");
Should be:
var count = $("#\#" + field.attr("aria-describedby") + " .count");
Or you could simply not include the "#" character when creating the element, giving:
var helpID = $(this).attr("aria-describedby");
Unfortunately this is a typo question (so it will be closed as such), this answer exists only temporarily to clearly show the error.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am working on a Blazor server project and have this button in my component
<button type="button" class="btn btn-primary" #onclick="#GetUserInput">Add Name</button>
Here is the code I have that the click event is calling
protected async void GetUserInput()
{
var result = await JsRuntime.InvokeAsync<string>("getName");
}
function getName() {
var retVal = prompt("Enter Name : ", "name here");
return retval;
}
In the javascript function, retVal has a value but in the GetUserInput method,
the code crashes with the error message below
ReferenceError: retval is not defined
at getActivityName (https://localhost:44318/script.js:15:11)
at https://localhost:44318/_framework/blazor.server.js:1:70045
at new Promise (<anonymous>)
at e.beginInvokeJSFromDotNet (https://localhost:44318/_framework/blazor.server.js:1:70011)
at https://localhost:44318/_framework/blazor.server.js:1:26293
at Array.forEach (<anonymous>)
at e.invokeClientMethod (https://localhost:44318/_framework/blazor.server.js:1:26263)
at e.processIncomingData (https://localhost:44318/_framework/blazor.server.js:1:24201)
at e.connection.onreceive (https://localhost:44318/_framework/blazor.server.js:1:17286)
at WebSocket.i.onmessage (https://localhost:44318/_framework/blazor.server.js:1:46503)'
I am not sure what is going on? Any ideas?
Javascript is case sensitive. retVal, not retval - JS won't complain about "retval" - it's just undefined.
function getName() {
var retVal = prompt("Enter Name : ", "name here");
return retVal;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Edit: Not a duplicate as this is not a question about using === vs ==. Both of those methods fail.
First two lines from csv:
email,Product,Term,Rate
example#gmail.com,New,24 Months,1.99%
I have tried both === and == in an if statement but it always fails. Here is the code I use. First I create the array from a csv file. Then I loop through that array. When I echo on the second to the last line the output is example#gmail.com - example#gmail.com.
This works with if(line[0] === 'New'){ until I add in the email column in my csv sheet, but now even running if(line[1] === 'New'){ does not work if the email column is there. I checked again, and by removing the email column, it works fine. Everything is formatted as text in the csv.
casper.then(function readFile() {
var stream = fs.open('ck.csv', 'r');
var line = stream.readLine();
var lineArray = [];
while(line) {
lineArray.push(line);
line = stream.readLine();
}
casper.eachThen(lineArray, function(response) {
line = response.data.split(',');
this.echo(line[0] + ' - ' + email);
if(line[0] === email && line[1] === 'New'){
Make sure both email and line[0] trimmed. (Use email = email.trim())
You can also use the localeCompare() Method
If they are equal, you'll get 0. And we all know !0 is true.
http://www.w3schools.com/jsref/jsref_localecompare.asp
if(!line[0].localeCompare(email) && !line[1].localeCompare('New')){}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have this function which produces the correct value when run, but I am having a hell of a time displaying the results.
Here is the JS which is calculated onChange in a form I am trying to display the resulting value elsewhere on the form. The alert displays the correct value but my id remains blank.
Thanks in advance for taking a look
function calculate_mtow1() {
togw_n = 0;
togw = $('#togw').val();
if (togw != '' && togw != 0 && togw != 'Nan') {
var togw = togw.replace(",", "");
togw_n = togw;
}
burn_n = 0;
burn = $('#burn').val();
if (burn != '' && burn !=0 && burn != 'Nan') {
var burn = burn.replace(",", "");
burn_n = burn;
}
var mtow1 = parseInt(togw_n) + parseInt(burn_n);
$('#mtow1').val(mtow1);
document.getElementById('mtow1');
alert(mtow1);
}
<td>TOW + Fuel Burn =<span id="mtow1"></span></td>
Your code is getting the element with getElementById but then not doing anything with it. You need to assign the result of getElementById to something, or call methods on it on the same line. If your goal is to put the value of mtow1 into your <span>, try doing this:
// Solution 1
var spanElement = document.getElementById("mtow1");
spanElement.innerHtml = mtow1;
Alternatively, perhaps you were trying to display the value of mtow1 by using this jQuery:
$('#mtow1').val(mtow1);
That doesn't do what you think it does. It changes the "value" attribute of the span to the value of mtow1, but that change isn't visible to the user. It's the same as writing this as your HTML:
<td>TOW + Fuel Burn =<span id="mtow1" value="valueofmtow1"></span></td>
If you want to use jQuery instead of the getElementById method I posted above, you could do this:
// Solution 2
$('#mtow1').html(mtow1);
You don't need to do both. Either solution will work on its own.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm doing my first project using AngularJS and now i've run into a JavaScript problem that just can't understand. Perhaps this is trivial to someone more experienced in JS, if so i hope you guys can help me :)
I've doing this string comparison in function, that receives an id passed as a parameter from a view, which it then compares to id of objects kept in the service:
for (var i = 0; i < this.Sessions.length; i++) {
if (this.Sessions[i].sessionId === sessionId) {
for (var j = 0; j < this.Sessions[i].Instances.length; j++) {
if (this.Sessions[i].Instances[j].instanceId === instanceId);
{
console.log("InstanceId's: " + this.workoutSessions[i].Instances[j].instanceId + " " + instanceId);
//Do stuff and return.
}
}
}
}
When i run the method all the instanceId's of all the instances will evaluate to true.. Why??? As far as i know i'm just comparing strings, but i guess not. The outer comparison works as it should, which makes it even stranger to me.
Output in console, showing that they evaluate to true no matter the value of the strings.
InstanceId's: l0h34qzzgdlpu8fr 42p9smh9kxdsfw29
InstanceId's: 42p9smh9kxdsfw29 42p9smh9kxdsfw29
Really what i want to do is stop the function as soon as i've found the correct instance, but if i put in a return statement inside the IF-block my compiler tells me the j++ statement is unreachable, indicating no matter what the expression is going to be true, and... that is just beyond me.
How the parameter is passed from the view:
<div ng-repeat="instance in session.Instances">
//Some form controls here...
<div style="float: right;">
<button class="btn btn-default" ng-click="addOne(session.sessionId, instance.instanceId)"> + 1</button>
<button class="btn btn-default">Remove</button>
</div>
</div>
Can anybody help??
Thanks in advance.
if (this.Sessions[i].Instances[j].instanceId === instanceId);
the colon at the end seems to be the culprit...
delete the semicolon in the if clause.
Your Code will be same as
if (this.Sessions[i].Instances[j].instanceId === instanceId)
{
;
}
{
console.log("InstanceId's: " + this.workoutSessions[i].Instances[j].instanceId + " " + instanceId);
//Do stuff and return.
}