Shape radio buttons with unobtrusive JavaScript

How to convert the following code to unobtrusive JavaScript?

<!DOCTYPE html> <html> <head> <title>title</title> <script type="text/javascript"> function ar_change(){ if (document.ar_form.ar_type[0].checked) var txt = ""; else if (document.ar_form.ar_type[1].checked) var txt = "first text."; else if (document.ar_form.ar_type[2].checked) var txt = "second text."; else if (document.ar_form.ar_type[3].checked) var txt = "third text."; else if (document.ar_form.ar_type[4].checked) var txt = "forth text."; document.ar_form.ar_text.value=txt; } </script> </head> <body> <form name="ar_form" action="." method="post"> <textarea name="ar_text"></textarea><br> <input type="radio" name="ar_type" value="0" onclick="ar_change()" checked>no text<br> <input type="radio" name="ar_type" value="1" onclick="ar_change()">text 1<br> <input type="radio" name="ar_type" value="2" onclick="ar_change()">text 2<br> <input type="radio" name="ar_type" value="3" onclick="ar_change()">text 3<br> <input type="radio" name="ar_type" value="4" onclick="ar_change()">text 4<br> <input type="submit" /> </form> </body> </html> 

This javascript changes the content when the user selects the radion button. the current script is working, I want to remove all the "onclick" from the tags and check that the redio button is changed using js. how am i doing this

+4
source share
2 answers

No changes to the form are required (other than removing the onclick handler):

Plain JS:

Demo here

 window.onload=function() { var rads = document.getElementsByName("ar_type"); for (var i=0,n=rads.length;i<n;i++) { rads[i].onclick=function() { this.form.ar_text.value=["","first_txt","second_txt","third_txt","fourth_txt","fifth_txt"][this.value]; } if (rads[i].checked) rads[i].click(); // set the value onload } } 

JQuery

Demo

 $(document).ready(function() { $('input[name=ar_type]:radio').click(function() { this.form.ar_text.value=["","first_txt","second_txt","third_txt","fourth_txt","fifth_txt"][this.value]; }); $('input[name=ar_type]:radio').filter(":checked").click(); // IMPORTANT!!! }); 
+2
source
 var artexts = [ "", "first text.", "second text.", "third text.", "forth text." ]; ondocumentload(function() { // use any known library thing or your owns var radios = document.getElementsByName("ar_type"); for (var i=0; i<radios.length; i++) radios[i].addEventListener("change", function() { for (var i=0; i<radios.length; i++) if (radios[i].checked) document.getElementById('txtarea').value = artexts[radios[i].value]; }, false); }); 

Do not use on * -tributes in html.

0
source

Source: https://habr.com/ru/post/1384577/


All Articles