I'm trying to dynamically add a button with an onclick functionality to my table's cell but i seem to have a problem with my formatting.
My JS:
noteArrHelper = noteArr[i];
console.log(noteArrHelper);
cell2.innerHTML = "<button type=\"button\""+"onclick=deleteNote(\""+noteArrHelper+"\")"+">Delete";
cell2.className = "noteright";
And this is how it looks like in the browser:
<button type="button" "onclick="deleteNote("joyful="" test")"="">Delete</button>
But i want it to look like:
<button type="button" onclick="deleteNote("joyful test")">Delete</button>
I tried a few other ways of formatting but couldn't get it to work. Also the browser puts out the "joyful test" part correctly without any "=" between the words.
You can do so by simply changing third line in your JS code to the following:
cell2.innerHTML = "<button type=\"button\" onclick=\"deleteNote('"+noteArrHelper+"')\">Delete</button>";
Good luck :)
You can simply use Template literals (Template strings)
Live Demo:
//var
let noteArrHelper = 'joyful test'
//innerHTML
document.querySelector('#test').innerHTML = `<button type="button" onclick="deleteNote('${noteArrHelper}')">Delete</button>`;
//function
function deleteNote(str) {
console.log(str) //joyful test
}
<div id="test"></div>
U can use Template literals
cell2.innerHTML = `<button type="button" onclick=${deleteNote(noteArrHelper)} >Delete</button>`
You can try this mate
cell2.innerHTML = "<button type='button' onclick=\"deleteNote(\'" + noteArrHelper + "\')\">Delete</button>";
When you have to use quotes multiple time, then use single quotes and double quotes in your code
cell2.innerHTML = "<button type='button'onclick='deleteNote('+noteArrHelper+')'>Delete</button>";
Related
This is driving me insane.
I create a cell in a table dynamically through:
tr.append("<td>" + countryArr[i].ISO_id + "</td>");
I created a button that when clicked calls a function with the value countryArr[i].ISO_id. This value is a string and needs to be called in "quotes".
I cannot get the function to be called with quotes.
I've tried:
tr.append("<td><button type='button' onclick='showCyclists(" + cId + ")'>Show country's cyclists</button></td>");
tr.append("<td><button type='button' onclick='showCyclists("" + cId + "")'>Show country's cyclists</button></td>");
tr.append("<td><button type='button' onclick='showCyclists('" + cId + "')'>Show country's cyclists</button></td>");
None of these work. Please help
With ES6 you you could just use the following called template literals, note the backticks `
tr.append(`<td><button type='button' onclick='showCyclists("${cId}")'>Show country's cyclists</button></td>`);
Just add escaped quotes showCyclists(\"" + cId + "\"):
tr.append("<td><button type='button' onclick='showCyclists(\"" + cId + "\")'>Show country's cyclists</button></td>");
You can't use single quotes because those are being used to delineate the attribute. You could use escaped double quotes to get this to work:
tr.append("<td><button type='button' onclick='showCyclists(\"" +
cId +
"\")'>Show country's cyclists</button></td>");
However, while it is possible to get your approach to work by manipulating the strings, the solution you are trying to use here (inline event handlers, and furthermore, inline event handlers created from JavaScript strings) is a bad practice.
Save yourself some headaches and build up the elements properly. Your code might be a few lines longer, but it will be cleaner.
Good approach:
var button = $('<button type="button">')
.text("Show country's cyclists")
.on('click', function () { showCyclists(cId) });
var td = $('<td>').append(button);
tr.append(td);
Working example:
function showCyclists(id) {
console.log("Here are all the cyclists.");
console.log(id);
}
var tr = $('tr');
var cId = '12345';
var button = $('<button type="button">')
.text("Show country's cyclists")
.on('click', function() { showCyclists(cId); });
var td = $('<td>').append(button);
tr.append(td);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr></tr>
</table>
I have a JSP containing JavaScript function.Within that I created an inner html code.That contain a button with onClick function.When clicking the button I want to pass 2 parameters to the the function of JavaScript. But I can't get the 2 values properly.Please help me
Thank you
<script type="text/javascript">
function find(){
var i=0;
var servicetypevalue="SERVICE";
var td7= document.createElement("td");
td7.innerHTML='<input type="button" value="View Status" class=button name="ptBtn" id="ptBtn" onClick="getStatus('i,servicetypevalue');">';
}
function getStatus(i,servicetypevalue){
alert("enter");
}
</script>
I want to show the enter alert.But the parameter values are not properly passed.
td7.innerHTML='<input type="button" value="View Status" class=button name="ptBtn" id="ptBtn" onClick="getStatus(' + i + ',' + servicetypevalue + ');">';
use string concatenation as given above.
If your'e going to generate your own elements in JS, it's different than jQuery. While in jQuery you can make strings into valid markup reliably, but JS is not as sophisticated. Yes you can make an element by innerHTML, but it's error prone. The procedure to accomplish what you want in plain JS is as follows:
#1. Create an element.
#2. Append element to a parent.
#3. Add attributes to element.
The way your code is, it wouldn't work because your'e skipping #2. .td7 is never appended on the DOM and if the innerHTML of .td7 was rendered, it might succeed that'd be wierd. Instead of using an inline event which limits you, addEventListener gives you much better control and is more manageable. Also your getStatus just alerts "enter" which doesn't prove that your 2 parameters actually were passed. I added another alert as proof that the parameters were passed.
var i = 0;
var servicetypevalue = "SERVICE";
var host = document.querySelector('body');
var td7 = document.createElement('td'); //#1
var ptBtn = document.createElement("button"); //#1
host.appendChild(td7); //#2
td7.appendChild(ptBtn); //#2
ptBtn.className = "button"; //#3
ptBtn.name = "ptBtn"; //#3
ptBtn.id = "ptBtn"; //#3
ptBtn.innerHTML = "View Status"; //#3
function getStatus(i, servicetypevalue) {
alert("enter");
alert("i: " + i + "\nservicetypevalue: " + servicetypevalue)
}
ptBtn.addEventListener('click', function(event) {
getStatus(i, servicetypevalue);
}, false);
window.load = find;
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
</body>
</html>
Try to replace
td7.innerHTML='<input type="button" value="View Status" class=button name="ptBtn" id="ptBtn" onClick="getStatus('i,servicetypevalue');">';
to
td7.innerHTML='<input type="button" value="View Status" class=button name="ptBtn" id="ptBtn" onClick="' + "getStatus('i','servicetypevalue'" + ');">';
How to add id attribute of an element in HTML as a variable which is declared above in javascript.
jQuery
var table_row = $('table').find('tr#'+pid);
var name = table_row.find('td:nth-child(1)').html();
table_row.find('td:nth-child(6)').html('<button type="button" id="what to write here" class ="save_db")>save</button> ');
I want to set id as name.
Thanks
It can be done using simple string concatenation as follows:
var table_row = $('table').find('tr#'+pid);
var name = table_row.find('td:nth-child(1)').html();
table_row.find('td:nth-child(6)')
.html('<button type="button" id="'+name+'" class ="save_db">save</button> ');
PS: Also note that your markup contained a seemingly unnecessary closing brace after class attribute. I've removed it in my code.
So you just want a variable inserted into the html string?
table_row.find('td:nth-child(6)').html`(
'<button type="button" id="' + name + '" class ="save_db">save</button> '
)`;
Concatenate name variable to the appending string as ID.
table_row.find('td:nth-child(6)').html('<button type="button" id="'+ name + '"
class ="save_db")>save</button>');
Please follow this code:
table_row.setAttribute("id", "id_you_like");
Please try with the below code snippet.
Let me know if i am not understand your question.
var id = "btn1";
var table_row = $('table').find('tr#'+pid);
var name = table_row.find('td:nth-child(1)').html();
table_row.find('td:nth-child(6)').html('<button type="button" id="'+id+'" class ="save_db")>save</button> ');
Have you tried this? Try using this:
<button type="button" id='"+name+"' class= "save_db">
I have a problem with complicated JS determination of exact item:
this PHP/SQL code:
$prod = array();
$vys = mysqli_query($db,"SELECT * FROM produkty ORDER BY nazev");
while ($arr = mysqli_fetch_assoc($vys)) {
$prod[$arr['id_typu']][] = "<option value='".$arr['id_produktu']."'>".$arr['nazev']."</option>";
$polozky[$arr['id_typu']]= '<select name=idp[]>' . implode(' ', array_values($prod[$arr['id_typu']])) . '</select>';
}
this JS code:
<script type=\"text/javascript\">
function polozky(divName, typ){
var newdiv = document.createElement('div');
newdiv.innerHTML = \" $polozky[1] \"
document.getElementById(divName).appendChild(newdiv);
}
</script>
and this HTML code:
<form method='post'><fieldset>
<button type='button' name='typ' value='1' onclick=\"polozky('dynamicInput', '1');\">Add produkty from cathegory 1</button>
<button type='button' name='typ' value='2' onclick=\"polozky('dynamicInput', '2');\">Add produkty from cathegory 2</button>
<button type='button' name='typ' value='3' onclick=\"polozky('dynamicInput', '3');\">Add produkty from cathegory 3</button>
<div name='dynamicInput'></div>
</fieldset></form>
The problem is, that for each cathegory I want to generate (for every value of button) its own content. Using that $polozky[1-3] I'm querying the database for the right items of that cathegory (for items WHERE id_type=value in bracket). And I can't imagine that for 100 cathegories, I need to manually insert 100 times $polozky[1-100]. There must be some trick to do this. Somehow to store the value or some usage of that parameter (i was thinking of some $num=typ inside of the JS branch, but it's not possible due to the different processing type of JS and PHP).
Do you know, what to do please? ;) Thank you
Try this
<script type=\"text/javascript\">
document.getElementsByTagName("button").onclick = function() {
var newDiv = document.createElement('div');
newDiv.innerHTML = this.innerHTML; //Puts text from button inside new Div
document.getElementById('divId').appendChild(newDiv);
}
</script>
I think this is what you are looking for. When a button is clicked you want to have a function that executes that will take the current text enclosed by the button, add it to a newly created div and append that to the page. You also need to give your last div an ID of "divId".
Im trying to use inner html and dynamically set an onclick statement that contains a variable:
cell5.innerHTML="<input type='button' value='Remove' onclick='removerow('manual_" + (num) + "')' />"
So lets say the num variable was set to 4. The output should be onclick="removerow('manual_4')"
Any help?
The best thing would be to avoid all this:
var input = document.createElement('input');
input.type = 'button';
input.value = 'Remove';
input.onclick = function() {
removerow('manual_' + num);
};
cell5.appendChild(input);
Depending on the relationship between the button, the cell and the row to be removed, you could also do DOM traversal inside the handler to get a reference to the row.
You can escaped nested quotes using \:
"...onclick=\"removerow('manual_" + (num) + "')\"..."
cell5.innerHTML='<input type="button" value="Remove" onclick="removerow(\'manual_' + (num) + '\')" />'
You can escape the quotes using \
So
onclick=\"removerow('manual_" + (num) + "')\"
Consider using a click event instead. It makes that sort of thing clearer:
$(".cell5") // whatever selector you want
.html('<input type="button" value="Remove"/>')
.click(function(){
removerow('manual_' + row);
});
Also consider using the row number as the input instead of a string. If they all have the same form you can simplify things with just:
removerow(row);
Clearly that is an API design decision, but it would simplify this expression if it makes sense.