1

I saw similar solutions on detecting and assigning actions when 'X' button pressed on type="search" textfield action upon pressing X button. I want to do using @Html.TextBoxFor(model => model.SearchTerm, new { id = "search-box", type = "search"}. However it cannot fire the event specifically on clearance button 'X' click.

So far I have managed to register all events:

$('#search-box').on('click', function (e) {
    alert(e);

    System.Diagnostics.Debug.Write(e.target);
});

Any help would be greatly appreciated

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
hackForLife
  • 144
  • 1
  • 2
  • 10
  • Your requirement is `'X'` button in `@Html.TextBoxfor` and whenever clicks on `'X'` the text box become empty. Right ? – Sunil Kumar Jul 13 '16 at 10:56
  • @SunilKumar It clears the text from textBox upon pressing 'X' without having any code, but my requirement is to redirect to home page when the user clicks 'X' button. – hackForLife Jul 13 '16 at 13:04

1 Answers1

1

I have tried following code:

HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="clearable" type="text" name="" value="" placeholder="" />

JQuery:

function tog(v){return v?'addClass':'removeClass';} 
$(document).on('input', '.clearable', function(){
    $(this)[tog(this.value)]('x');
}).on('mousemove', '.x', function( e ){
    $(this)[tog(this.offsetWidth-18 < e.clientX-this.getBoundingClientRect().left)]('onX');
}).on('touchstart click', '.onX', function( ev ){
    ev.preventDefault();
    alert('33');// put window.location('url goes here');
    $(this).removeClass('x onX').val('').change();
});

CSS:

.clearable{
  background: #fff url(https://i.stack.imgur.com/mJotv.gif) no-repeat right -10px center;
  border: 1px solid #999;
  padding: 3px 18px 3px 4px;     /* Use the same right padding (18) in jQ! */
  border-radius: 3px;
  transition: background 0.4s;
}
.clearable.x  { background-position: right 5px center; } /* (jQ) Show icon */
.clearable.onX{ cursor: pointer; }              /* (jQ) hover cursor style */
.clearable::-ms-clear {display: none; width:0; height:0;} /* Remove IE default X */

Fiddle is here : click here

Hope it helps you .. :)

Happy Coding..

Sunil Kumar
  • 3,142
  • 1
  • 19
  • 33