0

I want to replace the button submit identified by dvv with ""( just to remove the button). So I'm using this code, It works but I should click on the button 'test" twice to work. Any explanation?

<script>
    $.fn.gotof = function() { 
        $(document).ready(function(){
            $('#btt').click(function(){
                $('#dvv').replaceWith("");
            });
        });
    };

    function dofunc() {
        $.fn.gotof();  
    } 
</script>

<button id="btt" onclick="dofunc()">
    test
</button>
<div id="dvv">
    <input type="submit" value="submit">
</div>
4
  • what exactly is your requirement? want to delete the button? or replace the button text? Commented Apr 22, 2017 at 11:59
  • deleting the button Commented Apr 22, 2017 at 12:20
  • why not use remove() ? Commented Apr 22, 2017 at 12:22
  • is there a remove() function in javascript? Commented Apr 22, 2017 at 12:25

3 Answers 3

2

There is another problem. You add event listener only by first click and on the second click it do your work

You can fix that in that way

function dofunc() {
  $('#dvv').replaceWith("");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btt" onclick="dofunc()">test</button>
<div id="dvv"> <input type="submit" value="submit"></div>

or that

$(document).ready(function() {
  $('#btt').click(function() {
    $('#dvv').replaceWith("");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btt">test</button>
<div id="dvv"> <input type="submit" value="submit"></div>

In your case you mixed this two approaches in wrong way

Full jQuery style:

$.fn.gotof = function() {
  $('#dvv').replaceWith("");
};


function dofunc() {
  $("#btt").gotof();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btt" onclick="dofunc()">test</button>
<div id="dvv"> <input type="submit" value="submit"></div>

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

Comments

1

If you wan to delete the button, use remove method

$('#btt').click(function(){
            $(this).remove();
        });

Comments

0

The first time you click the button, an onclick event handler is added. The second time you click the button an on click event handler is added and the PREVIOUSLY ADDED handler is fired.

Replace all your JavaScript with just this snippet

 $(document).ready(function(){
    $('#btt').click(function(){
        $('#dvv').replaceWith("");
     });
  });

1 Comment

but I need some conditions in the function that's why I'm using that function "dofunc()"

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.