-2

I am trying to take a button and make it to a reset button for one field in multiple field form.

<button id ="resetbutton" type="button">reset focused field</button>
<script type="text/javascript">

document.getElementById('resetbutton').onclick= function() {
        // Get the focused element:
        var $focused = $(':focus');
        var field= document.getElementById($focused);
        field.value= "";
    };
</script>

the focused field variable doesn't work for me and it doesn't get the focused field that I need to reset, any suggestions?

maybe when I press the button I get a focus on the button but what I really want is latest focused field.

dreamoki
  • 43
  • 8
  • *What doesn't work? Be more specific.* – AStopher Dec 21 '14 at 11:42
  • Presumably because the field loses focus when you click the button. – James Hibbard Dec 21 '14 at 11:48
  • yes you are right, I saw in this answer that there is no way to get the previously focused element from javascript, any workaround to that? http://stackoverflow.com/questions/7329141/how-do-i-get-the-previously-focused-element-in-javascript – dreamoki Dec 21 '14 at 11:59

3 Answers3

3

If you retrieve the focused element by a click on a button, the element in question will always lose the focus just before that. To get the ID of a previously focused element you should track the focused elements. Create a last_focused variable that holds the ID for the last focused element, and update it when ever one of your form elements gets the focus. Then, when you click on your resetbutton, just use this value to handle the element.

bosnjak
  • 8,424
  • 2
  • 21
  • 47
0

Expanding on Lawrence's answer, this is how you might implement it:

var previouslyFocused;

$("input").on("blur", function(){
    previouslyFocused = this.id;
});

$("button").on("click", function(e){
    e.preventDefault();
    $("#" + previouslyFocused).val("");
});
input{
    margin: 5px;
    display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
    <input type="text" id="name" placeholder="Name" />
    <input type="text" id="age" placeholder="Age" />
    <input type="text" id="address" placeholder="Address" />
    <input type="text" id="shoeSize" placeholder="Shoe size" />
    <button>Reset focused field</button>
</form>
James Hibbard
  • 16,490
  • 14
  • 62
  • 74
0

An elegant solution for that is to use html5 type input "search" that adds a small "X" beside that input so you can reset it individually.

dreamoki
  • 43
  • 8