Retrieve the name of a button created with innerHTML - javascript

I'm trying to retrieve the name of a button created using innerHtml. My problem is really simple to understand, and sure enough, to solve. Thanks in advance!
this is my code, adding a column to a dynamic table:
colonne1.innerHTML = '<td align="center"><input id=' +
button_id_is_id_plat+ ' type="button" name='+title+' value="Supprimer"
onclick="DeletePlat('+button_id_is_id_plat+')"></td>';
the name which contains the variable title, is what i'm looking to retrieve in my DeletePlat function. Here is what I've tried but with no positive results:
var my_array=document.getElementById("plat_action"); //the id of the dynamic table
var longueur = arrayLignes.length;
while(i<longueur)
{
//I retrieve the cell which contains a string
var cellule = my_array.rows[i].cells[0];
//I retrieve the cell which contains the button that I've created with innerHTML
var cellule2 = my_array.rows[i].cells[1];
//Here, I want to retrieve the name of the button embedded into my "cellule2" variable
if (cellule.innerText.toString()==cellule2.innerText.toString())
{
//treatment...
}
}
I've also tried cellule2.name.toString(), but, it seems that it ain't the solution too.

Here an example of what you could do in order to retrieve the name from a button html element:
let buttonElement = document.getElementById("button");
let name = buttonElement.getAttribute('name');
console.log(name)
<button name="buttonname" type="submit" value="HTML" id="button">HTML</button>

To rerieve the name of a button no need to call toString() function : just use the .name attribute of your DOM element :
console.log(document.getElementById("button").name);
<div id="div">
<button id="button" name="nameOfButton">Button</button>
</div>

Related

JavaScript- dynamically adding input to a page

i am using JavaScript to add a div on the fly. The div should contain a form input whose 'name' attribute WILL changes in value incrementally.
I have managed to do this- I however have two problems.
First Problem:
The first div that i created is cancelled out by the next dynamically created div.
thus, when i submit the form, the first dynamically created imput form is blank-
but subsequent ones have values on them.
MY CODE :
html
<div id="dynamicDivSection"></div>
<button id="addbutton">add box</button>
<div id="boxes">
<div class="box">
<input type="text" id='dynamic-imput' name="">
</div>
</div>
javascript
var addbutton = document.getElementById("addbutton");
var key = 1;
addbutton.addEventListener("click", function() {
key++;
document.getElementById('dynamic-imput').name = 'ser['+key+'][\'name\']';
var boxes = document.getElementById("boxes");
var head = document.getElementById("dynamicDivSection");
var clone = boxes.firstElementChild.cloneNode(true);
head.appendChild(clone);
});
i suspect that the problem is causing by this:
document.getElementById('dynamic-imput').name =
'ser['+key+'][\'name\']';
i.e when i create the dynamic div it creates several inputs on the page that contain the same Id. if i am correct, then perhaps teh solution is to change the Id of the newly created imput - however, i am not sure how to change the Id of a dynamically created Imput.
Second problem.
i want each dynamically created div to go to the top of the page; i.e to be placed before the earlier created dynamic div- however, at the moment each dynamically created div go directly under the first dynamically created div.
You can insert as the first child with:
parent.insertAdjacentElement('afterbegin', nodeToInsert);
You can get and set attributes such as id with setAttribute and getAttribute. Though I'm not sure why you even need an ID here, it would be simpler not to have one and select the element with a class.
var addbutton = document.getElementById("addbutton");
var key = 1;
addbutton.addEventListener("click", function() {
key++;
document.getElementById('dynamic-imput').name = 'ser['+key+'][\'name\']';
var boxes = document.getElementById("boxes");
var head = document.getElementById("dynamicDivSection");
var clone = boxes.firstElementChild.cloneNode(true);
var clonedInput = clone.firstElementChild;
clonedInput.setAttribute('id', clonedInput.getAttribute('id') + '-' + head.children.length);
head.insertAdjacentElement('afterbegin', clone);
});
<div id="dynamicDivSection"></div>
<button id="addbutton">add box</button>
<div id="boxes">
<div class="box">
<input type="text" id='dynamic-imput' name="">
</div>
</div>

Change value of <input> to include a superscript, using Javascript

