i have started learning JQuery and made script that when you press button it adds that button value into a div. I made a CLEAR text that when you press it clears the text / numbers from that div but the problem is when you press the CLEAR and i press button that should add X value into that div it does not print it and i have to refresh the page.
CLEAR SCRIPT
$(document).ready(function(){
$("p").click(function(){
$(".total").remove();
});
});
CLEAR TEXT
<p>CLEAR</p>
DIV
<div id="div_number" class="total"></div>
EDIT:
I also have to remove value=""
from this Oh it can be my mistake, i also have to remove the value="" from
``
EDIT 2:
This is the code that i have made jsfiddle.net/utcs4L1h/
Update
So, based on your provided code on jsfiddle
, you just need to add this: count = 0;
after this: $('.total').empty();
$(".clear").click(function() {
$('.total').empty();
count = 0;
});
I kept following for future readers
You used remove()
, instead of empty()
or just text('')
.
From jQuery
documentation:
.remove( [selector ] )
: Remove the set of matched elements from the DOM. .empty()
: Remove all child nodes of the set of matched elements from the DOM. text()
: Get the combined text contents of each element in the set of matched elements, including their descendants. change this:
$(".total").remove();
on this:
$(".total").html('');
If you want clear your div, you shouldn't remove it, but only remove its content. Use html('')
to do this :)
Use empty() instead of remove().
$('.total').empty();
Doesn't matter much in this simple example, but empty() is preferred to html('') since jquery will remove event handlers/etc on child nodes.
I believe you are looking for the text()
jQuery method instead of removing your element from the DOM.
CODE SNIPPET:
$(document).ready(function() { var $triggerX = $("#trigger-x"), $triggerClear = $("#trigger-clear"), $totalContainer = $("#div_number"), $hiddenInput = $("#form_number"), iNumber = 1000; $triggerX.on("click", function() { $totalContainer.text(iNumber); $hiddenInput.val(iNumber); }); $triggerClear.on("click", function() { $totalContainer.text(""); $hiddenInput.val(""); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="form_number" type="number" value="" /> <button id="trigger-x">ADD #</button> <button id="trigger-clear">CLEAR</button> <div id="div_number" class="total"></div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.