Obtain value from <span> attributes inside <td> - javascript

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.

Related

Manipulating Text with JavaScript Based on Checkbox State

I'm trying to create a simple HTML page that presents a user with several options via checkboxes. I need to generate a string, stored in a variable that I can use on the page when a button is clicked, which will vary based on which boxes are checked.
The string will be a URL ("http://example.com/index.htm&term=") and will need to have additional text appended to it for each checkbox that is checked.
For example, if only a single box, say box1, is checked the string "box1" should be appended to the URL variable to look like "http://example.com/index.htm&term=box1"
If, however more than one box is checked, say box2 and box3 are checked, then the string "box2%20OR%20box3" should be appended to the URL string.
I'm pretty sure this can be done with JavaScript but I have no experience with it and would appreciate some guidance/examples.
Instead of storing it in a variable, I would recommend calling a function that builds the link when the button is pressed. If you really wanted to put it in a variable though, you would set up an event listener for the change event for each checkbox, and call the function to update the variable each time one of the checkboxes is checked or unchecked.
function checkboxUrl(checkboxes) {
const
url = `http://example.com/index.html`,
checkedArray = [];
for (let checkbox of checkboxes) {
if (checkbox.checked) checkedArray.push(checkbox);
};
const checkboxString = checkedArray.map(checkbox => checkbox.value).join(`%20OR%20`);
return url + (checkboxString ? `?term=` + checkboxString : ``);
}
let checkboxes = document.querySelectorAll(`input[type='checkbox']`);
label {
display: block;
}
<label><input type='checkbox' value='box1'>box1</label>
<label><input type='checkbox' value='box2'>box2</label>
<label><input type='checkbox' value='box3'>box3</label>
<button onclick='console.log(checkboxUrl(checkboxes))'>Get URL</button>
If you use Jquery you can do something like this:
<input type="checkbox" id="box1">
<input type="checkbox" id="box2">
<button type="button" id="myButton">Submit</button>
<script>
$(document).ready(function(){
$('#myButton').click(function(){
var url = 'www.myurl.com/index.html&term=';
var checkboxList = [];
var params = '';
$(':checkbox:checked').each(function(){
checkboxList.push($(this).attr('id'));
});
params = checkboxList.join('%'); //will output "box1%box2"
url += params //www.myurl.com/index.html&term=box1%box2
window.location.href = url;
});
});
</script>

How to create a radio button list with nametags from a javascript array

