How to pass 2 arguments to a Javascript function - javascript

I am working with HTML and Javascript.
I want to pass 2 arguments to the signUp function. I do not know where to put the comma between two arguments. Please help me!
Below is my code:
cellAction.outerHTML = "<input type='button' value='Approve' class='approve' onclick='signUp( \""+childData.email+"\"+\""+,childKey+"\" )'></td>";
Thanks in advance!

You do not need any + and quotes:
cellAction.outerHTML = "<input type='button' value='Approve' class='approve' onclick='signUp(childData.email, childKey)'></td>";
Demo:
var childData = {email: 'aa#xy.com'};
var childKey = 'k123';
var cellAction = document.getElementById('cellAction');
cellAction.outerHTML = "<input type='button' value='Approve' class='approve' onclick='signUp(childData.email, childKey)'></td>";
function signUp(email, key){
console.log(email + " :: " + key);
}
<div id="cellAction"></div>

You can use template literals
cellAction.outerHTML = `<input type='button'
value='Approve'
class='approve'
onclick='signUp(${childData.email},${childKey})'>
</td>`;

Related

I cant edit(splice) a specific index in my array through DOM, using a function

So i would like to change a specific index for eg "Lisa", and i want to do this through my DOM that i've created. As you can see i'm using a loop to get each <tr> and <td> out as a table. What im also doing is giving each of them an id='edit"+[i]+"' i've tried to combine each array with each id since they're always looping together.
var people = ["Olle", "Lisa", "Kalle", "Elin", "Johan", "Linda"];```
function listNames(){
varMyinnerHTLM = "<table class='nametable table table-dark table-hover'>";
varMyinnerHTLM += "<tbody>";
varMyinnerHTLM += "<tr><th>Namn</th></tr>";
for(i=0;i<people.length;i++){ //Loopar ut arrayens namn som en lista.
varMyinnerHTLM += "<tr><td><a href='#'>"+people[i]+"</a><button type='button' id='edit"+[i]+"' class='close' aria-label='Close'onClick='edit()'><span aria-hidden='true'>✏</span></button><button id='close"+[i]+"' type='button' class='close' aria-label='Close' onClick='removeRow()'><span aria-hidden='true'>×</span></button></td></tr>";
}
varMyinnerHTLM + "</tbody>";
varMyinnerHTLM += "</table>";
varMyinnerHTLM += "<input type='text' id='newname' class='nameinput input-group-text' placeholder='Namnet på personen'></br>";
varMyinnerHTLM += "<button type='button' id='addName' class='btn btn-primary' onClick='addName()'>Lägg till</button>";
varMyinnerHTLM += "<button type='button' id='reset' class='btn btn-light' onClick='reset()'>Nollställ</button>";
varMyinnerHTLM += "<button type='button' class='hide btn btn-success' onClick=''>Godkän</button>";
document.getElementById("jspage").innerHTML = varMyinnerHTLM;
}
So what im trying to achieve is that i want to be able to edit a specific index in my array through a onClick = "function()" type of way. The value has to be given in the input and then the function edit() will continue with the following down below:
var fullid = people[i] + edit[i]
function edit(){
nameValue = document.getElementById('newname').value;
if(nameValue === ""){
$('.nameinput').attr('style', "border-raidus: 5px; border:#C21414 1px solid;");
$('#newname').attr('placeholder', "Ange nytt namn").placeholder();
}else{
people.splice(fullid, 1, nameValue);
return listNames();
}
}
Maybe its obvious or not, but i think my people.splice(fullid, 1, nameValue); is way wrong but might be wrong. Because at the moment it only edits the first index of my array which is Olle when i want to edit Lisa eg.
I hope it was clear enough to understand my motives. I'd like to solve it in javascript but it also works if its with jquery.
Change the edit() function so it takes the array index as a parameter. And there's no need to use splice() if you're just changing 1 element, just assign to the array index.
function edit(i){
nameValue = document.getElementById('newname').value;
if(nameValue === ""){
$('.nameinput').attr('style', "border-raidus: 5px; border:#C21414 1px solid;");
$('#newname').attr('placeholder', "Ange nytt namn").placeholder();
}else{
people[i] = nameValue;
listNames();
}
}
Then change the HTML so you pass i as an argument to the function.
varMyinnerHTLM += "<tr><td><a href='#'>"+people[i]+"</a><button type='button' id='edit"+[i]+"' class='close' aria-label='Close'onClick='edit(" + i + ")'><span aria-hidden='true'>✏</span></button><button id='close"+[i]+"' type='button' class='close' aria-label='Close' onClick='removeRow()'><span aria-hidden='true'>×</span></button></td></tr>";
I'm not sure why you're returning something from edit(), the return value isn't used for anything. And listNames() doesn't return anything. Just call listNames() without using return.

join two html block variables in javascript

I am trying to join two blocks of html code with javascript and call a dialog afterwards. I have done some research and tried concat and + but that doesnt work. Here is a simplified version of my code:
var html =
"<div class=\"dialog-form\" title=\"Edit\">" +
"<form class=\"insertaplato\" method=\"POST\" action=\"edit.php\">" +
"<fieldset>" +
"<label>Plate: </label> <input type=\"text\" value=\"" + plate + "\" >" +
"<label>Price: </label><input type=\"text\" value=\""+ price +"\" >";
"Spicy: <br> ";
if (spicy==1)
{var varP=
"<label> Yes </label><input value= \"yes\" type=\"radio\" checked>"+
"<label> No </label><input value=\"no\"><br><br>";
} else {
var varP=
"<label> Yes </label><input value=\"yes\" type=\"radio\">"+
"<label> No </label><input value=\"no\" checked type=\"radio\"><br><br>";
}
var html2 = "<br>"+
"<br><input id=\"insert\" type=\"submit\" value=\"Edit\" name=\"send\"> " +
"</fieldset>"+
"</form>"+
"</div>";
var div = $(html)+$(varP)+$(html2);
div.dialog(
{
title:"Edit Plate",
close: destroy_this_dialog
});
As it is right now the dialog doesnt come up. If I do this with only the first html variable it come up Ok but when I try to add or concatenate the others nothing happens. I am evidently not using these variables as I should. Any ideas?
Concatenate the strings and not the jQuery objects
var div = $(html + varP + html2);
div.dialog(
{
title:"Edit Plate",
close: destroy_this_dialog
});
Remove the $ where you're appending the pieces together. You want to append the strings into a single object.
var div = $(html + varP + html2);
intead of
var div = $(html)+$(varP)+$(html2);
div.dialog(
{
title:"Edit Plate",
close: destroy_this_dialog
});
try this:
var div = html+varP+html2;
$('.dialog-form').dialog(
{
title:"Edit Plate",
close: destroy_this_dialog
});

Adding a button with innerHTML property

I'm trying to add html code inside a <span id="options"></span> so I'm trying to use this:
function editTextArea(element) {
var options = document.getElementById("options");
options.innerHTML = options.innerHTML + "Cols: <input type='text' id='colsTextArea' maxlength='3' /><br>Rows: <input type='text' id='rowsTextArea' maxlength='2' /><br><button type='button' onclick='updateTextArea('" + element.id + "')' >Add</button><br>";
}
But this is what I got,
<button type="button" onclick="updateTextArea(" textarea0')'="">Agregar</button>
My problem is with the quotes, so I later tried using createElement("button"), but now I can't add the onclick attribute.
I'm not using jQuery, so it would be nice to have a solution without it.
You need to use different quotes for the function call to updateTextArea than you do for the onclick attribute. You can't do onclick='alert('hi');', because the single quote terminates the onclick attribute.
function editTextArea(element) {
var options = document.getElementById("options");
options.innerHTML = options.innerHTML + "Cols: <input type='text' id='colsTextArea' maxlength='3' /><br>Rows: <input type='text' id='rowsTextArea' maxlength='2' /><br><button type='button' onclick='updateTextArea(" + '"' + + element.id + '"' + ")' >Add</button><br>";
}
You should definately consider doing this at least with the proper DOM API calls. You are right to try document.createElement
To set an onclick, do something like this:
var button = document.createElement('button').
button.onclick = function(){
alert('I was clicked');
}
Can be done with escaping the quotes also:
options.innerHTML = options.innerHTML + "Cols: <input type='text' id='colsTextArea' maxlength='3' /><br>Rows: <input type='text' id='rowsTextArea' maxlength='2' /><br><button type='button' onclick=\"updateTextArea(\'" + id + "\')\" >Add</button><br>";
if you are going with second option you can use setAttribute() method.
var ele = document.createElement('button');
ele.setAttribute('onclick','method_name');

unable to split string in jquery

<table border="0" class="commentbox">
<tr>
<td>
<div id="comment-f78d0b00-a008-473d-b647-a4a103ee3778"></div>
<input type="button" class='btnReply' id="reply-f78d0b00-a008-473d-b647-a4a103ee3778" value="Reply"/>
</td>
</tr>
</table>
$(".commentbox .btnReply").live("click", function () {
// $(this).hide();
// i = 1;
id = $(this).attr("id").split("-")[1]
alert(id);
var strDiv =
"<input type='text' class='txtCmnt' id='txtReply-" + id + "' />
<input type='button' class='btnSave' value='Save' id='btnSave-" + id + "' /> ";
$("#comment-" + id).append(strDiv);
});
i want the f78d0b00-a008-473d-b647-a4a103ee3778 to come after split rather alert is giving
f78d0b00
I have tried to change id = comment_ f78d0b00-a008-473d-b647-a4a103ee3778 and split
id = $(this).attr("id").split("_")[1],but it doesnt work.
Edited
Input - container-f78d0b00-a008-473d-b647-a4a103ee3778
Output after split f78d0b00-a008-473d-b647-a4a103ee3778
A slightly convoluted means of achieving your end-result:
// splits the supplied string by the hyphen '-' character
var string = 'comment-f78d0b00-a008-473d-b647-a4a103ee3778'.split(/-/);
// removes the zeroeth/first element from the string array
string.shift();
// joins the remaining elements from the string back together
var newString = string.join('-');
console.log(newString);​
JS Fiddle demo.
Edited to turn the above into a function:
function splitString(haystack, needle){
if (!needle || !haystack){
return false;
}
var string = haystack.split(needle);
string.shift();
return string.join(needle);
}
// the first argument is the string you want to work on,
// the second is the character you want to split on
// f is the variable that will hold the new string
var f = splitString('comment-f78d0b00-a008-473d-b647-a4a103ee3778','-');
console.log(f);​
JS Fiddle demo.
References:
join().
shift().
split()
If the format of the string is not going to change then how bout using the substring function instead?
var str = "comment-f78d0b00-a008-473d-b647-a4a103ee3778";
var subStr = str.substring(str.indexOf("-") + 1);
alert(subStr);
This returns: f78d0b00-a008-473d-b647-a4a103ee3778
Here s a jsfiddle for the same
http://jsfiddle.net/M2Ywy/
If it works for you then your code would look like this
var id = $(this).attr("id");
var subStr = id.substring(str.indexOf("-") + 1);
alert(subStr);
var strDiv =
"<input type='text' class='txtCmnt' id='txtReply-" + id + "' /> <input type='button' class='btnSave' value='Save' id='btnSave-" + id + "' /> ";
$("#comment-" + subStr).append(strDiv);
Demo jsFiddle
This should do it:
var id = '';
var strDiv = '';
$(".btnReply").live("click", function () {
// $(this).hide();
// i = 1;
id = $(this).prev('div').attr("id").split("comment-")[1];
alert(id);
strDiv = "<input type='text' class='txtCmnt' id='txtReply-"+ id +"' /><input type='button' class='btnSave' value='Save' id='btnSave-"+ id +"' />";
$("div[id*="+id+"]").append(strDiv);
});
You can do it this way, might be a longer version, but just 3 lines strong.
Just split() the string via the hyphens "-" and then splice the first index and then rejoin the whole string using the join() method
example: http://jsfiddle.net/eE48z/
$(document).ready(function(){
$(".commentbox .btnReply").click(function(){
var jid = $(this).attr("id").split("-");
jid.splice(0,1);
var id=jid.join("-");
alert(id);
var strDiv = "<input type='text' class='txtCmnt' id='txtReply-" + id + "' /><input type='button' class='btnSave' value='Save' id='btnSave-" + id + "' /> ";
$("#comment-" + id).append(strDiv);
});
});

jquery incrementing number in html name=""

I want the variable inputname to go up by 1 every time a new <input /> is added
e.g.
<input name="1" />
<input name="2" />
<input name="3" />
---html---
<p class="add">Add</p>
<div class="added"></div>
---jQuery/javascript---
$(document).ready(function() {
$("p.add").click(function() {
var inputname = somevar;
var added = "<input type=\"text\" name=\""+inputname+"\" />";
$("div.added").append(added);
});
});
here it is on jsfiddle.net if it helps -> http://jsfiddle.net/gamepreneur/54kzw/
Set inputname like this:
var inputname = $('.added input').length + 1;
This gets the total number of added inputs and increments by one, resulting in the new name.
Change the variable scope
Use this:
// declare your variable here so it exists throughout every call, instead of being
// delcared new with every call.
var inputname = somevar;
$(document).ready(function() {
$("p.add").click(function() {
var added = "<input type=\"text\" name=\""+(inputname++)+"\" />";
$("div.added").append(added);
});
});
Alternatives:
Grab the number of inputs ($('div.added input').length) and use that for a counter.
Grab the id of the last item $('div.added input:last').prop('name')) and increment it.
You need to declare inputname in the global scope so that it lasts longer than just the duration of the click function and then you need to increment it each time you use it.
I modified your fiddle to this: http://jsfiddle.net/jfriend00/54kzw/2/
var inputname = 1;
$(document).ready(function() {
$("p.add").click(function() {
var added = "<input type='text' name='" + inputname++ + "' />";
$("div.added").append(added);
});
});
Try
$(document).ready(function() {
$("p.add").click(function() {
var inputname = $('input', $("div.added")).length + 1;
var added = "<input type=\"text\" name=\"" + inputname + "\" />";
$("div.added").append(added);
});
});
Consider adding some other selectors to choose those inputs (like a class selector)

Categories

Resources