Henk Z Henk Z - 4 months ago 14
jQuery Question

If an input has a value, specific radio button should be checked

I want to check if an input (

) has a value and if so, it should check a radio button (
). If it does not have any value, it should check the other radio button (

See my current code:

<script type="text/javascript">
function ShowHideDiv() {
var chkYes = document.getElementById("Zakelijk");
var dvPassport1 = document.getElementById("checkzakelijk");
var dvPassport2 = document.getElementById("checkzakelijk1");
var dvPassport3 = document.getElementById("checkzakelijk2");
var display = chkYes.checked ? "block" : "none";
dvPassport1.style.display = display;
dvPassport2.style.display = display;
dvPassport3.style.display = display;

<div class="col-md-12 check-business">
<div class="form-group form-group-xl">
<label for="Particulier"><input type="radio" id="Particulier"checked="checked" name="checkzakelijk" onclick="ShowHideDiv()" />Particulier</label>
<label for="Zakelijk"><input type="radio" id="Zakelijk" name="checkzakelijk" onclick="ShowHideDiv()" />Bedrijf</label>

<div class="col-md-12" id="checkzakelijk" style="display:none;">
<div class="form-group">
<label for="inputCompanyName" class="control-label">{$LANG.clientareacompanyname}</label>
<input type="text" name="companyname" id="inputCompanyName" value="{$clientcompanyname}"{if in_array('companyname', $uneditablefields)} disabled="disabled"{/if} class="form-control" />


There are other ways, but this should get you going:

$(function() {
    if (($("#inputCompanyName").val() || "") != "") 
        $("#Zakelijk").prop("checked", true)
    } else {
        $("#Particulier").prop("checked", true)

This is based on your html where the input name='companyname' also has id 'inputCompanyName' and will clear the other radio because they have the same name=

Edit Working jsfiddle: https://jsfiddle.net/76x42os0/4

change input value in the code box (top left) and click run.

Update: Updated the fiddle to the indicated jquery version 3.1.0 and found the newer version of jquery needs id= to match #, while before it matched on name=