简体   繁体   中英

Change the colour of a radio button with Javascript not working via for loop

I have a form:

<form id='form' name='form' action='#' method='get'>
        <input type="RADIO" name="test" value="1">
 Yes
        <br>
        <input type="RADIO" name="test" value="2">
 No

</form>

and this Javascript:

var amount= document.form.test.length;
var radioButtons = document.form.test;

for (var i = 0; i < amount; i++) {
    var btn = document.createElement("button");
    var t = document.createTextNode("dsiable this button");
    btn.appendChild(t);
    btn.setAttribute.onclick = function () {
        radioButtons[i].disabled = true;
    };    
    document.form.test[i].parentNode.insertBefore(btn, document.form.test[i].nextSibling);
}

This creates the button with the text 'disabled this button', but when clicking it, nothing happens, and no error shows in the console. What am I doing wrong?

If I add a console.log('test') in the setAttribute part, it doesn't show up, so that part of the code never runs - why is this?

I also tried btn.setAttribute("onClick", "disable(radioButtons[i])") with the function

function disable(radioButtons) { //radioButtons.disabled = red; }

but this produces the can't change null of undefined error, which I do not understand.

What am I doing wrong? Changing the html is not an option.

Try using -

btn.onclick = function () {
    radioButtons[i].style.color = red;
};

To style radio inputs statically

This is how you HTML should look like this:

<input class="radio1" type="radio" name="any" id="r1" value="yes" onclick="which(this.value)"><label for="r1" >YES</label> 
<input class="radio1" type="radio" name="any"  id="r2"  value="no" onclick="which(this.value)" checked><label for="r2" >NO</label> </h2> 

This is how your CSS should look like

input[type=radio] {
display: none;
}

input[type=radio] + label::before {
content: '';
display: inline-block;
border: 2px solid white;
border-radius: 50%;
margin: 0 0.5em;
}

input[type=radio]:checked + label::before {
background-color: #9F5BA4;
}

.radio1 + label::before {
width: 1em;
height: 1em;
}

Now you can do your JQuery selection and change Border color and background color

to add an event listener to the button, use

btn.addEventListener('click', function() {
   // some code
});

I'd suggest the following, assigning the click-handlers to the ancestor <form> element:

 function disableRadiosByButton(){ // get all the radio inputs with the name of 'test': var radios = document.querySelectorAll('input[type=radio][name=test]'), // create a <button> element: button = document.createElement('button'), // create the textNode for that <button> element: text = document.createTextNode('disable the following input?'), // initialise a variable for use, later: tempButton; // add the textNode to the <button>: button.appendChild(text); // set the type of the <button> to 'button': button.type = 'button'; // add the 'disable' class to the element (for styling and filtering): button.classList.add('disable'); // get the ancestor <form> element, add a click-handling function: document.getElementById('form').addEventListener('click', function (e){ // 'e' is the automagically-passed in Event-object, // e.target is the element upon which the detected event ('click') was first triggered: var target = e.target; // if the target's lowercased tagName is 'button' and it has a class of 'disable': if (target.tagName.toLowerCase() === 'button' && target.classList.contains('disable')) { // prevent any default events from being triggered (form-submission being one // possibility): e.preventDefault(); // disabling the clicked-element's nextElementSibling: target.nextElementSibling.disabled = true; } }); // iterating over the array-like NodeList of radio-inputs: Array.prototype.forEach.call(radios, function (radio) { // 'radio' is the current Node over which the forEach is iterating; // cloning the created-<button> (cheaper than re-creating one): tempButton = button.cloneNode(true); // inserting the newly-cloned <button> before the relevant radio-input: radio.parentNode.insertBefore(tempButton, radio); }); } // calling the function: disableRadiosByButton(); 
 <form id='form' name='form' action='#' method='get'> <input type="RADIO" name="test" value="1" />Yes <br> <input type="RADIO" name="test" value="2" />No </form> 

Or, instead, to toggle the radio-inputs:

 // source: DOM node, the input to be disabled by the created <button>, // text: String, the text of the created <button> element. function addButtonBefore(source, text) { var button = document.createElement('button'), text = document.createTextNode(text); button.appendChild(text); button.addEventListener('click', function(e) { e.preventDefault(); // caching the current disabled-state (Boolean, true/false): var state = source.disabled; // inverting the current state, true becomes false, and vice-versa: source.disabled = !state; }); source.parentNode.insertBefore(button, source); } Array.prototype.forEach.call(document.querySelectorAll('input[type=radio][name=test]'), function(radio) { addButtonBefore(radio, 'toggle the following button'); }); 
 <form id='form' name='form' action='#' method='get'> <input type="RADIO" name="test" value="1" />Yes <br> <input type="RADIO" name="test" value="2" />No </form> 

References:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM