user1794918
user1794918

Reputation: 1159

javascript onclick radio clear textbox

I would like to clear a text box when a radio button above the text box is selected.

I have tried this:

 function clearThis(target){
    target = document.getElementById(target);
   target.value = "";
  }

 <input type="radio" name="not_req" id="clear_req" value="" 
        title="Click here to clear the No Auth need flag"><span id="clear" onclick = 'clearThis("claims")' >Clear

The box I would like to clear is

 <input type="text" size="5" name="auth_for" id="claims" value="{$prior_auth->get_auth_for()}" title="Set the number of times no auth can be used">

Took most of this from http://jsfiddle.net/BMrUb/ but I can see that the example is clearing the adjacent text box. I would like to clear a text box not adjacent to the radio button.

Upvotes: 0

Views: 1077

Answers (2)

user162097
user162097

Reputation: 1258

The problem is that it's the sibling input element that needs its value clearing, not the span, even though you only want it to clear when people click on the span element. So the example code below does this. You're also best off decoupling your javascript from your HTML by using event listeners (and not using the old-fashioned onclick attribute).

var clearSpanEl = document.getElementById("clear");

clearSpanEl.addEventListener("click", function(e) {
    var inputEl = e.target.previousElementSibling;
    inputEl.value = "";
}, false);

<input type="text" name="search" id="search" value="I can be cleared" />
<span id="clear">Clear results</span>

I've forked your JSFiddle here, so you can see it working.

Upvotes: 0

Kunal
Kunal

Reputation: 229

As Gerald said place your onclick="" in the <input type="radio" ... >, not in the <span>.

Upvotes: 1

Related Questions