I have implemented ajax on my webpage to dynamically change the content of a main div when different fields in the navigation bar are clicked. However, I am encountering a problem with form validation using JavaScript on elements loaded via ajax. For instance, when I load a checkbox and a submit button through ajax and then try to check the checkbox and submit the form, the validation does not work as expected.
Interestingly, when I perform the same form validation (checkbox+submit) without ajax, it works perfectly fine.
Am I missing something logical in this scenario?
Thank you!
Edit: Apologies for not providing the code. Here is my ajax code:
function loadWholePage(url)
{
var y = document.getElementById("storage");
//var x = document.getElementById("displayed");
var x = document.getElementById("content");
loadHTML(url, processHTML, x, y);
}
function loadHTML(url, fun, storage, param)
{
var xhr = createXHR();
xhr.onreadystatechange=function()
{
if(xhr.readyState == 4) // The request is complete
{
//if(xhr.status == 200)
{
storage.innerHTML = getBody(xhr.responseText);
fun( storage, param );
}
}
};
xhr.open("GET", url, true);
xhr.send(null);
}
function getBody(content)
{
test = content.toLowerCase(); // to eliminate case sensitivity
var x = test.indexOf("<body");
if(x == -1) return "";
x = test.indexOf(">", x);
if(x == -1) return "";
var y = test.lastIndexOf("</body>");
if(y == -1) y = test.lastIndexOf("</html>");
if(y == -1) y = content.length; // If no HTML then just grab everything till end
return content.slice(x + 1, y);
}
The HTML file I load with ajax:
<html>
<body>
<form>
<input type="checkbox" name="values" value="" id="chk3" />
<select name="select3" class="test" style="width:7em;" id="select3">
<option VALUE="">0-100</option>
<option VALUE="/tags/">100-200</option>
<option VALUE="/"> 200-300</option>
<option VALUE="/"> 300-400</option>
<option VALUE="/"> 400-500</option>
</select>
<input type="button" class="submit" id="testbutton" style="width:12em;" value="submit" onClick="testIt();">
</form>
</body>
</html>
I load it using:
<li onClick='setSelectedListElement(this);'>
<a onclick="loadWholePage('test.html');">TEST
</a>
</li>
And the simple script to check if the checkbox is checked:
<script type="text/javascript">
function testIt(){
var x=document.getElementById("chk3").checked;
alert(x);
}
</script>