I have been trying to create an HTML radio button list from a list of cable that the user inputs himself. The data goes into a CableList array, which contains a list of objects with many properties including the name.
I want to create that list of radio buttons with the length of the CableList, and assign the names to the radio buttons.
I am perfectly familiar with the for loop concepts, I am however not familiar with the appendchild method I have seen other people use. I am fairly new to HTML/Javascript and any help would be greatly appreciated.
This is just some of my ideas, however it does not work at all and I have no idea what to do from there.
function createRadioList(CableList){
var c = document.getElementById("Canva");
var ctx = c.getContext('2d');
for (Cables in CableList) {
var Cable = document.createElement('input');
Cable.setAttribute('type', 'radio');
Cable.setAttribute('name', 'choice');
document.getElementById().appendChild(Cable);
}
}
My expected results are simply a list of radio buttons with the name attributes of the cable list attached to them.
EDIT:
Thank you everyone for the reply. Here is my current HTML file:
<!DOCTYPE html>
<!--Created by: Philippe Gauthier 04/2019-->
<html>
<head>
<script language="JavaScript" src="DrawCables.js"></script>
<script language="JavaScript" src="drawingFunctions.js"></script>
</head>
<body>
<h2>Cable drawing function</h2>
<canvas id = "Canva" width = "750" height="750"></canvas>
<canvas id = "Legend" width = "250" height="750"></canvas>
<form>
<input type="radio" id="AllCables" > Show all cables<br>
<script>createRadioList(CableList)</script>
</form>
<br>
<!-- Rectangular switch -->
Show cable names <input type="checkbox" id="CablenamesBox"><br>
Show axis <input type="checkbox" id="AxisBox"><br>
Show grid (NOT SETUP) <input type="checkbox" id="GridBox"><br>
<script>MakeLegend()</script>
<button onclick="InitializeDrawing()" type = "button">Draw Cables</button>
</body>
</html>
Relevant javascript code
function Singlecore(X,Y,totalradius,outerradius,innerradius,name){
this.Center = [X,Y];
this.TotalRadius = totalradius;
this.ConductorOuterRadiusList = outerradius;
this.ConductorInnerRadiusList = innerradius;
this.Type = "Singlecore";
this.Name = name;
}
//Creates a PipeType cable type object
//The X and Y position of sub-singlecores are relative to the center of the main pipe
function Pipetype(X,Y,totalradius,name){
this.InnerCablesList=[]
this.Center = [X,Y];
this.TotalRadius = totalradius;
this.Type="Pipetype";
this.Name=name
for (var n=0;n<(arguments.length-4);n++){
this.InnerCablesList=this.InnerCablesList.concat(arguments[n+4]);
}
}
//Global, could be reorganised / changed
function CreateCableList(){
//Creating objects and placing them in a list
var C1 = new Singlecore(0,0,350,[300,250],[275,0],"Cable1");
var C2 = new Singlecore(1000,2000,350,[300,250],[275,0],"Cable2");
var C3 = new Singlecore(20,-2000,350,[300,250],[275,0],"Cable3");
var C4 = new Pipetype(1000,-1000,100,"Cable4",new Singlecore(50,50,20,[15,5],[7,0]), new Singlecore(10,-5,15,[10,7],[8,0]));
var C5 = new Singlecore(2000,-100,500,[300,250],[275,0],"Cable5");
ListOfConductors = [C1,C2,C3,C4,C5];
return ListOfConductors
}
I made a mistake in my original post... I am not trying to print it on my canvas but rather on me HTML. I would like to have a result like this(example taken from web):
<form action="">
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other
</form>
Rather than having 3 set radio buttons, Im trying to have a radio button for each cables in the cable list, and assign the respective names of the object.
As for the cables in mistake in the for loop, I just recently discovered the technique and I wanted to try it. I now understand that it only applies for objects and not arrays.
Can't append HTML to canvas with JavaScript.
It's kind of unclear if you are trying to render the radio inputs inside a canvas. If so, that's not the way. Canvas doesn't accept rendering elements that way.
To solve your issue of generating radio inputs trough JavaScript, this is the way:
const container = document.querySelector("#Canva"),
createRadioInputs = (items) => {
items.forEach(i => {
let input = document.createElement("input"),
label = document.createElement("label");
input.setAttribute("type", "radio");
input.setAttribute("value", i);
input.setAttribute("name", i);
label.setAttribute("for", i);
label.innerText = i;
container.append(input);
container.append(label);
});
}
createRadioInputs(["Item1", "Item2", "Item3", "Totally different item"]);
Why innerText instead of innerHTML?:
In this cases, since you only have to append text and not HTML, innerText provides better performance since innerHTML has to parse the string you provide. innerText does not.
If you append directly inside of a <canvas> tag with JavaScript it won't show up, use a <div> instead.
<div id="Canva"></div>
If you want to try it out you can check this working fiddle.
Also, someone already answered to rendering HTML elements to canvas, take a look at this answer, it may help you if you still need to render them into a canvas.
EDIT:
My answer is adaptable to your code, but I'm going to think that you just don't know how to adapt it.
Here is a fiddle of the newer version of code in your question. Check it and tell me if that helps you. This is why you should've specified what you wanted since the beginning.
Add id and value to tag, which should work then.
function createRadioList(cables) {
var canvas = document.getElementById("Canva");
for (var i = 0; i < cables.length; i++) {
var radio = document.createElement('input');
radio.setAttribute('id', 'cable_' + i);
radio.setAttribute('type', 'radio');
radio.setAttribute('name', 'choice');
radio.setAttribute('value', cables[i])
var label = document.createElement('label');
label.setAttribute('for', 'radio_' + i);
label.setAttribute('title', cables[i]);
label.innerText = cables[i];
canvas.appendChild(radio);
canvas.appendChild(label);
}
}
createRadioList(['a', 'b']);

