<div class="button button1" id="content" onclick="toggleClass(event);">Stay Updated</div>
<script>
function toggleClass(evt) {
var btn = evt.target;
if (btn.className == "button button1") {
btn.className = "info";
btn.onclick = null;
} else {
btn.className = "button button1";
}
}
</script>
Trying to change the content of the div after the click has happened and during the change in class.
You should try creating a text node using document.createTextNode which will take care of character escaping as well.
function toggleClass(event) {
var btn = evt.target;
//Clears the div
while(btn.firstChild){
btn.removeChild(btn.firstChild);
}
if (btn.className == "button button1") {
btn.className = "info";
btn.onclick = null;
//Append hello to the div
btn.appendChild(document.createTextNode('World'));
} else {
btn.className = "button button1";
btn.appendChild(document.createTextNode('Hello'));
}
}
<div class="button button1" id="content" onclick="toggleClass(event);">Stay Updated</div>
Related
I want to attach more than one field to a div along with a remove button. Something similar to Gmail file attaching methods if the user presses the remove button it should remove the specified p along with the button. But if I press the remove button it is not working properly I know the javascript array method is the problem but I am not able to understand where I am going wrong
<form name="create" action ="">
<input type="text" id="text">
<button name="submit" onclick="attach()" type="button">Submit</button>
</form>
<div id="attach">
</div>
<script>
function attach(){
var value =document.getElementById('text').value;
var content = document.createElement('p'); // is a node
content.className = 'element';
// Insert text
var btn = document.createElement("BUTTON");
btn.innerHTML = "Delete This element";
var i =0;
btn.onclick = function(){
console.log(i);
remove(i);
i++;
};
content.innerHTML = value;
document.getElementById("attach").appendChild(content);
document.getElementById("attach").appendChild(btn);
}
function remove(i){
var elem = document.getElementsByClassName('element');
elem[i].remove();
return false;
}
</script>
The working plunker is here.
http://plnkr.co/edit/eYhfN85FH4XabzE4rO4M?p=preview
What is going wrong here? How can I fix this?
A slightly different approach that simplifies your original example, is to take advantage of the function/closure you create for the button you create. In there, you can literally just reference the content and btn elements, and remove them directly
function attach(){
var value =document.getElementById('text').value;
var content = document.createElement('p'); // is a node
content.className = 'element';
// Insert text
var btn = document.createElement("BUTTON");
btn.className = 'element';
btn.innerHTML = "Delete This element";
btn.onclick = function(){
content.remove();
btn.remove();
};
content.innerHTML = value;
var attach = document.getElementById("attach");
attach.appendChild(content);
attach.appendChild(btn);
}
<form name="create" action ="">
<input type="text" id="text">
<button name="submit" onclick="attach()" type="button">Submit</button>
</form>
<div id="attach">
</div>
That way, you don't have to worry about what index you're removing or anything
Here you go!
function attach() {
const attachEl = document.getElementById("attach");
const value = document.getElementById("text").value;
const contentEl = document.createElement("p"); // is a node
contentEl.className = "element";
// Insert text
const btnEl = document.createElement("button");
btnEl.innerHTML = "Delete This element";
const wrapperEl = document.createElement("div");
btnEl.onclick = function() {
attachEl.removeChild(wrapperEl);
};
attachEl.appendChild(wrapperEl);
wrapperEl.appendChild(contentEl);
wrapperEl.appendChild(btnEl);
contentEl.innerHTML = value;
}
#attach{
background-color: teal;
}
.element {
background-color: wheat;
}
<form name="create" action="">
<input type="text" id="text">
<button name="submit" onclick="attach()" type="button">Submit</button>
</form>
<div id="attach">
</div>
We should use a wrapper to wrap a p & button together so that when we initiate delete it deletes the complete wrapper
function attach(){
var value =document.getElementById('text').value;
var content = document.createElement('p'); // is a node
var wrapper = document.createElement('div');
wrapper.className="wrapper";
content.className = 'element';
// Insert text
var btn = document.createElement("BUTTON");
btn.innerHTML = "Delete This element";
var i =0;
btn.onclick = function(){
console.log(i);
remove(i);
i++;
};
content.innerHTML = value;
wrapper.appendChild(content);
wrapper.appendChild(btn);
document.getElementById("attach").appendChild(wrapper);
}
function remove(i){
var elem = document.getElementsByClassName('wrapper');
elem[i].remove();
return false;
}
<form name="create" action ="">
<input type="text" id="text">
<button name="submit" onclick="attach()" type="button">Submit</button>
</form>
<div id="attach">
</div>
I am creating a simple note editor that has two divs a heading and a body. I'm trying to add a new note by creating the two divs with a button. Such that when you click the button the new divs will be created with texts appended to it through localStorage. When I click the button none of the divs is added. here is the html
<div id ="heading" contenteditable="true">
</div>
<div id="content" contenteditable="true">
</div>
<button type="button" onclick="addNote()" name="button">Add new Note</button>
here is the js
document.getElementById("heading").innerHTML = localStorage['title'] || 'Heading goes here';
document.getElementById('content').innerHTML = localStorage['text'] || 'Body of text editor';
setInterval(function () {
localStorage['title'] = document.getElementById('heading').innerHTML;
localStorage['text'] = document.getElementById('content').innerHTML;
}, 1000);
function addNote() {
const heading = document.createElement('div');
const content = document.createElement('div');
heading.id = "heading";
content.id = "content";
localStorage['title'] = document.getElementById('heading').innerHTML;
localStorage['text'] = document.getElementById('content').innerHTML;
}
your are missing to append the created elements to the dom (https://www.w3schools.com/jsref/met_node_appendchild.asp) :
function addNote() {
var heading = document.createElement('div');
var content = document.createElement('div');
heading.id = "heading";
content.id = "content";
document.getElementById("myDivs").appendChild(heading);
document.getElementById("myDivs").appendChild(content);
}
and you will need to have an div with id myDivs
<div id="myDivs"></div>
<button type="button" onclick="addNote()" name="button">Add new Note</button>
greetings
There are many problems in your code.
Proper way to set localStorage is via localStorage.setItem(key, val)
You need to append your DIVs somewhere on your HTML page.
Also you need to handle your setTimeout properly.
Please find solution below
HTML
<button type="button" onclick="addNote()" name="button">Add new Note</button>
JavaScript
var intervalObj = null;
function addNote() {
if(intervalObj) {
clearInterval(intervalObj)
}
const heading = document.createElement('div');
heading.setAttribute('contenteditable', true)
heading.id = "heading";
const content = document.createElement('div');
content.setAttribute('contenteditable', true)
content.id = "content";
heading.innerHTML = window.localStorage.getItem('title') || 'Heading goes here';
content.innerHTML = window.localStorage.getItem('text') || 'Body of text editor';
document.getElementsByTagName("body")[0].append(heading);
document.getElementsByTagName("body")[0].append(content);
intervalObj = setInterval(function () {
localStorage.setItem('title', document.getElementById('heading').innerHTML);
localStorage.setItem('text', document.getElementById('content').innerHTML);
}, 1000);
}
Instead of using the setInterval function you can load the data using an onload function and update to local storage whenever the AddNote button is clicked.
Modify the html as follows:
<body onload="load()">
<div id ="heading" contenteditable="true">
</div>
<div id="content" contenteditable="true">
</div>
<button type="button" onclick="addNote()" name="button">Add new Note</button>
</body>
And also you can modify your JS file as follows
function load() {
var headingText = localStorage['title'] || 'Heading goes here';
var bodyText = localStorage['text'] || 'Body of text editor';
document.getElementById("heading").innerHTML = headingText;
document.getElementById('content').innerHTML = bodyText;
}
function addNote() {
localStorage['title'] = document.getElementById('heading').innerHTML;
localStorage['text'] = document.getElementById('content').innerHTML;
}
here is javascript what i have tried
function toggle(clicked_id,name) {
alert(clicked_id);
alert(name);
var text = document.getElementById("clicked_id");
var ele = document.getElementById("name");
alert(ele.style.display);
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "+";
text.value="+"
}
else {
ele.style.display = "block";
text.innerHTML = "-";
text.value="-"
}
return
}
and html is
<input type="button" id="displayText1" onClick="return toggle(this.id,this.name)" value="+" style="margin-left:86%;" name="toggleText1">
<div id="toggleText1" style="display: none"><h1>Wallet Info Here</h1></div> </div>
<input type="button" id="displayText2" onClick="toggle(this.id,this.name)" value="+" style="margin-left:86%;" name="toggleText2">
<div id="toggleText2" style="display: none"><h1>Wallet Info Here</h1></div> </div>
i tried this but only alerts i am getting..no change in div style. That is not changing to hide or show mode
Issue is this:
var text = document.getElementById("clicked_id"); // func arg is in string format
var ele = document.getElementById("name"); // func arg is in string format
You have to use it without quotes.
var text = document.getElementById(clicked_id);
var ele = document.getElementById(name);
yet there is a better way of doing this, you can do something like this:
<input type="button" id="displayText1" onClick="toggle(this)" value="+" style="margin-left:86%;" name="toggleText1">
<input type="button" id="displayText2" onClick="toggle(this)" value="+" style="margin-left:86%;" name="toggleText2">
just pass this in the argument and you can change the function like this:
function toggle(el) {
var text = el;
var ele = document.getElementById(el.name);
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "+";
text.value="+"
} else {
ele.style.display = "block";
text.innerHTML = "-";
text.value="-"
}
}
As you don't need to return anything it is just a dom manipulation stuff, so you can remove the return statement.
I suggest you to avoid inline event handlers, so if you are interested in unobtrusive javascript then you can place this event handler in a js file with that toggle() function and you can use it:
document.getElementById('displayText1').addEventListener('click', function(){
toggle(this);
});
document.getElementById('displayText2').addEventListener('click', function(){
toggle(this);
});
or with querySelectorAll method:
document.querySelectorAll('#displayText1, #displayText2').addEventListener('click', function(){
toggle(this);
});
Just remove quotes around variable name
var text = document.getElementById(clicked_id);
var ele = document.getElementById(name);
DEMO
The quotes around the variables "clicked_id" and "name" causes them to act as string. And there are no elements with these id.
Just remove the quotes and things will work out.
var text = document.getElementById(clicked_id);
var ele = document.getElementById(name);
I have a submit button which I am sharing between 'Create' and 'Update'. I want the following labels depending on my page state:
Create = Submit
Update = Update
These buttons also have an image at the front of them using glyphicon but the image will be the same for both buttons.
To get to my page states (listed above) I have other JavaScript functions which the relevant buttons call.
All my code is below. I am struggling as I am fairly new to JavaScript and I now I can do it by adding using Value but this doesn't work due to my image.
Edit Button HTML
<button type="button"class="btn btn-default" name="RegCashMove_Edit_Button" onclick='RegCashMoveEdit()'>
<span class="glyphicon glyphicon-pencil" title="Edit" style="vertical-align: middle"></span>
</button>
Create Button HTML
<button type="button" class="btn btn-default" name="RegCashMove_Create_Button" onclick='RegCashMoveCreate()'>
<span class="glyphicon glyphicon-plus"></span> Create
</button>
Variable Button HTML
This is the button I want the label to be variable on. At the moment its 'Submit'
<button name="RegularCashMovements_Submit_Button" class="btn btn-default" id="RegularCashMovements_Submit_Button" type="submit">
<span class="glyphicon glyphicon-ok"></span> Submit
</button>
JavaScript function for 'Create' button
function RegCashMoveCreate(txt) {
document.getElementById('selection').value = "Create";
document.getElementById('index').value = "";
document.getElementById('RCMViewState').value = "Initial";
document.getElementById('submitAndCancel').style.display = "block";
document.getElementById('editAndConfirm').style.display = "none";
document.getElementById('yesAndNo').style.display = "none";
document.getElementById('confirmTemplate').style.display = "none";
document.getElementById('createEditDeleteTopLine').style.display = "block";
document.getElementById('RegCashMoveHeading').innerHTML = "<h3>" + txt + "</h3>";
document.getElementById('RegCashMoveFields').style.display = "block";
document.getElementById('RegCashMoveDeleteConfirmation').style.display = "none";
document.getElementById('FromDiv').innerHTML = "<%=fromInnerHtml%>";
document.getElementById('ToDiv').innerHTML = "<%=toInnerHtml%>";
document.getElementById('AmountDiv').innerHTML = "<%=amountInnerHtml%>";
document.getElementById('FrequencyDiv').innerHTML = "<%=frequencyInnerHtml%>";
document.getElementById('FromErrorDiv').innerHTML = "";
document.getElementById('ToErrorDiv').innerHTML = "";
document.getElementById('AmountErrorDiv').innerHTML = "";
document.getElementById('FrequencyErrorDiv').innerHTML = "";
document.getElementById('RegCashMove_From_DropDownList').value = "- - Please select - -";
document.getElementById('RegCashMove_To_DropDownList').value = "- - Please select - -";
document.getElementById('RegCashMove_Amount_TextBox').value = "";
document.getElementById('RegCashMove_Frequency_DropDownList').value = "0";
};
JavaScript function for 'Edit' button
function RegCashMoveEdit(txt, from, to, amount, frequency, index) {
document.getElementById('selection').value = "Edit"
document.getElementById('index').value = index;
document.getElementById('RCMViewState').value = "Initial";
document.getElementById('submitAndCancel').style.display = "block";
document.getElementById('editAndConfirm').style.display = "none";
document.getElementById('yesAndNo').style.display = "none";
document.getElementById('confirmTemplate').style.display = "none";
document.getElementById('createEditDeleteTopLine').style.display = "block";
document.getElementById('RegCashMoveHeading').innerHTML = "<h3>" + txt + "</h3>";
document.getElementById('RegCashMoveFields').style.display = "block";
document.getElementById('RegCashMoveDeleteConfirmation').style.display = "none";
document.getElementById('FromDiv').innerHTML = "<%=fromInnerHtml%>";
document.getElementById('ToDiv').innerHTML = "<%=toInnerHtml%>";
document.getElementById('AmountDiv').innerHTML = "<%=amountInnerHtml%>";
document.getElementById('FrequencyDiv').innerHTML = "<%=frequencyInnerHtml%>";
document.getElementById('FromErrorDiv').innerHTML = "";
document.getElementById('ToErrorDiv').innerHTML = "";
document.getElementById('AmountErrorDiv').innerHTML = "";
document.getElementById('FrequencyErrorDiv').innerHTML = "";
document.getElementById('RegCashMove_From_DropDownList').value = from;
document.getElementById('RegCashMove_To_DropDownList').value = to;
document.getElementById('RegCashMove_Amount_TextBox').value = amount;
document.getElementById('RegCashMove_Frequency_DropDownList').value = frequency;
};
I no I should be able to add a variable in each of my JavaScript function to display the relevant label but my issue is getting it on the button with my image
You can set the textual content of a HTML element with the "textContent" property ("innerText" in IE < 9):
var button = document.getElementById('RegularCashMovements');
button.innerText = button.textContent = 'new text';
The span element inside the button element should not be removed.
If you also want to change the title of the span do it like that:
for (var index = 0; index < button.childNodes.length; index++) {
if (button.childNodes[index].tagName == 'SPAN') {
button.childNodes[index].title = 'new title';
break;
}
}
You need to iterate through all child nodes of the button, instead of taking the first one, because than you will get the text content of the button again.
I hope i understood your problem. I also have to say, that your javascript is very procedural and inperformant because of all the "display: none;" and innerHTML accesses. My tip for you would be to think more objective and put all elements you need to hide in one container element and hide that one.
I am trying to change text and icons with jquery. When you click at the button it changes, but when you click the button again it struggles. The icon and the text does not change back to default.
Code behind
string box = "<div class=\"alter-Wrp\"> <div class=\"alert alert-danger {0}\">{1}</div></div>";
if(count > 0)
litAlert.Text += String.Format(box);
asp.page
<button class="btn btn-dangerr btn-lg" type="button"><span class="glyphicon glyphicon-bell beee"></span>
<span class="text">Show Alarm</span> </button>
<asp:Literal ID="litAlert" runat="server"></asp:Literal>
Jquery
$('.btn-dangerr').click( function(e) {
var tgl = $('.btn-dangerr');
var box2 = $('.alter-Wrp');
var icon = $('.glyphicon');
var text = $('.text');
var toggleClass = '.beee';
icon.addClass('glyphicon-bell');
text.text('Show Alarm');
box2.slideToggle(function (){
if (tgl.hasClass(toggleClass)) {
icon.removeClass('glyphicon-bell').addClass('glyphicon-fire');
text.text('Hide Alarm');
} else {
e.preventDefault();
}
$('.btn-dangerr').toggleClass(toggleClass);
});
});
http://jsfiddle.net/w8Yjz/25/
Pretty sure this is what you're trying to do:
$('.btn-dangerr').click(function (e) {
$('.alter-Wrp').slideToggle();
$('.beee').toggleClass('glyphicon-bell glyphicon-fire');
if ($('.beee').hasClass('glyphicon-fire')) {
$('.text').text('Hide Alarm');
} else {
$('.text').text('Show Alarm');
}
});
Fiddle