onclick passing on value of button - javascript

I want to send to my onClick function, the value of the button that pressed on it.
I have this function
numfunc = function (val) {
var t = document.createTextNode(val);
document.body.appendChild(t);
};
I have 5 buttons. I want them all to use this function onClick, but each send a different value,
their value.
var one = document.createElement("input");
one.type = "submit";
one.onclick = numfunc;
one.value = "1";
var two = document.createElement("input");
two.type = "submit";
one.onclick = numfunc;
two.value = "2";
and so on....
I'm trying to do this, on javascript not on the html file.
Thanks!

You can use this.value to get value inside you function numfunc, you don't need to send parameter, check example bellow.
Hope this helps.
numfunc = function (val) {
var t = document.createTextNode(this.value);
document.body.appendChild(t);
};
var one = document.createElement("input");
one.type = "submit";
one.onclick = numfunc;
one.value = "1";
var two = document.createElement("input");
two.type = "submit";
two.onclick = numfunc;
two.value = "2";
document.body.appendChild( one );
document.body.appendChild( two );

Can you use this code instead?
one.addEventListener("click", function () {
numfunc(this.value);
}, false);
two.addEventListener("click", function () {
numfunc(this.value);
}, false);

Related

how to pass an onclick method to a radio button created using Javascript?

I am creating a radio button using makeRadioButton function, here I am passing the name and value, I also tried passing the name of a function the same way, and it doesn't seem to work. Please help me how to pass a function to a newly created radio button.
function makeRadioButton(name, value, text) {
var label = document.createElement("label");
var radio = document.createElement("input");
radio.type = "radio";
radio.name = name;
radio.value = value;
**radio.onclick = "createDropdown()";**
label.appendChild(radio);
label.appendChild(document.createTextNode(text));
return label;
}
Try setting onclick to directly be the function createDropdown:
function makeRadioButton(name, value, text) {
var label = document.createElement("label");
var radio = document.createElement("input");
radio.type = "radio";
radio.name = name;
radio.value = value;
radio.onclick = createDropdown;
label.appendChild(radio);
label.appendChild(document.createTextNode(text));
return label;
}
function createDropdown(event) {
console.log("createDropdown");
};
document.body.appendChild(makeRadioButton("radio", null, "radio"));
Your code works fine you just have to append your returned value to the document.
Try this example below
function makeRadioButton(name, value, text) {
var label = document.createElement("label");
var radio = document.createElement("input");
radio.type = "radio";
radio.name = name;
radio.value = value;
radio.onclick = createDropdown;
label.appendChild(radio);
label.appendChild(document.createTextNode(text));
return label;
}
let lable = makeRadioButton("myRadio", null, "How old are you");
document.body.append(lable);
function createDropdown(){
console.log("CLICKED");
}

Pass contextual variable to onclick event handler as argument

*This is happening inside a larger block of code, in a for loop. See end of post for entire loop.
I've read all of the posts that seem to be about this subject, but I'm still lost.
I'm trying to assign an onclick event to a checkbox. The function being assigned to the onclick event needs to have access to a variable that is available in the scope where the checkbox is defined (idvariable).
var idvariable = parentChildList[i].children[j]["subjectid"];
var input = document.createElement("input");
input.type = "checkbox";
input.value = "";
input.onclick = function () {
return clicked(idvariable);
};
function clicked(id) {
alert(id);
};
I've tried every variation of inline and named functions, but I can't figure out how to give the clicked function access to idvariable. In this example above, the value of that variable is undefined.
Or, if I try it with this way:
var input = document.createElement("input");
input.type = "checkbox";
input.value = "";
var idvariable = parentChildList[i].children[j]["subjectid"];
input.onclick = function (idvariable) {
return clicked(idvariable);
};
function clicked(id) {
alert(id);
};
I get an alert that says [object MouseEvent]. Same with the following where I removed the () from the method name I'm assigning to the onclick event:
var idvariable = parentChildList[i].children[j]["subjectid"];
input.onclick = function () {
return clicked;
}(idvariable);
function clicked(id) {
return alert(id);
};
*entire loop:
for (var i = 0; i < parentChildList.length; i++) {
var row = table1.insertRow(-1);
var cell = row.insertCell(0);
cell.innerHTML =
"<h4 class=\"panel-title\"><a data-toggle=\"collapse\" data-parent=\"#accordion\" href=\"#collapse" + i + "\">" + parentChildList[i]["title"] + "</a></h4>";
if (parentChildList[i].children.length > 0) {
var row2 = table1.insertRow(-1);
var cell2 = row2.insertCell(0);
var table2 = document.createElement("table");
table2.className = "collapse";
table2.id = "collapse" + i;
cell2.appendChild(table2);
for (var j = 0; j < parentChildList[i].children.length; j++) {
var row3 = table2.insertRow(-1);
var cell3 = row3.insertCell(0);
var div = document.createElement("div");
div.className = "checkbox";
var label = document.createElement("label");
label.innerText = parentChildList[i].children[j]["title"];
var input = document.createElement("input");
input.type = "checkbox";
input.value = "";
input.setAttribute('subj', idvariable);
var idvariable = parentChildList[i].children[j]["subjectid"];
alert(idvariable);
input.onclick = function () {
return clicked(this.getAttribute('subj'));
};
function clicked(id) {
return alert(id);
};
cell3.style.padding = "0px 0px 0px 10px";
cell3.style.fontsize = "x-small";
cell3.appendChild(div);
div.appendChild(label);
label.insertBefore(input, label.childNodes[0]);
}
}
}
onclick handler receives Event object. If a handler attached as elem.onclick=handler then the element is available inside the handler as this. So this is workaround.
var idvariable = parentChildList[i].children[j]["subjectid"];
var input = document.createElement("input");
input.type = "checkbox";
input.value = "";
input.setAttribute('data-subj', idvariable);
input.onclick = function () {
return clicked(this.getAttribute('data-subj'));
};
function clicked(id) {
alert(id);
};
You will have to append the checkbox to some existing element first, using the following code.
var element = document.getElementById("one").appendChild(input);
Then you can get the parent by using something like the following...
var x = document.getElementById("someId").parentElement;
where x will contain the parent element.
This link https://stackoverflow.com/a/9418326/886393 is about custom data in an event (custom event). Hope that helps.
Thanks
Paras