The following code works correctly for me, in HTML.
<input type = "text" name = "var_1" id = "i_var_1" value = "x&sup8">
The following, using Javascript, also works:
<p id = "p1"><input type = "text" name = "var_1" id = "i_var_1" value = "0"></p>
<script....>
q1 = document.getElementById("p1");
q1.innerHTML = '<INPUT TYPE = "text" name = "var_1a" id = "i_var_1a" value = "x&sup8">';
</script>
However I need to add in the superscript when a button is pressed. So I have something like:
<p id = "p1"><input type = "text" name = "var_1" id = "i_var_1" value = "0"></p>
<input type = "button" id = "i_button" value = "Add the superscript" onclick="Add_Superscript()";>
<script.....>
function Add_Superscript()
{
q1 = document.getElementById("p1");
b1 = document.getElementById("i_var_1");
c1 = b1.value.toString() + "&sup8";
q1.innerHTML = '<INPUT TYPE = "text" name = "var_1a" id = "i_var_1a" value = c1.value>';
}
</script>
The above code does not reproduce the superscript properly.
Anyone any ideas? Thanks in advance for comments.
Not sure this is what you want, but it adds &sup8 to whatever is in the input box.
function Add_Superscript() {
q1 = document.getElementById("p1");
b1 = document.getElementById("i_var_1");
c1 = b1.value.toString() + "&sup8";
q1.innerHTML = '<INPUT TYPE = "text" name = "var_1a" id = "i_var_1a" value = "' + c1 + '">';
}
<p id="p1">
<input type="text" name="var_1" id="i_var_1" value="0">
</p>
<input type="button" id="i_button" value="Add the superscript" onclick="Add_Superscript()" ;>
I don't know what you're trying to do but maybe it's because of the c1.value ! Try:
q1.innerHTML = '<INPUT TYPE = "text" name = "var_1a" id = "i_var_1a" value =' + c1 + '>';
You have several typos in your code and a lot of unnecessary code as well. You just need to set up a click event handler on the button that populates the value of the pre-existing input. No need to create a new input.
A few notes:
When you were trying to create the new input element (which it turns out you don't need to do in the first place), you had the entire thing as a string. You need to inject the dynamic value into that string, by terminating the string, concatenating the new value in and then concatenating the closing of the string, like this:
q1.innerHTML = '<input type="text" name="var_1a" id="i_var_1a" value=' + c1.value + '>';
Next, it's best to use good naming conventions for elements and variables. Prefix an id and name with something that describes the "type" of thing the element is. Use btn (button), txt (textbox), chk (checkbox), rad (radio button), etc. And don't use _ (that's a very old convention). Instead use "camelCase". Further, with form elements, you need to give them a name for form submission purposes, but it is also a good idea to give them and id for CSS and JavaScript purposes. Use the same id that you used for name so that you don't have two different names for the same thing.
Lastly, don't configure your HTML elements to event handlers via HTML attributes (onclick, onmouseover, etc.). Doing this creates global anonymous functions that alter the this binding in the callback function, it creates "spaghetti code" that is hard to scale and debug and it doesn't follow the W3C DOM Event specification. Instead, do all the work in JavaScript and use .addEventListener() to connect functions to events.
// Get references to the relevant DOM elements
var btn = document.getElementById("btnGo");
var input = document.getElementById("txtInput");
// Set up a click event handling function
btn.addEventListener("click", add_Superscript);
function add_Superscript(){
// Create a new value that is the old value plus a "superscript" value
var newVal = input.value + "&sup8";
// Update the input with the new value:
input.value = newVal;
}
<p>
<input type="text" name="txtInput" id="txtInput" value="0">
</p>
<input type = "button" id="btnGo" value="Add the superscript">

Delete button next to each array's value

I have a HTML-JavaScript script in which the user can insert data to a new array [] by using a form's text field and an insert button.
By pressing insert button, the user inserts the data typed into the array.
I have a function which prints all the values of the array into <p id="demo"></p> and runs itself every 100 milliseconds in order to be updated with the arrays values.
I also have a reset button to delete every array's value when clicked.
What I want to do is add a delete button next to each array's value in order to be easier for the user to delete the wrong value he inserted.
I am using this code to insert values and print them:
HTML:
<div align="center">
<form id="form1">
<input type="text" name="fname" id="fname" placeholder="Type here!">
</form>
<br>
<input type="button" id="Button Insert" onclick="myFunction()" value="Insert">
<input type="button" onclick="myFunction3()" value="Reset">
</div>
<p id="demo" align="center"></p>
JavaScript/JQuery:
var all_values =[];
function myFunction() {
var temp_val = $("#fname").val();
all_values.push(temp_val);
document.getElementById("form1").reset();
}
setInterval(function () {
$("#demo").html(all_values.join("<br>"));
}, 100);
function myFunction3() {
all_values.length = 0;
}
To be more specific I want something like these things: iOS example JSFiddle Example 1 JSFiddle Example 2.
Could you please help me? Thanks in advance.
I'd do it the other way around.
Remove setInterval as it's really bad way to do such things.
Remove white spaces from the id attribute (id="Button-Insert", not id="Button Insert")
Don't use onclick attributes. Instead, register click event handlers with jQuery
// caching is a good practice when you reffer to the same elements multiple times:
var all_values =[], demo = $("#demo"), form = $("#form1")[0], fname = $("#fname");
$('#Button-insert').click(function(){
var temp_val = fname.val();
all_values.push(temp_val);
// create delete button along with the value
demo.append('<p>'+temp_val+' <button value="'+temp_val+'" type="button" class="del-btn">Delete</button></p>');
form.reset();
});
$('#Button-reset').click(function(){
all_values = [];
demo.html('');
});
// event delegation for dynamic elements:
demo.on('click', '.del-btn', function(){
all_values.splice(all_values.indexOf($(this).val()), 1);
$(this).parent().remove();
});
JSFiddle
Simply create the delete buttons at the same time you create the table.
function loadvalues(){
var i, button;
$('#demo').empty();
for(i in all_values){
$('#demo').append(all_values[i]);
button = $('<button>',{'text':'Delete'}).click(function(){
all_values.splice(this,1);
loadvalues();
}.bind(i)).appendTo('#demo');
$('#demo').append('<br>');
}
}
Also you don't need to poll, you could simply add each one on demand with a function like this:
function addVal(){
var val = $("#fname").val(), i = all_values.length;
all_values.push(val);
$('#demo').append(val);
button = $('<button>',{'text':'Delete'}).click(function(){
all_values.splice(this,1);
loadvalues();
}.bind(i)).appendTo('#demo');
$('#demo').append('<br>');
}
I had some typos, the code works,
Check here:
http://codepen.io/anon/pen/QbvgpW

editing dynamically generated table

I have a dynamically generated tables the foot of the table contain some text fields when click on save i want to add the value of text fields to the body of that table .
here is the table
<table border="1" class="entity_table">
<tfoot>
<tr>
<td>
<div class="pane1"></div>
<div class="pane2">
<input type="text" id="name"><br>
<select id="data">
<option value="1">int</option>
<option value="2">tinyint</option>
</select>
<br><span id="save">save</span>
</div>
</td>
</tr>
</tfoot>
<tbody class="table-body" id='myid'></tbody>
</table>
i did this but this is id specific ..i want to update that specific table on which it is clicked and edited .
var myName = document.getElementById("name");
var data = document.getElementById("data");
var Mtable = document.getElementById("myid");
var rowCount = Mtable.rows.length;
var mrow = Mtable.insertRow(rowCount);
var mcell = mrow.insertCell(0);
mcell.innerHTML = myName.value;
var mcell1 = mrow.insertCell(1);
mcell1.innerHTML = size.value;
i want to update each dynamically generated table with values that is entered in its table's foot section
You can use below jQuery :
$(function(){
$('#save').click(function(){
$(this).closest('table').find('tbody').append('<tr><td>'+$('#name').val()+' and '+$('#data').val()+'</td></tr>');
});
});
Demo
EDIT - to eliminate input and select box id dependency use below code :
$(function(){
$('#save').click(function(){
var name = $(this).closest('tr').find('input[type=text]').val();
var data = $(this).closest('tr').find('select').val();
$(this).closest('table').find('tbody').append('<tr><td>'+name+' and '+data+'</td></tr>');
});
});
Demo
So if I understood this right, you dont want to use element's ID to select it.
You have some else options if you dont want to work with elements IDs:
1) You can add them some data- attribute, for example: data-id. And based on this you select your element like this:
myElement.querySelector("[data-id='X']") where myElement is some parent element of your tables and X is their ID which you generated before (lets say it will start from 0 and will increment with every next table).
2) If possible, work with objects. When you create your tables, you either create them with raw text with defining html elements or you create new elements with calling createElement("table") on document keyword. If second option is your option, you can save this elements to some array (myTables in this case) and then approach this elements in a standard way - lets say:
myTables[0].getElementsByTagName("input")
Hope it helps your issue. Hope I understood issue you were asking about.

