javascript - Check radio button programmatically is not working in every browser -
i need check radio button based on path in url.
$(document).ready(function () { function make_url() { var results_url = window.location.pathname.split("/"); console.log(results_url); // ["", "tradeshows"] if (results_url[1] == "tradeshows") { $("#radio2").attr('checked', 'checked'); } else if (results_url[2] == "tradeshows") { $("#radio2").attr('checked', 'checked'); } } }); <ul class="cd-filter-content cd-filters list" id="radiobuttons" onchange="make_url();" style="display: block; padding:0px;"> <li> <input type="radio" checked="" id="radio1" name="radiobutton" value="" data-filter=".radio2" class="filter"> <label for="radio1" class="radio-label">all events</label> </li> <li> <input type="radio" id="radio2" name="radiobutton" data-filter=".radio3" class="filter" value="1"> <label for="radio2" class="radio-label" id="trade">trade shows</label> </li> </ul>
the code working fine on local file system, not on server.
when try console, everytrhing works fine:
$("#radio2").attr('checked','checked');
i tried vanilla javascript:
document.getelementbyid('radio2').checked = true; console.log(document.getelementbyid('radio2').checked); // false
and tried different solution jquery:
$('#radio2').prop('checked', true); // uncaught typeerror: cannot set property 'checked' of null
if getting following error.
uncaught typeerror: cannot set property 'checked' of null
then jquery returning $('#radio2')
null, try logging $('#radio2')
, check in console whether returns value or not.
the main cause of error is, when function executing, there no element present id radio2, there might error if executing function before dom loads.
as mentioned works fine on local machine , not working on server, respond time of server little slower local machine, element not getting loaded , before script loading.
please provide full more description of code.
Comments
Post a Comment