问题
i have a problem in creating radio buttons dynamically, i have a text box and a button, i asked the user to input a value in the text field then i retrieve the text box value and use it to create a radio button when he press a button, i tried this code in javaScript but it doesn't create a radio button on clicking the specified button:
<script type="text/javascript" >
function createRadioElement(value, checked) {
var radioHtml = '<input type="radio" value="' + value + '"';
if ( checked ) {
radioHtml += ' checked="checked"';
}
radioHtml += '/>';
var radioFragment = document.createElement('div');
radioFragment.innerHTML = radioHtml;
return radioFragment.firstChild;
}
$( '#admin' ).live( 'pageinit',function(event){
$( "#AddButton" ).bind( "click", function(event, ui) {
var x=document.getElementById('option').value
createRadioElement(x, checked);
});
});
</script>
`
回答1:
Try the following for the creation of a radio input:
function createRadioElement(elem, value, checked) {
var input = document.createElement('input');
input.type = 'radio';
input.value = value;
if (checked) {
input.checked = 'checked';
}
elem.parentNode.insertBefore(input, elem.nextSibling);
}
JS Fiddle demo.
References:
- createElement().
- insertBefore().
- parentNode.
回答2:
Here are the problems as I can see them:
- In your
#AddButton
click function, you pass a variablechecked
which does not exist. - You don't pass the element returned from
createRadioElement
to anything that will insert it into the DOM
I fixed those by basically changing your #AddButton
click function to the following:
$("#AddButton").bind("click", function(event) {
var x = document.getElementById('option').value,
$ra = $('#RadioArea');
$ra.html(createRadioElement(x, true));
});
You'll probably want to change this so it appends the radio button to the end of whatever your #RadioArea
element is instead of replacing the contents completely.
See demo
来源:https://stackoverflow.com/questions/9574167/how-to-create-radio-buttons-dynamically