Appending a button onto an element and changing its attributes - javascript

Hey guys I'm making a little email app as a personal project for me and I had an issue when I'm appending a button element onto a div using Javascript.
Apparently, the button is displaying but it's almost invisible.
So I tried to change the value of it to "Archive" but it's remaining just a small sliver of a button that I can barely see.
How can I change the value of the button with javascript?
Thanks! Below is my code:
fetch('/emails/' + id)
.then(response => response.json())
.then(email => {
document.getElementById("message-view").innerHTML = "From: " + email.sender + "<p>To: " + email.recipients + "</p>" + "<p>Sent at: " + email.timestamp + "<p>Subject: " + email.subject + "</p>" + "<p>" + email.body + "</p>";
const archiveButton = element.appendChild(document.createElement('button'));
archiveButton.value = "Archive";
});

The value attribute doesn't set the button content. Use the textContent attribute instead : archiveButton.textContent = "Archive"

The value attribute works with input tags
Example :
<input type="button" value="Click Me">
In that case it would work
but if you had :
<button> Click Me </button>
It would not work.
You would have to use textContent or innerText
Example :
const button = document.querySelector("button")
button.textContent = "Archive"

Related

How to concatenate and pass parameters values in html using jQuery

I'm using jQuery to get values from ajax rest call, I'm trying to concatenate these values into an 'a' tag in order to create a pagination section for my results (picture attached).
I'm sending the HTML (divHTMLPages) but the result is not well-formed and not working, I've tried with double quotes and single but still not well-formed. So, I wonder if this is a good approach to accomplish what I need to create the pagination. The 'a' tag is going to trigger the onclick event with four parameters (query for rest call, department, row limit and the start row for display)
if (_startRow == 0) {
console.log("First page");
var currentPage = 1;
// Set Next Page
var nextPage = 2;
var startRowNextPage = _startRow + _rowLimit + 1;
var query = $('#queryU').val();
// page Link
divHTMLPages = "<strong>1</strong> ";
divHTMLPages += "<a href='#' onclick='getRESTResults(" + query + "', '" + _reg + "', " + _rowLimit + ", " + _startRow + ")>" + nextPage + "</a> ";
console.log("Next page: " + nextPage);
}
Thanks in advance for any help on this.
Pagination
Rather than trying to type out how the function should be called in an HTML string, it would be much more elegant to attach an event listener to the element in question. For example, assuming the parent element you're inserting elements into is called parent, you could do something like this:
const a = document.createElement('a');
a.href = '#';
a.textContent = nextPage;
a.onclick = () => getRESTResults(query, _reg, _rowLimit, _startRow);
parent.appendChild(a);
Once an event listener is attached, like with the onclick above, make sure not to change the innerHTML of the container (like with innerHTML += <something>), because that will corrupt any existing listeners inside the container - instead, append elements explicitly with methods like createElement and appendChild, as shown above, or use insertAdjacentHTML (which does not re-parse the whole container's contents).
$(function()
{
var query=10;
var _reg="12";
var _rowLimit="test";
var _startRow="aa";
var nextPage="testhref";
//before divHTMLPages+=,must be define divHTMLPages value
var divHTMLPages = "<a href='#' onclick=getRESTResults('"+query + "','" + _reg + "','" + _rowLimit + "','" + _startRow + "')>" + nextPage + "</a>";
///or use es6 `` Template literals
var divHTMLPages1 = `` + nextPage + ``;
$("#test").append("<div>"+divHTMLPages+"</div>");
$("#test").append("<div>"+divHTMLPages1+"</div>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"></div>

jQuery getJSON and get value from button

I'm download data from JSON file and display button with value:
function iterateOverPrzepisy(best) {
$('#listaPrzepisow').html('');
$.getJSON('przepisy.json', function(data) {
for (var x in przepisyDost) {
$('#listaPrzepisow').append(" <div data-role=\"collapsible\"><h2>" + przepisyDost[x].nazwa + "</h2>" +
"<ul data-role=\"listview\" data-theme=\"d\" data-divider-theme=\"d\">" +
"<li>" +
"<h3>Składniki: " + przepisyDost[x].skladniki + "</h3>" +
"<p class='ui-li-desc' style='white-space: pre-wrap; text-align: justify;'>" + przepisyDost[x].tresc + "</p>" +
"<button id='ulubioneBtn' value='" + przepisyDost[x].id + "'>Ulubione</button></li>" +
"</ul>" +
"</div>");
j++;
}
})
}
When I click to button #ulubioneBtn I would like to get value from this button. So I add done to getJSON
}).done(function(data){
$('button#ulubioneBtn').click(function (event) {
console.log("Ulubione: ");
event.preventDefault();
var id = $("button#ulubioneBtn").val();
console.log("Value: " + id);
//dodajemy do ulubionych
localStorage.setItem("ulubione"+id, id);
});
});
But it's not working. When I click on button Ulubione I always get in console log value = 0
The problem seems to be that you add multiple buttons with the same id. An id of a html element should be unique.
przepisyDost does not appear to be defined at
for (var x in przepisyDost) {
? Try
for (var x in data.przepisyDost) {
Duplicate id's are appended to document at
"<button id='ulubioneBtn' value='" + przepisyDost[x].id
+ "'>Ulubione</button></li>" +
within for loop. Try substituting class for id when appending html string to document
"<button class='ulubioneBtn' value='" + data.przepisyDost[x].id
+ "'>Ulubione</button></li>" +
You could use event delegation to attach click event to .ulubioneBtn elements, outside of .done()
$("#listaPrzepisow").on("click", ".ulubioneBtn", function() {
// do stuff
})
I have created a dummy JSON and executed the same JS with a single change.
In onclick handler instead of getting button I am using $(event.target).
And it is working fine.
Please find the fiddle https://jsfiddle.net/85sctcn9/
$('button#ulubioneBtn').click(function (event) {
console.log("Ulubione: ");
event.preventDefault();
var id = $(event.target).val();
console.log("Value: " + id);
//dodajemy do ulubionych
localStorage.setItem("ulubione"+id, id);
});
Seems like first object doesn't have any id value.
Please check JSON response returned from server.
Hope this helps you in solving.

How to add Call a phone number link in innerHTML

I am trying to add a call specific phone number using <a href> tag inside innerHTML. I've tried with double and single quotes.
1st Case is not firing at all.
2nd Case it does appear but when clicking on the phone number rather than dialing it closes.
var popDiv = document.createElement('span');
popDiv.setAttribute('class', 'popDiv');
popDiv.innerHTML ="It seems you are looking for: " + "<span style='color:#FF0000'>" + getTitle + "</span>" + "<br />" + "Why don't you call me?" + "<a href='tel:01234567890'>01234 567 890</a>";
Please find link to the JSFiddle
Does anyone know what a possible solution would be?
You need to check the mouseup event's target and if it's h1, then only remove the popDiv. This should work :
$("#"+parentContainerId).on('mouseup', function(e){
if(event.target.tagName.toLowerCase() === 'h1') {
$('span.selectedText').contents().unwrap();
$(this).find('span.popDiv').remove();
}
});
Updated jsFiddle
Just try with that :
var popDiv = document.createElement('span');
popDiv.setAttribute('class', 'popDiv');
popDiv.innerHTML ="It seems you are looking for: " + "<span style='color:#FF0000'>" + getTitle + "</span>" + "<br />" + "Why don't you call me?" + "01234 567 890";
and be sure you have not any meta like that :
<meta name = "format-detection" content = "telephone=no">

Replacing input with div, after replacing div with input

I replace a div with a text input so the user can edit the text. When the user hits enter, I want the text input to change back into a div with the edited text.
The problem I'm having I can't get the text input to change back into a div after pressing enter. I've tried replaceWith() and a number of combinations of JQuery functions that should do this, but I can't figure it out. Can anyone help?
Here is the div containing the comment text to be edited
<div id="comment-message-' + comment.id + '">' + comment_message + '</div>
The user clicks a link to edit the comment and the comment turns into a text input. This works fine
Edit Comment
This is the function that changes the comment into a text input. This works
function editComment(id) {
var t = $('#comment-message-' + id).text();
$('#comment-message-' + id).replaceWith('<form id="edit-comment-form-' + id + '" name="edit-comment-form-' + id + '" action="javascript:callAPI(' + id + ')"><input id="edit-comment-' + id + '" name="edit-comment-' + id + '" type="text" value="' + t + '"/></form>');
}
Using the Facebook API, I make the call. If there is no error, the text input changes into a div with the new comment. The API call here works, but the change from text input to div does not
function callAPI(id) {
var e = document.getElementById('edit-comment-' + id).value,
edit = { message: e };
FB.api('/' + id, 'POST', edit, function (response) {
if (response && !response.error) {
var comment = $('#comment-message-' + id),
form = $('#edit-comment-form-' + id); // forgot to add '#' here
comment.removeChild(form);
comment.html('<div id="comment-message-' + id + '">' + e + '</div>');
}
});
}
use below code to replace input type to div
FB.api('/' + id, 'POST', edit, function (response) {
if (response && !response.error) {
$('#edit-comment-form-' + id).replaceWith('<div id="comment-message-' + id + '">' + e + '</div>')
}
});
you alrady replace $('#comment-message-' + id) with input form so do same you need to replace $('#edit-comment-form-' + id) to $('#comment-message-' + id)

Stringifyed onClick event does not work

I have an event which parses a certain string which contains button name and url.
than I assign the data to a button. and add on click event which suppose to open url in a new window. But this on click event doe not work. The window does not show up. If url was wrong it would open a window and prompt a mistake.
But in my case when I click the botton it does not react. Probably something is wrong with on click event here: onclick=\"myWindow = window.open('partArray[1]', '', 'width=300,height=300');\". But I can't understand what.
here is the code
<script>
...
var checkType = partArray[0].split("+");
outPuts = outPuts + " <input type='button' class='WordDocType' name='" + partArray[0] + "' value='" + partArray[0] + "' onclick=\"myWindow = window.open('partArray[1]', '', 'width=300,height=300');\" /> "
document.getElementById("demo").innerHTML=outPuts;
</script>
<body>
...
<div id="demo"></div>
...
</body>
partArray[1] is not evaluated; the browser should still open window with the URL specified as "partArray[1]" but I doubt that is what you want. Try adding double quotes and concatenating it when you build your HTML.
outPuts = outPuts + " <input type='button' class='WordDocType' name='" + partArray[0] + "' value='" + partArray[0] + "' onclick=\"myWindow = window.open('" + partArray[1] + "', '', 'width=300,height=300');\" /> "
If you provide some more context or code it'd be easier to see what might be going on. Are you sure there is not a popup-blocker getting in the way?

Categories