I could use some help with this code.
I have created a fiddle to show the issue - http://jsfiddle.net/r4hqC/
I am trying to read the value of 2 radio groups and then send their values via a GET request (Ajax).
The code works except on the first radio click where the value of the radio is returned as undefined until the radio is changed. This happens on both groups.
Here is the code:
function jsdatabaseMatch()
{
$(document).ready(function(){
$(".form1").change(function () {window.vala = $('.form1:checked').val(); //Radio group 1
$(".form2").change(function () {window.valb = $('.form2:checked').val(); //Radio group 2
});
});
});
alert(window.vala); //Radio 1 contains..
alert(window.valb); //Radio 2 contains..
var getr = window.vala + "&pricerange=" + window.valb; //GET request
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","showcase.php?yes="+getr,false); //Prepare GET Request
xmlhttp.send();
document.getElementById("pricecompare").innerHTML=xmlhttp.responseText;
}
I have tried replacing the .change
with .click
the result is the same.
Thanks in advance.
SOLVED BY tymeJV
onclick
triggers from HTML which execute jsdatabaseMatch
.function jsdatabaseMatch()
in jQuery on radio .change
event.Here it is:
$(document).ready(function(){
$(".form1").change(function () {window.vala = this.value;}); //Radio group 1
$(".form1").change(jsdatabaseMatch); //Radio group 1
$(".form2").change(function () {window.valb = this.value;}); //Radio group 2
$(".form2").change(jsdatabaseMatch); //Radio group 2
});
function jsdatabaseMatch()
{
alert(window.vala);
alert(window.valb);
var getr = window.vala + "&pricerange=" + window.valb; //GET request
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","showcase.php?yes="+getr,false); //Prepare GET Request
xmlhttp.send();
document.getElementById("pricecompare").innerHTML=xmlhttp.responseText;
}
You need to close your change events when they are done. Also, assigned the value using the this
selector.
$(".form1").change(function() {
window.vala = this.value; //Radio group
}); // <---You can always add .change() right here to fire the event on DOM ready.
$(".form2").change(function () {
window.valb = this.value; //Radio group 2
});