onclick on <li> element, I want to clear div which i will find by id. I have got a code
javascript this is how i writing code in a div:
document.getElementById("outputLaps").insertAdjacentHTML(
"beforebegin",
<br /> + "some code";
And that's how i try to clear the div:
document.getElementById("outputLaps").innerHTML = '';
or
var myNode = document.getElementById("outputLaps");
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
But they don't work.
#EDIT
Ok, i tried some solutions from answer but they are not working fine. I will try to explain it one more time.
I've got two elements. When i click on one, it adds some content to div. When i click on second element, i want to clear this div, not completely destroy it. Some solutions from the answers clear only something that i wrote in the div before first element add some code to it.
HTML
<ul>
<li id="lap" onclick="displayLap()">Lap</li>
<li id = "clear" onclick="clearLaps()">Clear laps</li>
</ul>
<div id="outputLaps">rr</div>
First element on click add text:
function displayLap() {
numberOfLap++;
document.getElementById("outputLaps").insertAdjacentHTML(
"beforebegin",
" Number of lap: " + numberOfLap + " time: " + minutes + ":" + seconds + ":" + milliseconds
);
}
Then i want to clear it with this function:
function clearLaps() {
}
You were close:
document.getElementById("outputLaps").outerHTML='';
You can use this.
var node = document.getElementById("outputLaps");
node.parentNode.replaceChild(node.cloneNode(false), node);
Or if you want to destroy all.
var node = document.getElementById("outputLaps");
node.parentNode.removeChild(node);
Ok, I finally created what I wanted. Thanks everyone for answer. I had to change the way of adding text to the div, had to change it all on text so the innerHTML could clear it easy. I had to not use <br /> but instead of "\n", so it display next text properly. Here what I have now:
html
<ul>
<li id="lap" onclick="displayLap()">Lap</li>
<li id = "clear" onclick="clearLaps()">Clear laps</li>
</ul>
<div id="outputLaps"></div>
JS
function displayLap() {
numberOfLap++;
var str = "Number of lap: " + numberOfLap + " time: " + minutes + ":" + seconds + ":0" + milliseconds + "\n";
document.getElementById("outputLaps").appendChild(
document.createTextNode(str))
}
function clearLaps() {
numberOfLap = 0;
document.getElementById("outputLaps").innerHTML = "";
}
for javascript use .remove()
document.getElementById("outputLaps").remove();
you can do this in jquery
$(function() {
$("li").on("click",function() {
$("#outputLaps").remove();
});
});
Related
I have the following code:
if (secsleft < 10) {
var msg = 'No activity detected in the last 10 seconds.';
if (auth == "true"){
msg += '<br />You will be logged out in <br /><p id="counter">' + secsleft + '</p><br /> more seconds if no activity is detected.';
} else {
msg += '<br />You will be redirected in <br /><p id="counter">' + secsleft + '</p><br /> more seconds if no activity is detected.';
}
if (secsleft < 4) {
//$("#counter").css({"color":"red"});
//$("#counter").css("color", "red");
document.getElementById("counter").style.color = "red";
}
Message('<span id="timer">' + msg + '</span>', 10000);
}
The intent obviously is to change the color of the counter to red when less than four seconds are left. The problem is that the p tag with id="counter" is first created in the IF statement. If I was looking to bind an event to it, I know how to do it. It would be something like:
$(document).on(eventName, "#counter", function() {});
But that doesn't work for attributes. I have tried all kinds of combinations as you can see from the commented code in the inner IF, but none work. Incidentally (and surprisingly to me), I can get the attribute easily, so for example:
alert($("#counter").css("color"));
gives me the right value. So, how does one change the value?
The issue is that you're not actually creating the element until after that if statement, so all of your jQuery selectors and getElementById calls will not find anything on the page since there is nothing with an id of "counter" yet. You've simply made a string that you will later convert into an actual element.
What you need to do is create an actual element and then using a reference to it you can change its attributes before you even put it on the page.
var counter = document.createElement('p');
counter.id = 'counter';
counter.style.color = red;
Or something along those lines. I've shown you the vanilla JS solution here but you can do the same using jQuery:
var counter = $('<p></p>');
counter.attr('id','counter');
counter.css('color','red');
I don't see much jQuery but you did add it as a tag. So why not do something like this?
$("body").find("#counter").css("color", "red");
You can't use document.getElementById() for elements which have not yet been added to the document. That's why it doesn't work.
You could simplify your code a lot.
if (secsleft < 10) {
var color = secsleft < 4 ? 'red' : 'inherit';
var action = auth === 'true' ? 'logged out' : 'redirected';
var msg = 'No activity detected in the last 10 seconds.'
+ '<br />You will be '+ action +' in '
+ '<span style="color: '+ color +'">' + secsleft + '</span>'
+ ' more seconds if no activity is detected.';
Message('<span id="timer">' + msg + '</span>', 10000);
}
I think there is a neater way to achieve what you are looking for rather can adding in the styles using jQuery. Instead it is better to allow your CSS to handle the styles and the jQuery to add in classes where appropriate.
In the below code the <4 check is used to assign a value to a counterClass variable which is then added to you counter element. You can then add a css rule to achieve the red colour.
if (secsleft < 10) {
var counterClass = "";
if (secsleft < 4) {
counterClass = "warning";
}
var msg = 'No activity detected in the last 10 seconds.';
if (auth == "true") {
msg += '<br />You will be logged out in <br />p id="counter" class="' + counterClass + '">' + secsleft + '</p><br /> more seconds if no activity is detected.';
} else {
msg += '<br />You will be redirected in <br /><p id="counter" class="' + counterClass + '">' + secsleft + '</p><br /> more seconds if no activity is detected.';
}
Message('<span id="timer">' + msg + '</span>', 10000);
}
Hope this helps.
The first problem is that you haven't yet added the #counter element to the document, meaning you can't use the document.getElementByID(...); method on it (yet).
To be able to manipulate a element, you would have to add it to the document, to do this you would use:
// appends the new "div" element to the body (I.E: inserts the new element at the end of the body)
$("body").append("<div id='element-id'>Hello World!</div>");
You could also use these methods:
// replaces the "innerHTML" of the "body" element with the new "div" element
$("body").html("<div id='element-id'>Hello World!</div>");
// prepends the new div to the body (I.E: inserts the element as the first child not the last child)
$("body").prepend("<div id='element-id'>Hello World!</div>");
Now, the second problem is that you are getting the value of the CSS property and NOT setting it.
To get the current value of a CSS property you would use this:
$("#element-id").css("property-name")
To change the value of a CSS attribute in jQuery you would use this:
// listen for an event to occur
$(document).on("event-name", function() {
// change a single property of the element
$("#element-id").css("property", "new-value");
});
You could also change multiple properties of the element at once, using a JavaScript object like this:
// listen for an event to occur
$(document).on("event-name", function() {
// change multiple properties of the element using a JavaScript object
$("#element-id").css({
"property-name-one": "new-value",
"property-name-two": "new-value"
});
});
For more information on the jQuery methods mentioned above, visit the links below:
jQuery.fn.html(...);.
jQuery.fn.append(...);.
jQuery.fn.prepend(...);.
jQuery.fn.on(...);.
jQuery.fn.css(...);.
Hope this helps, good luck and all the best.
You will not get element using getElementById which have not yet been added to DOM. you can use inline styles.
if (secsleft < 10) {
var alertColor = "inherit";
if(secsleft < 4) {
alertColor = "red";
}
var msg = 'No activity detected in the last 10 seconds.';
if (auth == "true"){
msg += '<br />You will be logged out in <br /><p id="counter" style="' + alertColor + '">' + secsleft + '</p><br /> more seconds if no activity is detected.';
} else {
msg += '<br />You will be redirected in <br /><p id="counter" style="' + alertColor + '">' + secsleft + '</p><br /> more seconds if no activity is detected.';
}
Message('<span id="timer">' + msg + '</span>', 10000);
}
I have created one html which contains search box. After searching, I'm getting the data in list. But when I click on that I'm getting the value of all list item by using this
var text = $(this).text(); method
In my app, if I click on one item only it should give me only that value of list item not other. I'm making a mistake somewhere, but I don't know where.
Here is my code:
HTML
<ul data-role="listview" class="ui-li-icon">
<li id="list"></li>
</ul>
And here is my JavaScript code:
function successCallback(responseObj)
{
// alert(JSON.stringify(responseObj));
form.reset();
dataj=JSON.stringify(responseObj);
len=dataj.length;
for(i=0;i<len;i++)
{
var output = "<ul>" + responseObj.merchants[i].imageFileName+ " " + "<font size=3 color=green>" + responseObj.merchants[i].merchantName + "</font>" +"</ul>";
$('#list').append(output);
}
$('#list').click(function() {
var index = $(this).index();
var text = $(this).text();
alert('Index is: ' + index + ' and text is ' + text);
});
}
So when I'm searching for some a item. I'm getting list of:
ab
abc
But when I clicked on it. I get value of both ab and abc. I just want only one value where I have clicked.
//replace your click event by below code
$('.ui-li-icon li').click(function() {
var index = $(this).index();
var text = $(this).text();
alert('Index is: ' + index + ' and text is ' + text);
});
$('#list').append(output);
I believer list is the id you are giving to list items i.e.
Now, this will confuse the browser because id should be UNIQUE and here you are giving this id to all the list items.
If you fix this, your problem should be resolved!
Or you could simply attach click event using this
$('.ui-li-icon li').click //Your click event handler
It's very difficult to understand what you are asking. From what I can tell you're looking for something like this:
$('#list li').on('click', function(){
alert("index: "+$(this).index() + " value: "+ $(this).text());
});
Here's a fiddle http://jsfiddle.net/Jw8qz/
I want to delete the last append when i click the back button. but when Im choosing appending again,the last append still there.
this is my codes on appending. its working:
$(req.responseText).find('ItemName').each(function () {
ItemNameArr[ItName] = $(this).text();
ItName++;
})
$(req.responseText).find('ItemQty').each(function () {
ItemQtyArr[ItQty] = $(this).text();
ItQty++;
})
$(req.responseText).find('ItemUnit').each(function () {
ItemUnitArr[ItUn] = $(this).text();
ItUn++;
})
for (var a = 0; a < ItemNameArr.length; a++) {
//$contentDt = $('<p><h6> ' + ItemQtyArr[a] + " " + ItemUnitArr[a] + " " + ItemNameArr[a] + '</h6></p>');
$('#Ingredients').append('<p><h6> ' + ItemQtyArr[a] + " " + ItemUnitArr[a] + " " + ItemNameArr[a] + '</h6></p>')
$('#Ingredients').fieldcontain('refresh')
}
My codes in back button when its click:
$("#btnBack").on('click',function(){
$('#Ingredients').empty()
$('#Ingredients').fieldcontain('refresh')
});
My codes in html when it was append
<div data-role="fieldcontain" id="Ingredients"> <!--Ingridients-->
</div>
});
You can do it using below code.
$('#Ingredients p:last').remove();
Use this Code
$('#Ingredients p:last').remove();
Explanation
# referees for the id selector.
$('#Ingredients p) finds the p tag in the element with id Ingredients.
$('#Ingredients p:last') selects last p tag in the element with id Ingredients.
.remove() function removes it from the page.
Problem is in your back button code (click event)
it will be -
$("html").on('click','#btnBack',function(){
// your code
// for remove last p element within #Ingredients
$('#Ingredients p:last').remove();
});
I'm trying to make a generator for a mod menu in Call of Duty. I want people to be able to add a menu or delete one. I'm trying to id the menus sequentially so that I can use the text field values correctly. I made it so that if they delete a menu it changes the ids of all the other menus to one lower and same for the button id, but I don't know how to change the onlick event to remove the right element.
Better yet, if there's a better way to do this, I would love to know it.
<script type="text/javascript">
y = 1
function test2()
{
document.getElementById("test2").innerHTML += "<div id=\"child" + y + "\"><input type=\"text\" value=\"menu name\" \><input id=\"button" + y + "\" type=\"button\" value=\"remove?\" onclick=\"test3(" + y + ")\" /></div>";
y++;
alert(y);
}
function test3(x)
{
document.getElementById("test2").removeChild(document.getElementById("child" + x));
for(var t = x+1;t < y;t++)
{
alert("t is " + t + ". And y is " + y);
document.getElementById("button" + t).setAttribute("onclick" , "test3(t-1)");
document.getElementById("button" + t).id = "button" + (t-1);
document.getElementById("child" + t).id = "child" + (t-1);
}
y--;
}
</script>
<input value="testing" type="button" onclick="test2()" />
<div id="test2" class="cfgcode"></div>
I wouldn't worry about re-indexing all of the elements after you add or remove one, that seems a waste. It would be better to simply write a more generic function, rather than one with the element id hard coded into it.
For example, your first function could be written as so:
function genericFunction(el)
{
var html = ''; // create any new html here
el.innerHTML = html;
}
You can then add onclick handlers such as:
myDiv.onclick = function() { genericFunction(this) };
I would also agree with all the commenters above, use jQuery, it makes any code which interacts with the DOM much much simpler.
I'm using Raphael for drawing some elements on a website. The elements include rectangle, line (path). I have given an id to the path element and trying to access it in the onclick event of that line. but when I do an alert of the id, nothing is visible. Following is the code snippet
function createLine()
{
var t = paper.path("M" + xLink + " " + yLink +"L" + linkWidth + " " + linkHeight);
t.attr('stroke-width','3');
t.attr('id','Hello');
t.node.onclick = processPathOnClick;
}
function processPathOnClick()
{
alert($(this).attr("id"));
}
Can anyone please tell me what is the problem with the above code. Any pointer will be helpful.
Thanks
Are you sure you don't want to write $(t.node).attr('id','Hello'); instead?
Update: someone just downvoted this answer. And I truly feel obligated to point out this way of setting the id isn't particularly good. You would be better off using:
t.node.id = 'Hello';
I wish there was a way to credit Juan Mendes, other than upvoting his comment to this answer.
Try this:
function createLine() {
var t = paper.path("M" + xLink + " " + yLink +"L" + linkWidth + " " + linkHeight);
t.attr('stroke-width','3');
t.id = 'Hello';
t.node.onclick = processPathOnClick;
}
function processPathOnClick() {
alert($(this).id);
alert(this.id); // This should work too...
}
Basically you are creating a new property called "id" on your Raphael line instance variable "t". It's kind of hacking, in my opinion, but it does the trick just fine.
Try setting the handler using jquery
function createLine()
{
var t = paper.path("M" + xLink + " " + yLink +"L" + linkWidth + " " + linkHeight);
t.attr('stroke-width','3');
t.attr('id','Hello');
$(t.node).click(processPathOnClick);
}
function processPathOnClick()
{
alert($(this).attr("id"));
}