Changing input text value with Javascript doesn't change display - javascript

I'm trying to change the value of a text input field based on user actions. I'm doing it like this:
document.getElementById(textFieldID).value = newValue;
It isn't quite working -- the original text in the field remains on the screen, unchanged. However, when I submit the form, it behaves as though the value was indeed changed correctly. (And a debug alert confirms that yup, I'm hitting that bit of the code and passing in the right field ID and text value.) Anybody have any insights? Is there something I need to be doing to redraw the input element?
Edit: Per Jeff B's request, and per the fact that this seems to have everybody stumped, here's some relevant bits of code:
<script LANGUAGE="JavaScript" TYPE="text/javascript">
function changeText(changeSelector)
{
var myindex = document.getElementById(changeSelector+"Recent").selectedIndex;
var SelValue = document.getElementById(changeSelector+"Recent").options[myindex].value;
document.getElementById(changeSelector).value = SelValue;
document.getElementById("historicalText").value = SelValue;
document.getElementById("historicalTextSelect").value = changeSelector;
}
</script>
<input onChange="updateScrollingPreview1217(this); return true;" type="text" id="crawlMsg1217" name="crawlMsg1217" size="60" maxlength="1000" value="">
<select id="crawlMsg1217Recent" name="crawlMsg1217Recent" onchange="javascript:changeText('crawlMsg1217');">
[options go here]
</select>
And that "onChange" handler isn't what's gumming up the works; I get the same behavior with or without it.
Edit 2: It looks like the problem is being caused by "JSpell", a third-party spelling checker our product uses. (I'm told that clients prefer using it to a spellcheck built into the browser; go figure.) It appears to be slightly misconfigured on my test machine, so I'm going to try straightening that out and praying that it makes the problems go away. If it doesn't ... should be interesting.
Edit 3: Yup. Fscking JSpell. Just posted a complete answer for the sake of posterity, will accept it tomorrow when I'm allowed. My thanks to everybody who tried to help; +1's all around, wish I could give more.

I have confirmed that the culprit is indeed JSpell, and that the precise trouble spot is this line:
window.onload=jspellInit;
Despite the prayers mentioned in Edit 2 above, making sure it was configured correctly did NOT make the problem go away. And this line is indispensable to JSpell's functionality. I don't know if JSpell always hoses Javascript functionality this way, or if there's some sort of perfect storm of factors that's causing it to pick a fight with my page, but that is indeed the source of my problems.
My thanks to everybody who tried to help. This was obviously a bit of a no-win in terms of getting the right answer, since it was caused by a component that was seemingly entirely unrelated and thus didn't get mentioned by me, but you at least confirmed that I was (in theory) doing things right and not simply going insane.

Is the document's id actually "textFieldID" or is "textFieldID" a javascript variable that contains the ID of the text input to change? If it is not a variable, I believe you should make it:
document.getElementById('textFieldID').value=newValue;

It's hard to debug this without the context, since the code you have ought to work fine. Can you confirm that you've got the right node by doing something like:
document.getElementById(textFieldID).style.border = "4px solid red";

What does any other element on the page have a name attribute that is the same as the id?
Internet Explorer 8 and later. In IE8
mode, getElementById performs a
case-sensitive match on the ID
attribute only. In IE7 mode and
previous modes, this method performs a
case-insensitive match on both the ID
and NAME attributes, which might
produce unexpected results. -
http://msdn.microsoft.com/en-us/library/ms536437%28VS.85%29.aspx
Try alerting your the nodeName and id ofr the returned element and make sure its the input you expect.

Use div element instead of textfield. I had same problem, my textfield which is changed with another script wasnt get the right value. you can easily use any div element like textfield with some CSS. than you can get the value from div using innerHTML.

Related

Jquery $('input[name=""]').change(function WILL NOT FIRE in Chrome unless there is an uncaught error after it

So, here's a script that I've written to make some inputs dependent on an affirmative answer from another input. In this case, the 'parent' input is a radio button.
You can see that it hides parent divs of inputs when the document is ready, and then waits for the pertinent option to be changed before firing the logic.
If you'll look at the comment near the bottom of the javascript, you'll see what's been stumping me. If I remove the if statement, the change function does not fire. If I set the variable so that there is not an error logged in the console, then the change event does not fire.
If I change the jquery selector to $('select').change... the event fires, but obviously won't work on a radio button. Changing it to $('input').change... also fails.
<script type="text/javascript"><!--
$(function(ready){
$('#input-option247').parent().hide();
$('#input-option248').parent().hide();
$('#input-option249').parent().hide();
$('#input-option250').parent().hide();
$('#input-quantity').attr('type', 'hidden');
$('#input-quantity').parent().hide();
$('input[name="option\\[230\\]"]').change(function() {
if (this.value == '21') { //If yes, display dependent options
$('#input-option247').parent().show().addClass('required');
$('#input-option248').parent().show().addClass('required');
$('#input-option249').parent().show().addClass('required');
$('#input-option250').parent().show().addClass('required');
} else if (this.value == '22') { //If no, hide dependent options
$('#input-option247').parent().hide().removeClass('required');
$('#input-option248').parent().hide().removeClass('required');
$('#input-option249').parent().hide().removeClass('required');
$('#input-option250').parent().hide().removeClass('required');
}
});
//I don't know why this is necessary, but the input.change() event WILL NOT FIRE unless it's present. If I set the variable, then it breaks the change function above. If it's not here, it breaks the change function above. I'm stumped.
if(poop){}
});//--></script>
I'm really hoping that someone will see something rather obvious that my tired brain won't see. This is such a simple script, and I'm pulling my hair out over what seems like a rather annoying bug.
If you selector has special characters you need to use \\ before those characters.
$('input[name="option[230]"]')
should be
$('input[name="option\\[230\\]"]')
See http://api.jquery.com/category/selectors/
This may or may not be a good answer, but I managed to get the problem solved. I have another script on the page that is firing on the change event using this selector: $('select[name^="option"], input[name^="option"]').change(function() {
My best guess is that both functions cannot fire using a single change event from the same element. I moved the functional part of the code above to be within the second script, and it seems to be working as expected. If anyone wishes to contribute an answer that explains this behavior, I will accept it.

How can I tell what I am iterating over in jQuery?

When I am debugging jQuery code, how can I tell what elements my selector is operating on?
I just spent a couple of hours trying to figure out what I was doing wrong with this code that is supposed to turn off one input field and turn on another:
<input id="qty-dropdown" ...>
<input id="qty-box" ...>
...
$('.qty-dropdown').hide();
$('.qty-box').show();
and of course the problem was that it should have been
$('#qty-dropdown').hide(); // # for ID, not . for class
$('#qty-box').show();
I was working on figuring if I was calling hide() and show() incorrectly, and not realizing I was operating on zero elements. If I had been able to tell that $('.qty-dropdown') was selecting no elements, I'd have saved a lot of time.
Is there anything I can do like:
$('.some-selector').dump()?
that will give me debugging information?
This question has an answer with a chunk of code that looks like it should dump into the console, but dropping that into my code didn't seem to put anything into my Firebug console.
I also realize that my original problem could have been solved with:
alert( $('#js-qty-dropdown').length );
but I am looking for a more complete solution for next time.
jQuery objects act kind of like arrays. Get the number of elements selected:
$('.qty-dropdown').length
If you are using Chrome for debugging, you can log out the object and hover over the different elements, and it will highlight them on the page:
console.log($('.qty-dropdown'));

ng-show won't work in h2 tags, but works later in html code

I am using angular with html5. I have the following code near the top of my page:
<h2 ng-show="stat == 'Active'">Carry On!!</h2>
<h2 ng-hide="stat == 'Active'">Account deactivated. To reactivate, please click Here.</h2>
It's part of a greeting. I basically want to check if the status of the user is active. If it is, then certain things on the page appear. If the status is deactivated, on hold, etc., then I want to tell them they need to reactivate their account to continue going. There's also a lot of account info on the page that I use ng-show/hide for that works perfectly. In sublime, I just selected all the open space where I wanted to type and typed them all up the same way so I don't think there's a problem with syntax.
For folks who still want to see what ngShow/Hide I use later, here it is:
<div ng-hide="stat == 'Active'"> <div class="conf"><div class="cont"></div></div></div>
<div ng-show="stat == 'Active'">
Sounds to me like your page might have some invalid markup maybe? Does it validate with the HTML5 validator?
If it does then something you can try is using an object.
In your controller do something like:
var ctrlObj = {stat: 'Active'};
Then in your markup do:
<div ng-show="ctrlObj.stat == 'Active'"></div>
There is a good article somewhere on the web arguing the case for never using double equals. I haven't used one in over 2 years since. === does type checking too. Makes for more robust code.
Also there's an article on ng saying if you're not using the dot (as in my example) you're doing something wrong. Has helped me a lot.

javascript: get contents of textarea, textContent vs. innerHTML vs. innerText

I am having trouble getting the contents of a textarea with js. I feel like I've done this many times before without problems but something is throwing it off or I have a mental block.
html
<textarea id="productdescript">test copy..asdfd</textarea><button value="Enter" onclick="addProduct()">
js
function addProduct() {
var descript = document.getElementById('productdescript').textContent;
alert(descript);
}
Firefox is the only browser I have currently.
When I use textContent, the alert box appears but it is blank.
When I use value, the alert box appears and says "Undefined"
When I use innerHTML, all the HTML appears including the tags.
Also, I understand that textContent only runs in FF and for cross browser compatibility you need to do something like innerText and textContent but textContent is not working in FF. There is no jquery on this app
What is the correct cross browser way to get contents of textarea! Thanks for any suggestions.
For textarea, you could only use .value in your scenario (I tested your given code and it works fine).
.
Also,
1) keep in mind that you call this function addProduct() ONLY after your element is mentioned in the code, otherwise it will be undefined.
2) there must not be another element with id as productdescript
3) there must not be a JS variable called productdescript
This are your code?
you write document.getElementByID.... and the "D" should be written lowercase "d"
document.getElementById('productdescript').textContent;

Onclick JavaScript not working properly in IE

Please excuse my ignorance I am not very familiar with JavaScript and have been tasked with repairing a bug by a developer no longer at the company.
The onclick works perfectly in FireFox, however in IE 7&8 (the only ones we test for), it appears to run through the onclick functions properly, then instead of the data being submitted to the form URL in goStep3(), it runs through every onclick on the page, with href="#" then finally submits with incorrect information as the variable has been overwritten 50 times.
view
EDIT:
When I run trackSponsor(62, 64265); goStep3(1896, 64265, 0); return false; in the Developer Tools in IE8 I get an error of returning false outside of a function....removing that it works just fine.
Is the line that I believe is causing the problems?
trackSponsor() is working properly and returns false
goStep3() is quite a large function however it works by retrieving values from 4 other functions within, assigning the values to a URL within theAction
It completes the function by EDIT:
var yr = $("#find-yr").attr('value');
var me = $("#find-me").attr('value');
var mo = $("#find-mo").attr('value');
var keywords = $("#find-keywords").attr('value');
var theAction = PATH_BASE+'find/step3/'+p_term+'/'+p_id+'/'+p_l_id+'/';
document.forms['FindForm'].action = theAction;
document.FindForm.submit();
return true;
I have tried returning false from this function, as well as changing the document.FindForm.submit() to the 'correct' syntax of document.forms['FindForm'].submit() and it still does not submit until running through all of the other onclick s on the page.
Thanks in advance!
Notes:
jQuery is being used as well.
Javascript is not throwing any errors.
This works fine in FireFox
I can see it going through all of the other functions in the other onclicks using Developer Tools and stepping through the page it does not submit the results of goStep3 until it has gone through all of the other onclick functions on the page.
"posting my earlier comment as an answer"
I see a lot of jQuery being used with attribute selectors, so plz check the code against those.
EDIT:
I noticed ur unfamiliar with JavaScript... so in-case u didnt know, a jQuery selector, will select all tags matching a certain "selector-filter" and perform a certain action on them... so if there is a selector that selects all A tags with a href attribute (or maybe another common attribute between them...) then that would be the cause of your problem.
EDIT: -after you posted your answer -
glad you found an answer...
though it is alittle werid,
cause according to your question it goes through "every element with href="#" ...
However According to msdn, Event bubbling simply passes these unhandled events to the parent element for handling. not through "similar" tags :)
oh well..nothing is logical when it comes to IE
I would start by removing "return false;" from the onClick event since it really isn't doing anything.
try changing
href="#"
with
href='javascript:void(0)' .
I can't say for sure where things are going wrong, but I discourage using a form's name attribute to reference it like you have done here:
document.forms['FindForm'].action = theAction;
document.FindForm.submit();
Why not try the following jQuery:
$("form:FindForm").action = theAction;
$("form:FindForm").trigger("submit");
You should also check that $("form:FindForm") is indeed referencing the desired form element.
The problem was called because of how IE uses the bubble! Thanks all for your help, I have included the code solution to be placed in goStep3().
var browserName = navigator.appName;
if (browserName == "Microsoft Internet Explorer") {
window.event.cancelBubble = true;
}

Categories