Removing content of a var still failing [duplicate] - javascript

This question already has answers here:
How to change the Content of a <textarea> with JavaScript
(6 answers)
Closed 7 years ago.
Today i made a question and i tried to make some advices of experts on javascript, however my code it is still failing. Im going to try to give more information with the purpose to solve my problem. Im new on javascript and im completely sure that this will piece of cake for some people. This is my problem with my code. Im going to try to give all info as soon as possible.
I have this jsp with this textarea:
<form:textarea id="textEnv" path="buscadorReferenciaE" onkeyup="comprobarTexto();"
cssStyle="vertical-align: middle; margin-left:1px; width: 263px; height: 220px;" />
In this code as you can see a user enter string, and is involved in the onkeyup:
And this is my function on javascript:
function comprobarTexto(){
var texto = document.getElementById('textEnv').value;
if (texto.length > 14) {
texto= "";
}
}
The purpose of this function is that when the user reaches 14 characters the text on the texfield must be REMOVED COMPLETELY, however despite advices of experts my code still failing and the function doesnt work. Its very probably that is my fault, but im still not seeing how to resolve this. I give more information on the last question that i made:
Removing content of a var
It must be the function in javascript, that is not working, no more code of my jsp is involved. When the characthers reaches to 14 the function warn me with an alert(now is removed but it works) I will try tomorrow to solve this, with your help. Thanks for your help as always.

You must write to the text field:
function comprobarTexto(){
var texto = document.getElementById('textEnv').value;
if (texto.length > 14) {
texto= "";
document.getElementById('textEnv').value = "";
}
}
You copy the content of the textarea to a variable and clear the variable, but this leaves the textarea unchanged. So, clear the textarea too.

Check you rendered code in your browser:
var texto = document.getElementById('textEnv').value;
This may be correct when you are in the editor. But that ID changes once it renders. Set the ID to match what the rendered version shows.

The problem is that you are merely saving the reference to the value at that current time. Instead, I'd suggest something like this:
function comprobarTexto(){
var texto = document.getElementById('textEnv');
var current = texto.value;
if (current.length > 14) {
texto.value = "";
}
}
this way, you are defining it once and using it multiple times to do various things.
Hope this helps you understand!

Related

Javascript: " != " Operator doesn't work properly

Good evening !
I am facing a strange behavior with my js/jquery, for a simple function where I am retrieving the last ID of a row, in order to check wether or not it's different from the previous one:
oldMsgId = 0;
// Ajax...
currentId = $( ".message_container tr:last" ).attr('id');
checkNewMsg(currentId);
// ... End Ajax.
function checkNewMsg(MsgId) {
if (MsgId != oldMsgId) {
var snd_msg = new Audio('sound/msg.wav');
snd_msg.volume = 0.3;
snd_msg.play();
}
oldMsgId = MsgId ;
}
The system works, however, when no new messages are retrieved, which means the latest ID is EQUAL to the old ID, it still execute the condition !
Of course, it will execute once the page is loaded because the oldMsgId is set to 0, but after that by testing with alerts, it has shown that the condition is running as it should not !
It drives me crazy, if someone has a solution I would be glad to hear it :)
EDIT : RESOLVED
Well, while using alerts inside the function this time, it appears I have made a huge mistake placing my oldMsgId var inside a loop function (which calls to ajax), so, the variable was reset to 0 everytime and thus made the difference, I'm very sorry xD!
Problem resolved, thanks everyone !
Well, while viewing with alerts inside the function this time, it appears I have made a huge mistake placing my oldMsgId var inside a loop function (which calls to ajax), I'm sorry xD!
Problem resolved, thanks everyone !

Why does this script never run?

I've got the following JavaScript statement, that executes on Page Load:
The variable u1 is populated with one of the following values:
BBSLoan|Accept|PPI+No|60Months
BBSLoan|Refer|PPI+No|60Months
HSBSLoan|Accept|PPI+No|48Months
HSBSLoan|Refer|PPI+No|48Months
I have been informed that the conditions in the conditional statements will never be met - is this true? From what I can see, going on each of the variables, the index that will be returned by indexOf is 0? Unless I am mistaken?
EDIT: Just to clarify, the variable 'u1' will be populated dynamically with any of the 4 strings listed above. The %pu1=!; is actually a macro that will populate this value.
<script language="JavaScript" type="text/javascript">
var u1 = '%pu1=!;';
if (u1.indexOf('BBSLoan|Accept') > -1) {
var pvnPixel = '<img src="http://www.url1.com"/>';
document.writeln(pvnPixel);
}
if (u1.indexOf('BBSLoan|Refer') > -1) {
var pvnPixel2 = '<img src="https://www.url2.com;"/>';
document.writeln(pvnPixel2);
}
if (u1.indexOf('HSBSLoan|Accept') > -1) {
var pvnPixel3 = '<img src="https://www.url3.com;"/>';
document.writeln(pvnPixel3);
}
</script>
Thanks in advance!
EDIT: Just to clarify, the variable 'u1' will be populated dynamically with any of the 4 strings listed above. The %pu1=!; is actually a macro that will populate this value.
This answer is not correct. It will be deleted later, but is being left to prevent this answer from popping up again.
var u1 = '%pu1=!;';
The value of u1 is always '%pu1=!;', since you declare it as that.
Ok I finally got this to work using search instead of indexOf!
Would it make more sense to use a switch statement with a default case, or at a minimum provide an "else" with a default?
Have you tried to put a debugger statement in after var u1 is set, and step through using the client (firefox, chrome, IE, safari all have built in "developer tools" with the ability to step through js code) debugger to see what the value of u1 is?

Having problems with the mouseup event