Javascript: How to implement the "enter/return key" to save a value?

Sorry, I am not really good with JS.
The code is essentially the user double clicks on the text, textbox appears, changes text, and saves a new value. However, I want the user to be able to also click enter to save the new value.
In addition, if possible, to have a dedicated "Save" button to save the new value and "discard" to keep the old value.
Also, if I double click many times, the text appears as "(input type="text")". Is there a way to remove that?
Please help if you can.
The HTML + JS code
<html>
<head>
<script type="text/javascript">
window.onload = function() {
var elements = getElementsByClassName('text-edit', '*', document);
for(var i = 0; i < elements.length; i++) {
elements[i].ondblclick = function() {
this.setAttribute('oldText', this.innerHTML); // not actually required. I use this just in case you want to cancel and set the original text back.
var textBox = document.createElement('INPUT');
textBox.setAttribute('type', 'text');
textBox.value = this.innerHTML;
textBox.onblur = function() {
var newValue = this.value;
this.parentNode.innerHTML = newValue;
}
this.innerHTML = '';
this.appendChild(textBox);
}
}(i);
}
function getElementsByClassName(className, tag, elm) {
var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
var tag = tag || "*";
var elm = elm || document;
var elements = (tag == "*" && elm.all) ? elm.all : elm.getElementsByTagName(tag);
var returnElements = [];
var current;
var length = elements.length;
for(var i = 0; i < length; i++) {
current = elements[i];
if(testClass.test(current.className)) {
returnElements.push(current);
}
}
return returnElements;
}
</script>
</head>
<div><span class="text-edit">Some text</span></div>
</html>
The snippet below allows you to modify the value of a textbox using save button or enter key and discarding any changes using cancel button.
<!-- HTML -->
<h1 id="editable">Lorem Ipsum</h1>
// JavaScript
window.onload = function(){
var h1 = document.getElementById('editable');
h1.onclick = function(){
var old = this;
var input = document.createElement("INPUT");
input.type = "text";
input.value = this.innerHTML;
input.onkeyup = function(e){
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) {
old.innerHTML = input.value;
input.parentNode.replaceChild(old, input);
save.parentNode.removeChild(save);
cancel.parentNode.removeChild(cancel);
}
};
this.parentNode.replaceChild(input, this);
var save = document.createElement("INPUT");
save.type = "button";
save.value = "Save";
(function(old, input){
save.onclick = function(){
old.innerHTML = input.value;
input.parentNode.replaceChild(old, input);
this.parentNode.removeChild(this);
cancel.parentNode.removeChild(cancel);
};
})(old, input);
input.parentNode.insertBefore(save, input.nextSibling);
var cancel = document.createElement("INPUT");
cancel.type = "button";
cancel.value = "Cancel";
(function(old, input){
cancel.onclick = function(){
input.parentNode.replaceChild(old, input);
this.parentNode.removeChild(this);
save.parentNode.removeChild(save);
};
})(old, input);
input.parentNode.insertBefore(cancel, input.nextSibling);
};
};
Working jsBin

Not working with Edit Button in Javascript