Obtain value from <span> attributes inside <td>

My vb.net program is generating a checkboxlist with several checkboxes. While building the checkboxes, I'm also setting a couple of Attributes. When the user clicks the box, I'm trying to access the values of the attributes in javascript.
The vb.net looks like this:
L = New ListItem
thisROLEn = "A"
L.Value = dr("apr_key")
L.Text = Trim(dr("apr_name"))
L.Attributes("Role" & thisROLEn) = Trim(dr("ROLE_DESC"))
L.Attributes("Title") = AppToolTip
AppList.Items.Add(L)
Here's what a TR section of the generated html looks like:
<tr>
<td>
<span RoleA="User" RoleB="Admin" Title="Approve access">
<input id="MainContent_AppList_0" type="checkbox" name="ctl00$MainContent$AppList$0" value="7" />
<label for="MainContent_AppList_0">Finance</label>
</span>
</td>
I can get the value of the checkbox just fine. My question is how do I access the value of "RoleA" from javascript?
Basic idea based off your comment.
var checkbox= document.getElementById("MainContent_AppList_0");
var span = checkbox.parentNode;
var isChecked = checkbox.checked;
var roleA = span.RoleA;
You can get the attribute value by getAttribute
document.getElementById('MainContent_AppList_0').parentNode.getAttribute("roleA")
As you mentioned you are able to access check box, based on that I have created a sample pseudo code here:
var a=document.getElementsById('ctl00$MainContent$AppList$0');
var b = a.parentNode;
var roleA = b.getAttribute('RoleA');
Hope it helps.

Categories