-
Feb 9th, 2017, 10:53 AM
#1
Thread Starter
New Member
need help to fill input radio field with data from xml field with javascript
INDEX.HTML
<input name="sex" id="radio" type="radio" value="">
<input name="sex" id="radio" type="radio" value="">
<input name="sex" id="radio" type="radio" value="">
<input name="sex" id="radio" type="radio" value="">
XML FILE
<question id="Q004">
<type>radio</type>
<title>1.- Who is the actual president of the USA? :</title>
<option>a) barack obama</option>
<option>b) Bill Clinton</option>
<option>c) Hillary Clinton</option>
<option>d) Donald trump</option>
<answer>4</answer>
</question>
I need help to read values from a question in a xml file and insert answers in the values of the radio buttons using dom with javascript, i am learning to do a test with xml,js,css and javascript if u can give me and advice to use a book to get started with quiz or similar. Thanks a lot
-
Feb 13th, 2017, 03:22 PM
#2
Re: need help to fill input radio field with data from xml field with javascript
Even though you may have a value attribute for an input element, whenever the type is Radio nothing would actually come up. You will need to have a separate element to display the options. Take a look at this exaple:
Code:
<!-- html -->
<form>
<legend id="question"></legend>
<label for="1">
<input id="1" name="sex" type="radio" />
</label>
<label for="2">
<input id="2" name="sex" type="radio" />
</label>
<label for="3">
<input id="3" name="sex" type="radio" />
</label>
<label for="4">
<input id="4" name="sex" type="radio" />
</label>
<input data-correct="" type="submit" value="Submit" />
</form>
/* CSS */
label {display: block;}
In terms of actually parsing your XML, I would use JQuery for this. Take a look at this example:
Code:
$(document).ready(function(){
var xml = "<question id='Q004'><type>radio</type><title>1.- Who is the actual president of the USA? :</title><option>a) barack obama</option><option>b) Bill Clinton</option><option>c) Hillary Clinton</option><option>d) Donald trump</option><answer>4</answer></question>";
loadQuestion();
function loadQuestion() {
//Set the text of the <legend> to the <title>
$('form:first legend').text($(xml).find("title").text());
//Get all <option> elements, but only return the text
var options = $(xml).children('option').map(function() {
return $(this).text();
}).get();
//Set the <input type="radio">'s respective text
$('form:first label:first').append(options[0]);
$('form:first label:nth-child(3)').append(options[1]);
$('form:first label:nth-child(4)').append(options[2]);
$('form:first label:last').append(options[3]);
//Set the data-correct attribute of the <input type="submit">
$('form:first input[type=submit]:first').attr('data-correct', $(xml).find("answer").text());
};
$('form:first').on('submit', function() {
//Get the selected radio button's index
var attempt = $("form:first input:checked").first().attr('id');
var correct = $("form:first input[type=submit]").first().attr('data-correct');
if (attempt == correct) {
alert('correct');
} else {
alert('incorrect');
};
});
});
Fiddle: http://codepen.io/anon/pen/EZrPNR
-
Feb 13th, 2017, 03:46 PM
#3
Thread Starter
New Member
Re: need help to fill input radio field with data from xml field with javascript
thanks a lot i am doing a high profesional formation grade, and i am doing a quiz in html css xml and js,
i need two make 10 question, 2 question of each type of input form types, and store the answer and give the final score, but i fill stupid and frustated because i am not able to do it for my self, thanks a lot, may you help me by skype i am from spain. may you give me online classes in the evening spanish time or tell me which is your country, thanks a lot again
-
Feb 13th, 2017, 03:49 PM
#4
Thread Starter
New Member
Re: need help to fill input radio field with data from xml field with javascript
thanks a lot i have more questions, because i have to make a quiz in ccs,html,js,xml it is hard for me because it is my first time programming.
I see you insert the question in js, but is posible to read 10 questions from a xml and fill the html div.
for example i have this xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE questions SYSTEM "questions.dtd">
<questions>
<question id="UAP_HE1">
<type>radio</type>
<title>1.- ࠑuiꮠes el actual presidente de los Estados Unidos? :</title>
<option>a) barack obama</option>
<option>b) Bill Clinton</option>
<option>c) Hillary Clinton</option>
<option>d) Donald trump</option>
<answer>4</answer>
</question>
<question id="UAP_HE2">
<type>checkbox</type>
<title>2.- ࠑuiꮠcanta Booma Yee?</title>
<option>a) Geo Da Silva@Jack MAzzoni</option>
<option>b) Bustamante</option>
<option>c) Shakira</option>
<answer>1</answer>
</question>
<question id="UAP_HE3">
<type>text</type>
<title>3.- ࠑuien escribio Parque Jurco?</title>
<answer>MICHAEL CRICHTON</answer>
</question>
<question id="UAP_HE4">
<type>multiple</type>
<title>4.-ࠃuales son mis apellidos?</title>
<option>a) Segu�option>
<option>b) Pedrosa</option>
<option>c) Brey</option>
<option>d) Clinton</option>
<answer>0</answer>
<answer>1</answer>
</question>
<question id="UAP_HE5">
<type>radio</type>
<title>5.- ࠃuando finalizo la Guerra Civil Espa�� :</title>
<option>a) 26 de junio de 1936</option>
<option>b) 18 de julio de 1936</option>
<option>c) 1 de abril de 1939</option>
<option>d)20 de noviembre de 1975</option>
<answer>3</answer>
</question>
<question id="UAP_HE6">
<type>select</type>
<title>6.- ࠃuando murio Francisco Franco?</title>
<option>a) 7 de mayo de 1945</option>
<option>b) 20 de noviembre de 1975</option>
<option>c) 14 de abril de 1912</option>
<option>d) 26 de junio de 1977</option>
<answer>2</answer>
</question>
<question id="UAP_HE7">
<type>multiple</type>
<title>7.- ࠑu顩diomas oficiales se hablan en Mallorca?</title>
<option>a) Mallorquin</option>
<option>b) Espa��/option>
<option>c) Ingles</option>
<option>d) Aleman</option>
<answer>1</answer>
<answer>2</answer>
</question>
<question id="UAP_HE8">
<type>checkbox</type>
<title>8.- ࠅn que a��e llego a la luna?</title>
<option>a) 20 de julio 1969</option>
<option>b) 16 de julio 1969</option>
<option>c) 06 de julio 1965</option>
<answer>1</answer>
</question>
<question id="UAP_HE9">
<type>select</type>
<title>9.- ࠅn a��e creo Facebook?</title>
<option>a) 04 de diciembre de 2010</option>
<option>b) 10 de enero de 2000</option>
<option>c) 4 de febrero de 2004</option>
<option>d) 26 de abril de 1999</option>
<answer>3</answer>
</question>
<question id="UAP_HE10">
<type>text</type>
<title>10.- ࠑuiꮠes el director ejecutio de Facebook?</title>
<answer> Mark Zuckerberg</answer>
</question>
</questions>
and i have this js.
var formElement=null;
var numeroSecreto=null;
var respuestaSelect=null;
var respuestasCheckbox = [];
var nota = 0; //nota de la prueba sobre 3 puntos (hay 3 preguntas)
//****************************************************************************************************
//Después de cargar la página (onload) se definen los eventos sobre los elementos entre otras acciones.
window.onload = function(){
//CORREGIR al apretar el botón
formElement=document.getElementById('myform');
formElement.onsubmit=function(){
borrarCorreccion();
corregirNumber();
corregirSelect();
corregirCheckbox();
presentarNota();
return false;
}
//LEER XML de xml/preguntas.xml
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
gestionarXml(this);
}
};
xhttp.open("GET", "xml/preguntas.xml", true);
xhttp.send();
}
//****************************************************************************************************
// Recuperamos los datos del fichero XML xml/preguntas.xml
// xmlDOC es el documento leido XML.
function gestionarXml(dadesXml){
var xmlDoc = dadesXml.responseXML; //Parse XML to xmlDoc
//NUMBER
//Recuperamos el tÃ*tulo y la respuesta correcta de Input, guardamos el número secreto
var tituloInput=xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
ponerDatosInputHtml(tituloInput);
numeroSecreto=parseInt(xmlDoc.getElementsByTagName("answer")[0].childNodes[0].nodeValue);
//SELECT
//Recuperamos el tÃ*tulo y las opciones, guardamos la respuesta correcta
var tituloSelect=xmlDoc.getElementsByTagName("title")[1].childNodes[0].nodeValue;
var opcionesSelect = [];
var nopt = xmlDoc.getElementById("profe_002").getElementsByTagName('option').length;
for (i = 0; i < nopt; i++) {
opcionesSelect[i] = xmlDoc.getElementById("profe_002").getElementsByTagName('option')[i].childNodes[0].nodeValue;
}
ponerDatosSelectHtml(tituloSelect,opcionesSelect);
respuestaSelect=parseInt(xmlDoc.getElementsByTagName("answer")[1].childNodes[0].nodeValue);
//CHECKBOX
//Recuperamos el tÃ*tulo y las opciones, guardamos las respuestas correctas
var tituloCheckbox = xmlDoc.getElementsByTagName("title")[2].childNodes[0].nodeValue;
var opcionesCheckbox = [];
var nopt = xmlDoc.getElementById("profe_003").getElementsByTagName('option').length;
for (i = 0; i < nopt; i++) {
opcionesCheckbox[i]=xmlDoc.getElementById("profe_003").getElementsByTagName('option')[i].childNodes[0].nodeValue;
}
ponerDatosCheckboxHtml(tituloCheckbox,opcionesCheckbox);
var nres = xmlDoc.getElementById("profe_003").getElementsByTagName('answer').length;
for (i = 0; i < nres; i++) {
respuestasCheckbox[i]=xmlDoc.getElementById("profe_003").getElementsByTagName("answer")[i].childNodes[0].nodeValue;
}
}
//****************************************************************************************************
//implementación de la corrección
function corregirNumber(){
var s=formElement.elements[0].value;
if (s==numeroSecreto) {
darRespuestaHtml("P1: Exacto!");
nota +=1;
}
else {
if (s>numeroSecreto) darRespuestaHtml("P1: Te has pasado");
else darRespuestaHtml("P1: Te has quedado corto");
}
}
function corregirSelect(){
var sel = formElement.elements[1];
if (sel.selectedIndex==respuestaSelect) {
darRespuestaHtml("P2: Correcto");
nota +=1;
}
else darRespuestaHtml("P2: Incorrecto");
}
function corregirCheckbox(){
var f=document.getElementById('myform');
var escorrecta = [];
for (i = 0; i < f.color.length; i++) {
if (f.color[i].checked) {
escorrecta[i]=false;
for (j = 0; j < respuestasCheckbox.length; j++) {
if (i==respuestasCheckbox[j]) escorrecta[i]=true;
}
}
}
for (i = 0; i < f.color.length; i++) {
if (f.color[i].checked) {
if (escorrecta[i]) {
nota +=1.0/respuestasCheckbox.length; //dividido por el número de respuestas correctas
darRespuestaHtml("P3: "+i+" correcta");
} else {
nota -=1.0/respuestasCheckbox.length; //dividido por el número de respuestas correctas
darRespuestaHtml("P3: "+i+" incorrecta");
}
}
}
}
//****************************************************************************************************
// poner los datos recibios en el HTML
function ponerDatosInputHtml(t){
document.getElementById("tituloInput").innerHTML = t;
}
function ponerDatosSelectHtml(t,opt){
document.getElementById("tituloSelect").innerHTML=t;
var select = document.getElementsByTagName("select")[0];
for (i = 0; i < opt.length; i++) {
var option = document.createElement("option");
option.text = opt[i];
option.value=i+1;
select.options.add(option);
}
}
function ponerDatosCheckboxHtml(t,opt){
var checkboxContainer=document.getElementById('checkboxDiv');
var h3 = document.createElement("h3");
h3.innerHTML = t;
checkboxContainer.appendChild(h3);
for (i = 0; i < opt.length; i++) {
var input = document.createElement("input");
var label = document.createElement("label");
label.innerHTML=opt[i];
label.setAttribute("for", "color_"+i);
input.type="checkbox";
input.name="color";
input.id="color_"+i;;
checkboxContainer.appendChild(input);
checkboxContainer.appendChild(label);
}
}
//****************************************************************************************************
//Gestionar la presentación de las respuestas
function darRespuestaHtml(r){
var resDiv=document.getElementById('resultadosDiv');
var p = document.createElement("p");
var node = document.createTextNode(r);
p.appendChild(node);
resDiv.appendChild(p);
}
function presentarNota(){
darRespuestaHtml("Nota: "+nota+" puntos sobre 3");
}
function borrarCorreccion(){
var resDiv=document.getElementById('resultadosDiv');
resDiv.innerHTML = "";
nota=0.0;
}
and this index.html
<!DOCTYPE html>
<html>
<head>
<script src='js/questions.js'></script>
</head>
<body>
<form id='myform'>
<h3 id='tituloInput'></h3>
<input id='num' type='number'>
<br><br>
<h3 id='tituloSelect'></h3>
<select id='sel'>
</select>
<br><br>
<div id='checkboxDiv'></div>
<br><br>
<input type='submit' value='Corregir'>
</form>
<div id='resultadosDiv'></div>
</body>
</html>
I dont watt you to do my Jobs please te achaca me
Last edited by psegui; Feb 13th, 2017 at 05:21 PM.
-
Feb 13th, 2017, 05:58 PM
#5
Re: need help to fill input radio field with data from xml field with javascript
Try to do this instead:
Code:
<!-- html -->
<form></form>
/* CSS */
label {display: block;}
//JQuery
$(function() {
var xml = '<questions> <question id="UAP_HE1"> <type>radio</type> <title>1.- ࠑuiꮠes el actual presidente de los Estados Unidos? :</title> <option>a) barack obama</option> <option>b) Bill Clinton</option> <option>c) Hillary Clinton</option> <option>d) Donald trump</option> <answer>4</answer> </question> <question id="UAP_HE2"> <type>checkbox</type> <title>2.- ࠑuiꮠcanta Booma Yee?</title> <option>a) Geo Da Silva@Jack MAzzoni</option> <option>b) Bustamante</option> <option>c) Shakira</option> <answer>1</answer> </question> <question id="UAP_HE3"> <type>text</type> <title>3.- ࠑuien escribio Parque Jurco?</title> <answer>MICHAEL CRICHTON</answer> </question> <question id="UAP_HE4"> <type>checkbox</type> <title>4.-ࠃuales son mis apellidos?</title> <option>a) Segu�option> <option>b) Pedrosa</option> <option>c) Brey</option> <option>d) Clinton</option> <answer>0</answer> <answer>1</answer> </question> <question id="UAP_HE5"> <type>radio</type> <title>5.- ࠃuando finalizo la Guerra Civil Espa�� :</title> <option>a) 26 de junio de 1936</option> <option>b) 18 de julio de 1936</option> <option>c) 1 de abril de 1939</option> <option>d)20 de noviembre de 1975</option> <answer>3</answer> </question> <question id="UAP_HE6"> <type>select</type> <title>6.- ࠃuando murio Francisco Franco?</title> <option>a) 7 de mayo de 1945</option> <option>b) 20 de noviembre de 1975</option> <option>c) 14 de abril de 1912</option> <option>d) 26 de junio de 1977</option> <answer>2</answer> </question> <question id="UAP_HE7"> <type>checkbox</type> <title>7.- ࠑu顩diomas oficiales se hablan en Mallorca?</title> <option>a) Mallorquin</option> <option>b) Espa��/option> <option>c) Ingles</option> <option>d) Aleman</option> <answer>1</answer> <answer>2</answer> </question> <question id="UAP_HE8"> <type>checkbox</type> <title>8.- ࠅn que a��e llego a la luna?</title> <option>a) 20 de julio 1969</option> <option>b) 16 de julio 1969</option> <option>c) 06 de julio 1965</option> <answer>1</answer> </question> <question id="UAP_HE9"> <type>select</type> <title>9.- ࠅn a��e creo Facebook?</title> <option>a) 04 de diciembre de 2010</option> <option>b) 10 de enero de 2000</option> <option>c) 4 de febrero de 2004</option> <option>d) 26 de abril de 1999</option> <answer>3</answer> </question> <question id="UAP_HE10"> <type>text</type> <title>10.- ࠑuiꮠes el director ejecutio de Facebook?</title> <answer> Mark Zuckerberg</answer> </question> </questions>';
createForm();
function createForm() {
//iterate through each <question>
$(xml).find('question').each(function(i) {
//create a <fieldset>
var code = '<fieldset>';
//create a <legend>
code += '<legend>' + $(this).find('title').first().text() + '</legend>';
//get the input type
var type = $(this).find('type').first().text();
if(type = 'checkbox' || type == 'radio') {
var type = $(this).find('type').first().text();
//create the input that is not a <select> or text
$(this).find('option').each(function(j) {
//create each <input>
code += '<label><input name="question' + i + '" type="' + type + '" />' + $(this).text() + '</label>';
});
} else if(type != 'text') {
//create the select input
code += '<select>';
$(this).find('option').each(function(j) {
//create each <option>
code += '<option>' + $(this).text() + '</option>';
});
//finish the <select> tag
code += '</select>'
}
if(type == 'text') {
//create the text input
code += '<input type="text" />';
}
//finish the <fieldset> tag
code += '</fieldset>';
//Append the code
$('form:first').append(code);
});
//create the submit button
$('form:first').append('<input type="submit" value="Submit" />')
}
});
Fiddle: http://codepen.io/anon/pen/pRGEdW
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|