I've been pulling my hairs trying to get this to work with jQuery's innerhtml, Although some people told me its not recommended to use, its for a small part of a page so I dont think it will affect site speed and such.
Heres the snippet ive been using:
$('input[name|="yesno1"]').change(function () {
if ($(this).val() == 'YES') {
$("#div1").hide();
$("#div2").show();
} else {
$("#div2").hide();
$("#div1").show();
}
});
And The code:
function replace3() {
document.getElementById('number').innerHTML = "<b>3. </b>";
document.getElementById('question').innerHTML = "<b>Would You Like To Try It? </b>";
document.getElementById('answer1').innerHTML = "<input type=\"radio\" name=\"yesno1\" id=\"dl\" value=\"YES\" /> Yes";
document.getElementById('answer2').innerHTML = "<input type=\"radio\" name=\"yesno1\" id=\"dl\" value=\"NO\" /> No";
document.getElementById('nextbutton').innerHTML = "<div id=\"div1\">Default Link</div> <div id=\"div2\">No Answer Link</div>";
}
Im trying to set the radio button YES/ NO with a different link, I tried using the above on a standard html page and it works, but it fails here when its using within the innerHTML tags.
Your options:
(recommended) You could bind that click
event on
on the parent element. This is the best method because irrespective of the number of input
inside its the parent the click
is always attached to the parent and that makes it DRY and more performant.
$("Parent of input").on('click', 'input[name|="yesno1"]', function(){
if ($(this).val() == 'YES') {
$("#div1").hide();
$("#div2").show();
} else {
$("#div2").hide();
$("#div1").show();
}
});
You could place your event handler with $('input[name|="yesno1"]')
as selector as the last statement inside the replace3()
method. At that time your input
elements would be in DOM and so you can bind the click handler to the element.
function replace3() {
document.getElementById('number').innerHTML = "<b>3. </b>";
document.getElementById('question').innerHTML = "<b>Would You Like To Try It? </b>";
document.getElementById('answer1').innerHTML = "<input type=\"radio\" name=\"yesno1\" id=\"dl\" value=\"YES\" /> Yes";
document.getElementById('answer2').innerHTML = "<input type=\"radio\" name=\"yesno1\" id=\"dl\" value=\"NO\" /> No";
document.getElementById('nextbutton').innerHTML = "<div id=\"div1\">Default Link</div> <div id=\"div2\">No Answer Link</div>";
//your change event here
$('input[name|="yesno1"]').change(function () {
if ($(this).val() == 'YES') {
$("#div1").hide();
$("#div2").show();
} else {
$("#div2").hide();
$("#div1").show();
}
});
}
You could bind this element (input
) to the document
object which always exists, even before jquery is loaded.
$(document).on('change', 'input[name|="yesno1"]', function() {
if(this.value =='YES') {
$("#div1").hide();
$("#div2").show();
} else {
$("#div2").hide();
$("#div1").show();
}
});