Which API I need to use instead of serializeArray to get the custom attributes of fields?

I'm using serializeArray() to retrive the form attributes. When I try to get the attributes, I'm receiving name and value for all the fields.
I have checked the documentation https://api.jquery.com/serializeArray/. I understood it will return the name and value of all the fields.
Now I have few custom attributes for some fields. I want to retrieve them using those custom attributes.
How can i achieve this?
Here is my logic.
var data = $('form').serializeArray();
var newData = {};
var queue = {};
data.forEach(function(field) {
if( field.customField != undefined && field.customField.indexOf("true")>=0 ) {
queue[field.name] = frm.value
} else {
newData[frm.name] = frm.value;
}
});
I need to get that customField attribute, I'm adding that to the HTML field attribute.
May not be the best, but you can do like this.
Let's say you have set of text boxes, text areas and so on with custom data attributes in it. What I am doing here is adding a class to those fields that you need to get value / data attributes in it.
Let's take the following HTML as an example.
HTML
<form id="frm">
<input class="serialize" type="text" name="title1" value="Test title 1" data-test1="test AAA" data-test2="test BBB" /><br/>
<input class="serialize" type="text" name="title2" value="Test title 2" data-test1="test CCC" data-test2="test DDD" /><br/>
<textarea class="serialize" data-test1="textarea test 1">TEST 22 TEST 11</textarea>
<button id="btn" type="button">Serialize</button>
</form>
What I am doing here is iterating through fields which has class .serialize and putting value, name, data attributes and so on to an array.
jQuery
$(document).ready(function(){
$('#btn').on('click', function(e) {
var dtarr = new Array();
$(".serialize").each(function(){
var sub = new Array();
sub['name'] = $(this).attr('name');
sub['value'] = $(this).val();
//data attribute example
sub['data-test1'] = $(this).data('test1');
sub['data-test2'] = $(this).data('test2');
dtarr.push(sub);
});
// This will give you the data array of input fields
console.log(dtarr);
});
});
Hope this helps.

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.

How to parse a variable in Javascript

I'm trying to use this code:
var field="myField";
vals[x]=document.myForm.field.value;
In the html code I have
<form name="myForm">
<input type='radio' name='myField' value='123' /> 123
<input type='radio' name='myField' value='xyz' /> xyz
</form>
But this gives me the error:
document.myForm.field is undefined
How can I get field to be treated as a variable rather than a field?
Assuming that your other syntax is correct (I havne't checked), this will do what you want:
var field="myField";
vals[x]=document.myForm[field].value;
In JS, the bracket operator is a get-property-by-name accessor. You can read more about it here.
Use the elements[] collection
document.forms['myForm'].elements[field]
elements collection in DOM spec
BTW. If you have two fields with the same name, to get the value of any field, you have to read from:
var value = document.forms['myForm'].elements[field][index_of_field].value
eg.
var value = document.forms['myForm'].elements[field][0].value
and, if you want to get value of selected radio-button you have to check which one is selected
var e = document.forms['myForm'].elements[field];
var val = e[0].checked ? e[0].value : e[1].checked ? e[1].value : null;
You have to do it like this:
var field = "myField";
vals[x] = document.myForm[field].value;
or even
vals[x] = document.forms.myForm.elements[field].value;
Based on your tags, it seems that you are using jQuery. If so, you can just do this and it will make your life much easier:
var vals = new Array();
$("form[name='myForm'] :radio").each(function() {
vals.push($(this).val());
});
:-D

Categories