function getUrlVars(){ var vars = {}; var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value){ vars[key] = value; }); return vars; } var getBt = getUrlVars()["bt"];
According to the getBt variable here, how can I do ‘checked’ from the options below to the value equal to value?
So, for example, if the value of getBt is 2, I want to select the radio option with value 2.
<div class="card-body"> <label class="custom-control custom-radio"> <input type="radio" name="Filter[type][]" checked="" value="0" class="custom-control-input"> <div class="custom-control-label">All</div> </label> <label class="custom-control custom-radio"> <input type="radio" name="Filter[type][]" value="1" class="custom-control-input"> <div class="custom-control-label">option1</div> </label> <label class="custom-control custom-radio"> <input type="radio" name="Filter[type][]" value="2" class="custom-control-input"> <div class="custom-control-label">option2</div> </label> <label class="custom-control custom-radio"> <input type="radio" name="Filter[type][]" value="3" class="custom-control-input"> <div class="custom-control-label">option3</div> </label> </div>
Advertisement
Answer
Let’s assume your method of parsing URL is working fine, and variable getBt
contains the value that you wanted to be checked in radio button, there are couple of solution that you might try.
1. Using Vanilla JS
We can use attribute selector in DOM by using document.querySelector()
and document.querySelectorAll()
methods.
let getBt = 2; // value populated by parsing URL let radioButton = document.querySelector(`[name="Filter[type][]"][value='${getBt}']`);; radioButton.checked = true;
2. Using jQuery
JQuery makes DOM manipulation easier, and for including that in your project, include the following in your project html file:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Now in JS file, just write this:
$(`input[value=${getBt}]`).attr("checked", "checked")
PS: You can choose any solution to solve the issue. Hope it works.
You can find both version of solution in this Stackblitz link