1

I have a button where on clicking the button it will clear all the textbox and drop down values now i need to create a common function and place my below jquery code in that common function so that i can call that function in button2,button3 click events of jquery

<input type="button" value="Clear" title="clear" id="btnclear" />
<input type="button" value="" title="clear" id="btn2" />
<input type="button" value="" title="clear" id="btn3" />
// I need to place the below code in a function to use the function in remaining click events
$('#btnclear').off('click').on('click', function (RD) {
  $('#txtname').val("");
});

$("#btn2").click(function () {
  // I need to call the created common jquery function to clear the fields 
});

$("#btn3").click(function () {
  // I need to call the created common jquery function to clear the fields 
});
3
  • So create a function and call it...? If you're struggling try this: developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions Commented Jan 21, 2019 at 8:05
  • that i what my question is how to create a common function and place that common function in btn2 and btn3 click events of jquery Commented Jan 21, 2019 at 8:06
  • I don't understand the problem Commented Jan 21, 2019 at 8:09

1 Answer 1

3

Just define a function in the normal way. Then you can call it from all the handlers:

function clear_text() {
  $("#txtname").val("");
}
$('#btnclear').off('click').on('click', function() {
    clear_text();
});

$("#btn2").click(function() {
    $("#tr2").show();
    clear_text();
});

$("#btn3").click(function() {
    $("#tr2").hide();
    clear_text();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" value="Clear" title="clear" id="btnclear" />
<input type="button" value="" title="clear" id="btn2" />
<input type="button" value="" title="clear" id="btn3" /> Text: <input type="text" id="txtname">

Sign up to request clarification or add additional context in comments.

11 Comments

then do i need to return clear_text() function in my html input tags <input type="button" value="" title="clear" id="btn2" /> <input type="button" value="" title="clear" id="btn3" />
No, you don't need to do anything different in the HTML.
Maybe you defined it inside a function scope and then tried to use it outside the function?
Make sure the event handlers are in the same scope where you put the function definition.
My answer shows the way to do it. You're getting that error because you wrote something completely different.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.