Todavía estoy aprendiendo JS y estoy tratando de crear una validación de formulario. Me gustaría pintar el elemento principal de mi botón de opción <p> si el botón de opción no es válido.
Encontré una propiedad para ubicar el parent de mi HTMLElement : element.parentElement
Sin embargo, no puedo seleccionar el elemento <p> usando radio.parentElement . Aquí está mi código simplificado:
window.onload = Init; function Init() { var formElement = document.forms.myform; //myform var radio = formElement.radioName; formElement.onsubmit = ProcessForm; var isFormValid = () => { //validate if form is valid if not -> paint <p> red if ( radio.value === null || radio.value === "" ) { console.log(radio.parentElement); //(this is undefined. Why?) radio.parentElement.backgroundColor = "red"; //(this does not work because it is undefined) //Error:doubt.js:13 Uncaught TypeError: Cannot set properties of undefined (setting 'backgroundColor') return false; } return true; }; function ProcessForm(event) { event.preventDefault(); if (isFormValid()) { //do stuff } else { //do nothing } } } <!DOCTYPE html> <html> <head> <script src="./doubt.js"></script> </head> <body> <form name="myform" action="#" method="POST"> <p id="caption_project"> Project Selection <br /> <input type="radio" name="radioName" id="id1" value="1" /> <label for="id1">1</label> <br /> <input type="radio" name="radioName" id="id2" value="2" /> <label for="id2">2</label> <br /> </p> <input id="btnSubmit" type="submit" /> </form> </body> </html> ¿Cómo puedo seleccionar el elemento <p> sin cambiar el documento HTML?
Tiene más de una entrada de radio denominada radioName , por lo que formElement.radioName no es la entrada; es la colección de entradas. Puede obtener la enésima entrada especificando su índice, como formElement.radioName[0] .
var formElement = document.forms.myform; //myform var radio = formElement.radioName; // first radio console.log(radio[0].parentElement); <form name="myform" action="#" method="POST"> <p id="caption_project"> Project Selection <br /> <input type="radio" name="radioName" id="id1" value="1" /> <label for="id1">1</label> <br /> <input type="radio" name="radioName" id="id2" value="2" /> <label for="id2">2</label> <br /> </p> <input id="btnSubmit" type="submit" /> </form> También puede simplemente consultar la p a través de querySelector :
// query the document for the id: console.log(document.querySelector('#caption_project')); // or the first p under the form: console.log(document.forms.myform.querySelector('p')); <form name="myform" action="#" method="POST"> <p id="caption_project"> Project Selection <br /> <input type="radio" name="radioName" id="id1" value="1" /> <label for="id1">1</label> <br /> <input type="radio" name="radioName" id="id2" value="2" /> <label for="id2">2</label> <br /> </p> <input id="btnSubmit" type="submit" /> </form>