Why Isn't Javascript Changing A Variable With Onchange?
Solution 1:
As commented above, the property name is "onchange", not "onChange". Javascript is case-sensitive, so those two are definitely different.
Also, the code you posted looks like it's missing a }
somewhere. As it is, everything's inside the changeUp
function. Which, coincidentally, never closes before that ending script tag.
However, there's something else going on here. This line in your markup:
<select name="uname"id="useruname" onChange="changeUp();">
Gets completely wiped out by this line in your code:
document.getElementById("useruname").onChange = function() {
Here's how I'd fix it up. First, the javascript:
functioncreateAjax() {
if(window.XMLHttpRequest)
returnnewXMLHttpRequest();
elsereturnnewActiveXObject("Microsoft.XMLHTTP");
}
functionupdateAddUser(username) {
var ajax = createAjax();
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
var json = ajax.responseText;
var fields = JSON.parse(json);
Object.keys(fields).forEach(function (name) {
var input = document.getElementsByName(name);
input.value = fields[name];
});
}
}
ajax.open("GET", "ajaxuseradd.psp?uname=" + username, true);
ajax.send();
}
Then you can just change the HTML select
tag to:
<select name="uname"id="useruname" onchange="updateAddUser(this.value)">
Having said all that, I would strongly urge you try something like jQuery. It would make the javascript code as trivial as:
$('#username').change(function(){
$.get('ajaxuseradd.php', {uname:$(this).val()}, function(data, status, xhr) {
$.each(data, function(key,value) {
$('#'+key).val(value);
});
}, 'json');
});
Yeah, that's really terse, I know. More expressively, it could be written like this:
$('#username').change(function() {
var userName = $(this).val();
$.ajax({
type: 'GET',
url: 'ajaxuseradd.php',
data: {
uname: userName
},
success: function(data, status, xhr) {
$.each(data, function(key, value) {
$('#' + key).val(value);
});
},
dataType: 'json'
})
});
Solution 2:
You are missing a brace. Try running jslint on your code.
Secondly, You are trying to assign a function to the onChange event inside the method changeUp. Whereas changeUp is again the same method invoked in the first place. May be causing recursion.
Thanks, RR
Post a Comment for "Why Isn't Javascript Changing A Variable With Onchange?"