javascript - Get properties of dynamically-defined, checked radio button -
there load of similar questions asked still can't figure out.
i have set of radio buttons, dynamically defined (both number of buttons , labels them change).
i need label , number associated checked radio button. how can this?
i made js fiddle showing that, when click on button, checked radio "undefined". here's code:
$(document).ready(function() { var myarray = ["never", "sometimes", "always"]; (i = 0; < myarray.length; i++) { addradiobutton("radio", + 1, label = myarray[i]); } function addradiobutton(type, number, text) { var label = document.createelement("label"); var element = document.createelement("input"); //assign different attributes element. element.setattribute("type", type); element.setattribute("value", number); element.setattribute("name", type); element.setattribute("id", "radio_" + number); label.appendchild(element); label.innerhtml += text; var foo = document.getelementbyid("questionanswerradio"); //append element in page (in span). foo.appendchild(label); } $("#questionanswerradio").click(function(event) { var currentslideresult = 0; currentslideresult.answerchosen = $("#questionanswerradio :radio:checked + label").text(); currentslideresult.numberchosen = $("#questionanswerradio :radio:checked + value").text(); alert(currentslideresult.answerchosen) }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="questionanswerradio"></div>
- use
$(this)
inside event handler value , label of clicked radio button - assign empty object variable
currentslideresult
- to label associated radio button use
$(this).parent().text()
- use
change
event on radio instead ofclick
- you can pass array element directly function, no need assign variable , pass variable
- to create new element , append element can use jquery
$(document).ready(function() { var myarray = ["never", "sometimes", "always"]; (i = 0; < myarray.length; i++) { addradiobutton("radio", + 1, myarray[i]); } function addradiobutton(type, number, text) { var input = $('<input />') .attr({ type: type, value: number, name: type, id: 'radio_' + number }); $('<label />') .text(text) .prepend(input) .appendto('#questionanswerradio'); } $("#questionanswerradio").on('change', ':radio', function(event) { var currentslideresult = {}; currentslideresult.answerchosen = $(this).parent().text(); currentslideresult.numberchosen = $(this).val(); alert(currentslideresult.answerchosen); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="questionanswerradio"></div>
Comments
Post a Comment