Hello I am working on two functions swapFE() and swapEF(). The purpose of these two functions is to exchange the French phrases with the English phrases which I've already done.
When I press the mouse button down on each phrase the English translation appears which is what i want it to do.
The problem is when I release the mouse button the French phrase should reappear and it doesn't happen. I don't know what I'm doing wrong.
I would appreciate it if someone can help me. Thanks for your time and for your help.
function swapFE(e){
var phrase = e.srcElement;
var parent = phrase.parentNode;
var idnum = parent.childNodes[0];
var phrasenum = parseInt(idnum.innerHTML)-1;
phrase.innerText = english[phrasenum];
phrase.className ='english';
}
function swapEF(e){
var phrase = e.srcElement;
var parent = phrase.parentNode;
var idnum = parent.childNodes[0];
var phrasenum = parseInt(idnum.innerHTML)-1;
phrase.innerText = french[phrasenum];
phrase.className ='french';
}
Without seeing your html it's difficult to determine if your issue is (1) your javascript method (I'm assuming swapEF) isn't working correctly or (2) the assignment of your event handler is not working or both. Make sure you are using the correct event functions ( "mousedown" and "mouseup") and try to test your functions manually in a javascript debugger like firebug or the Chrome javascript console. That will help you pinpoint the issue and fix your problem, but without the html and the assignment of your event handler it is difficult to post a solution.

Javascript/jQuery function yields undefined in <IE8

A short while back I asked a question here about how I could calculate when a heading was longer than one line within a given container, and subsequently wrap each of these lines in a <span>:
Use Javascript/jQuery to determine where a heading breaks to the next line?
I chose an answer which worked great for me, at least until I checked in IE7 and IE6, in which all the headings handled by this script rendered as
"undefinedundefinedundefinedundefinedundefinedundefined[...]"
on the page. As I'm not really a JavaScript person (that's why I asked such a question in the first place), it's really tough for me to figure out where the problem is. I assumed an undefined variable or something, but I just can't seem to grasp it.
Can anyone help?
I'll repeat the code here, but please refer to the link above for context:
$(function(){
$h = $('.fixed').find('h3');
$h.each(function(i,e){
var txt = $(e).text();
$th = $('<h3 />').prependTo($(e).parent());
var lh = $(e).text('X').height();
$(e).text('');
while (txt.length > 0) {
$th.text($th.text() + txt[0]);
txt = txt.slice(1);
if (($th.height() > lh) || (txt.length <= 0)) {
var shc = $th.text().split(' ');
var ph = shc.slice(0,-1).join(' ')+' ';
if (txt.length <= 0) { ph += shc.pop(); }
$('<span />').text(ph).appendTo($(e));
$th.text(shc.pop());
}
}
$th.remove();
})
});
You need to change
$th.text($th.text() + txt[0]);
to be
$th.text($th.text() + txt.charAt(0));
IE<8 doesn't accept string positions through array indexes ;)
The styling doesn't work, but that'll be a CSS issue which I couldn't fix before leaving. But everything is wrapped in spans :)
Nothing jumps out at me. But, since you mentioned in your comment to your question that you see "undefined" in Firebug, I would start there. Even though those browsers are failing gracefully, the fact that you see undefined there is your first hint to finding the problem for the harder-to-diagnose IE6/7. I would use Firebug and either breakpoint in the function, or use some console.log() calls to document what the values that you are working with are each step of the way. Once you start seeing undefined... you have likely found your problem.

How can I ensure that changes to a form DOM are complete before POSTing?

Currently I have a race condition existing in my JavaScript code. What I am trying to do with this code is convert all check boxes which are a part of the 'checkbox' class and are not checked into text boxes with a value of zero. Currently when you post a check box that is not checked it does not appear in the $_POST data. However I need to know all the values whether true or false for these particular set of check boxes.
The code I have is here:
Code:
function checkboxConvert() {
var chkBxs = $$('.checkbox');
for (var i = 0; i < chkBxs.length; i++) {
if (chkBxs[i].checked == false) {
chkBxs[i].type = 'textbox';
chkBxs[i].value = '0';
}
}
setTimeout("document.productForm.submit();",1000);
}
Now the problem that I have been getting is that when I try to submit this form the values of the recently changed text boxes does not appear in the $_POST data. Therefore, as you can see above I have postponed the page submit for 1 sec and then I have all the data available to me. However as time goes on and my data set gets larger, 1 sec may no longer be enough. This I think is a race condition and I need to figure some way of running the code only after all the check boxes have been converted and they have their new values. I would have thought that this would be unnecessary from the start, but for some reason it's trying to run both pieces simultaneously and I can't submit until I have the proper values in place.
Any help is much appreciated!
This is definitely not the way to do web. I strongly advise you abandon your checkboxConvert function, and solve this issue on the server side
JavaScript always runs single-threaded in the browser so I don't think it can be a race condition.
I'd generally agree with others that you shouldn't do this, but your problem may be that you're changing the element to a type of "textbox" instead of "text". If you declare an input of type "textbox" in HTML markup, it will usually render as a text field anyway because that's the default. However, changing an already valid "checkbox" type input to the invalid "textbox" may not work predictably.
Try changing it to this:
function checkboxConvert() {
var chkBxs = $$('.checkbox');
for (var i = 0; i < chkBxs.length; i++) {
if (chkBxs[i].checked == false) {
chkBxs[i].type = 'text';
chkBxs[i].value = '0';
}
}
// Because JS in the browser is single-threaded, this
// cannot execute before the preceding loop completes anyway.
document.productForm.submit();
}
There's got to be a better way to do this. Try something like:
Know about all your possible values on the server side. It looks like you're using PHP; keep a simple array with the names of your checkboxes.
When you take your $_POST data, remove the names of checkboxes you've received values for from your array.
The remaining are all false.

Categories

Resources