I'm Creating an Edit button that will edit my data in my row. the problem is if I click multiple edit button it doesn't comply.
It only complies when I click 1 edit button.
HERE IS MY EXAMPLE : http://jsfiddle.net/te2wF/31/
HERES MY CODE
function editRow(t)
{
var i = t.parentNode.parentNode.rowIndex;
var table = document.getElementById('myTable');
if ( table.rows[i].cells[3].childNodes[0].value =="Edit")
{
var name = table.rows[i].cells[0].innerHTML;
var age = table.rows[i].cells[1].innerHTML;
var gender = table.rows[i].cells[2].innerHTML;
var tname = table.rows[i].cells[0];
var tage = table.rows[i].cells[1];
var tgender = table.rows[i].cells[2];
tname.innerHTML = "";
var textname = document.createElement("input");
textname.id = "textname";
tname.appendChild(textname);
tage.innerHTML = "";
var textage = document.createElement("input");
textage.id = "textage";
tage.appendChild(textage);
tgender.innerHTML = "";
var textgender = document.createElement("select");
textgender.id = "textgender";
tgender.appendChild(textgender);
document.getElementById('textname').focus();
document.getElementById("uid").innerHTML = i;
document.getElementById("textname").value = name;
document.getElementById("textage").value = age;
textgender.options.add(Option(gender));
if(gender == "Male") textgender.options.add(new Option("Female"));
else textgender.options.add(new Option("Male"));
table.rows[i].cells[3].childNodes[0].value="Save"
document.getElementById("name").disabled = true;
document.getElementById("age").disabled = true;
document.getElementById("gender").disabled = true;
document.getElementById("insert").disabled = true;
}
else
{
update(document.getElementById('uid').innerHTML);
table.rows[i].cells[3].childNodes[0].value="Edit"
document.getElementById("insert").disabled = false;
}
}
Thank you for helping.....
you should change:
textgender.options.add(Option(gender));
to
textgender.options.add(new Option(gender));
But more to the point on the edit button:
You're attempting to access the editable inputs on your table by id - but when you create a second set of textname and textage inputs, the id's are the same as the other row that you're editing. You either need to create unique id's on these elements (perhaps by appending the row number to the id), or you need to set it up so that you can only edit one row at a time (disable and grey the other rows when you're editing one)
Please, when using jsfiddle, please keep javascript on javascript tab and html on html tab to make it easier and faster to help you.
I believe you should adjust 2 places on your code:
First
document.getElementById('textname').focus();
document.getElementById("uid").innerHTML = i;
document.getElementById("textname").value = name;
document.getElementById("textage").value = age;
textgender.options.add(Option(gender));
should be
document.getElementById('textname').focus();
document.getElementById("uid").innerHTML = i;
document.getElementById("textname").value = name;
document.getElementById("textage").value = age;
textgender.options.add(new Option(gender));
Second:
else
{
update(document.getElementById('uid').innerHTML);
table.rows[i].cells[3].childNodes[0].value="Edit"
document.getElementById("insert").disabled = false;
}
should be:
else
{
update(document.getElementById('uid').innerHTML);
table.rows[i].cells[3].childNodes[0].value="Edit"
document.getElementById("name").disabled = false;
document.getElementById("age").disabled = false;
document.getElementById("gender").disabled = false;
document.getElementById("insert").disabled = false;
}
try here http://jsfiddle.net/te2wF/31/

Removing a newly created element in JavaScript with creating a button

I have added a <p> to a <div> by this code and made a button, too.
var selectedId = this.value;
var divElem = $("#selectedItem");
var bElem = document.createElement("Button");
var bElemInnerHTML = document.createTextNode("Erase");
bElem.addEventListener('click', function () {
remove(this.value);
}, true);
bElem.appendChild(bElemInnerHTML);
var pElem = document.createElement("p");
var pElemInnerHTML = document.createTextNode(this.value);
pElem.setAttribute('id', selectedId);
alert(pElem.getAttribute('id'));
pElem.style.fontSize = '25px';
pElem.style.textAlign = 'center';
pElem.style.margin = '5px';
pElem.appendChild(pElemInnerHTML);
pElem.appendChild(bElem);
divElem.append(pElem);
I add to the button to run the remove function when clicked on
function remove(id){
var emad = document.getElementById(id);
emad.parentNode.removeChild(emad);}'
but it doesn't work.
bElem.addEventListener('click', function () {
remove(this.value);
}, true);
this.value in the above context refers to the Button element's value property(which is a string), not the ID of the Button. Also, you haven't defined the ID, so this.id would return ""(an empty string)
bElem.addEventListener('click', function () {
remove(this.id);
}, true);
You can modify remove() to accept an Object instead:
function remove(btn){
emad.parentNode.removeChild(btn);
}
bElem.addEventListener('click', function () {
remove(this);
}, true);

Categories

Resources