Search code examples
javascripthtmlhref

Href to checked input radio


I have this code and I want after click to a href checked to radio box code:

 <p><a href=""><?php echo $result['answer1'];?><input type="radio" value="1" class='rgt' name='test1'/></a></p>
 <p><a href=""><?php echo $result['answer2'];?><input type="radio" value="2" class='rgt' name='test2'/></a></p>
 <p><a href=""><?php echo $result['answer3'];?><input type="radio" value="3" class='rgt' name='test3'/></a></p>

How can do it?


Solution

  • HTML:

    <div id="container">
    <p><a href="">111111111111111<input type="radio" value="1" class='rgt' name='test1'/></a></p>
     <p><a href="">2222222222222222<input type="radio" value="2" class='rgt' name='test2'/></a></p>
     <p><a href="">3333333333333333<input type="radio" value="3" class='rgt' name='test3'/></a></p>
    </div>
    

    (all is placed in container, for easier targeting)

    JS:

    container=document.getElementById('container');
    links=container.getElementsByTagName('a');
    
    for(i=0;i<links.length;i++) {
    
        links[i].addEventListener("click", function(e){
    
    e.preventDefault();  
    
            if(this.childNodes[1].checked == true) {
    
            this.childNodes[1].checked = false;
            }
            else {
                 this.childNodes[1].checked =true;
            }
    
    
        });
    
    
    }
    

    Demo: http://jsfiddle.net/ydu6h8vd/