Solution 1 :

You input have some issues with input closing and also with your JS.

This is how you can close input element />

Also, if you are calling getPrevious on input click you can use getPrevious(this) and get the value of the onclick input like this simplified method.

Just run snippet below to see it action.

function getPreview(event) {
  if (event.value == "option1") {
    console.log('option 1 checked')
  } else {
    console.log('option 2 checked')
  }
}
<div class="action">
  <div class="...">{label...}</div>
  <div class="...">
    <input type="radio" tabindex="0" aria-label={...} name="preview" value="option1" onclick="getPreview(this)"/>
    <label>{...}</label>
  </div>
  <div class="...">
    <input type="radio" tabindex="0" aria-label={...} name="preview" value="option2" onclick="getPreview(this)" />
    <label>{...}</label>
  </div>
</div>

Problem :

I need to check the first radio button (value = “option1”) by default. But after adding “checked” attributes, the radio button with value “option2” needs two click to get checked. Any idea whats wrong here?
Based on other posts i have included the code in between form tag, i have also tried changing “checked” to ‘checked=”checked”‘, tried with different “name” attribute, removing the div around radio button.

This is my code:

HTML

            <div class="action">
                <div class="...">{label...}</div>
                <div class="...">
                    <input type="radio" tabindex="0" aria-label={...} name="preview" value="option1" onclick={getPreview} checked></input>
                    <label>{...}</label>
                </div>
                <div class="...">
                    <input type="radio" tabindex="0" aria-label={...} name="preview" value="option2" onclick={getPreview} ></input>
                    <label>{...}</label>
                </div>
            </div>

JS

 getPreview(event) {
        if(event.target.value == "option1") {
            ...
        } else {
            ...
        }
    }

But nothing seems to be working.

Comments

Comment posted by Always Helping

firstly that’s not how use to close input element use this –

Comment posted by pks

I am using LWC framework, bare html and js works fine for me but with LWC framework i still have the same issue. I should probably post this in channel specific to LWC. Thanks for your help.

Comment posted by pks

Thanks for the suggestion. But it did not work. If i remove the “checked” attribute both the radio buttons get checked on single click.

Comment posted by Always Helping

@pks its working fine. i have updated my answer and removed

By