I have an HTML page which contains table rows like
<tr id="tp1">
<input type="checkbox" id="tc_">
</tr>
<tr id="tp2">
<input type="checkbox" id="tc_">
</tr>
The page contains input elements other than checkboxes as well
I have to change the values of all checkbox's id from tc_ to tc_1 ,tc_2 and so on.
I have thought of doing it as below
function startup(){
for(var i=0;i<3;i++)
{
var elem=document.getElementById("tp"+i);
var str=elem.innerHTML;
str.replace(/tc_,'tc_'+i); // how do I correctly use the arguments here?
elem.innerHTML=str;
//alert (""+str);
}
}
Thanks.
It isn't valid to have non-unique IDs in the first place. Any chance you can fix how the checkboxes are rendered so you don't have to do this?
That being said, I wouldn't do this by manipulating the HTML attributes. I would instead do this by manipulating the DOM properties of those input checkboxes:
// keep track of the current "new" checkbox ID suffix
var checkBoxIndex = 0;
for (var i = 0; i < 3; i++) {
// find the table row
var elem = document.getElementById("tp" + i);
// get the input elements within that row
var inputs = elem.getElementsByTagName("input");
// for each of the input elements...
for (var j = 0, k = inputs.length; j < k; j++) {
// if it's not a checkbox, skip it
if (inputs[j].type.toLowerCase() !== 'checkbox') {
continue;
}
// Alas, give the checkbox a new, unique ID
inputs[j].id = "tc_" + (checkBoxIndex++);
}
}
Also, hopefully you get an answer for your other question. This is a terrible workaround and I would hate to see it in production code.
The trick here is to select all the input elements of your rows using the appropriate CSS selector, then modify their ids:
function startup() {
for (var i = 0; i < 3;i++) {
var elem = document.getElementById("tp" + i);
var l = elem.querySelectorAll('td > input'); // Select "input"s in "td"s
Array.prototype.forEach.call(l, function (e, j) { // Apply to each element obtained
e.id = 'tc_' + j; // Modify the id
});
}
}
There's several good answers above but if you still want to change the id from tc_ to tc_ + i then you can do it like this.
<body>
<button id="tc_">1</button>
<button id="tc_">2</button>
<button id="tc_">3</button>
<script type="text/javascript">
for(var i=0;i<3;i++)
{
document.getElementById("tc_").id="tc_"+i;
}
</script>
</body>
Honestly though you shouldn't be doing it like this despite the fact this code works as other users have said it isn't valid to have non-unique id's.
Related
I got a grid view which has dynamic columns and i want to assign a hidden field to the columns which contains the same name.
This loop creates the columns of the grid view
for (var i = 0; i <= days; i++) {
$('<td>' + result1[i] + '</td>').appendTo($('#trr'));
}
and i want to add this same date 2019-12-02 to every column it creates as a hidden field
<input type="hidden" value="2019-12-02" class="th-hidden-date" />
I have no idea of doing this..
If anyone got any idea ,it would be so helpful for my project.
Much appreciated..
can i access the class when it loops and create the hidden field.
Just add result[i] as the value to your input. And append that input inside the td.
Check below
EDIT : if you want to get the values of the inputs later on see the edited snippet
var result = ['2019-12-02', '2020-02-25', '1970-01-01']
for (var i = 0; i < result.length; i++) {
var input = `<input type="hidden" value=${result[i]} class="th-hidden-date" />`
$('<td>' + result[i] + input + '</td>').appendTo($('#trr'));
}
// to get the values of the inputs later on
$('#trr input').each(function() {
console.log ($(this).val())
});
#trr td {
border:1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr id="trr"></tr>
</table>
Try below solution
for (var i = 0; i <= days; i++) {
$('<td>' + result1[i] + '<input type="hidden" style="display:none;" value="2019-12-02" class="th-hidden-date" />' +'</td>').appendTo($('#trr'));
}
Add your hidden input in your td and get it's value whenever you want.
I'm new to all this and I really need help. I've been on this for hours now.
I have these checkboxes. I'm using a cfoutput to generate them and giving them each the value of SID from the query.
<cfoutput query="getvalues">
<div><input type="checkbox" name="chk" id=#getvalues.SID# value=#getvalues.SID# class="chkbxs">
</cfoutput>
<input type="button" name="PrintSelected" value="Print Selected" onclick="printTextArea()">
The only thing I want to do is get the values of these checkboxes and store them in an array. getElementsByClassName returns an html collection. I've been told I need to loop over the html collection and then store the values in a new array which is what I attempted below but this isn't working.
<script type="text/javascript">
function printTextArea() {
var myList = document.getElementsByClassName("chkbxs");
var newList = [];
for (var i = 0; i < myList.length; i++) {
newList.push(myList[i].value);
}
for (var j = 0; j < newList.length j++)
{
alert (newList[j]);
}
}
</script>
Any help would be appreciated.
Why are you setting the array items to console.log(myList[i].value);?
console.log() just returns undefined.
Just change the line to following:
newList[i] = myList[i].value;
Hey guys I have a form which is stated below
<td><input type="text" id="NumberofRisks" name="Yeses" style="width: 25px" value ="<?php echo $row['Total-Score'];?> " </td>
The form has some data from a table as a value and I would like to take this value into my Javascript from to do a simple calculation. The function is listed below.
function sum()
{
sumField = document.getElementById("NumberofRisks");
var sum = 0;
$("input[name^='yanswer']:checked").each(function(){
sum++;
});
sumField.value = sum;
}
I need to get that value into the function as the value where it says NumberofRisks. Is there a way I can do this?
Try this to set sum to the initial value of #NumberofRisks.
var prevCheckedCount = 0;
function sum()
{
var sumField = document.getElementById("NumberofRisks");
// start sum with the inital value in HTML from DB
var valueOnClick = Math.floor(sumField.value);
var thisCheckedCount = 0;
$("input[name^='yanswer']:checked").each(function(){
thisCheckedCount++;
});
if(thisCheckedCount <= prevCheckedCount) {
sumField.value = valueOnClick - prevCheckedCount + thisCheckedCount;
} else {
sumField.value =valueOnClick + thisCheckedCount;
}
prevCheckedCount = thisCheckedCount;
}
Here's this code working: http://jsfiddle.net/t5hG4/
In order to grab the value of the input box you can use the following javascript:
var sum = document.getElementById("NumberofRisks").value;
Is this what you're trying to achieve?
As a side note, in the example you provided you did not close the input box so that might be giving you some errors as well.
EDIT:
If you're looking for a pure Javascript way to do this see below:
var elements = document.getElementsByTagName('input');
var sum = document.getElementById("NumberofRisks").value;
for (var i = 0; i < elements.length; i++) {
if (elements[i].checked) {
sum++
}
}
See fiddle - http://jsfiddle.net/es26j/
I have created 50 textareas with names def1,def2,def3.....,def50. In my body onLoad() function,I want the same value is set in all these textboxes.
Instead of writing the code 50 times, How can I write some Javascript code to set the value of the textarea, ie in a loop?
I suggest to read the MDC JavaScript guide, as loops and string concatenation are fairly basic operations:
for(var i = 1; i < 51; i++) {
var nameOfTextarea = 'def' + i;
// ...
}
I would give your textboxes ID's (not just names) if possible, and then do something like the following:
var namePrefix = "def";
for(var i = 1; i <= 50; ++i)
{
var textbox = getElementById(namePrefix + i);
// do something to textbox number i.
}
Try jquery for this:
<input type="text" id="t1"/>
<input type="text" id="t2"/>
<input type="text" id="t3"/>
The Jquery code:
var arr = [ "t1", "t2", "t3" ];
jQuery.each(arr, function() {
$("#"+this).val("hello");//$("#" + this).text("hello");
});
Here is the working demo
Try this.
var textareas = document.getElementsByTagName("textarea");
for(var i=0;i<textareas.length;i++){
if(textareas[i].id.indexOf("def") == 0){
textareas[i].value = textareas[i].id;
}
}
You can use tagname property but it will not work if you have some more textbox anywhere else in your page
function loader(){
for(var i=0;i<50;i++)
document.getElementsByName("def"+i)[0].value='Any Value';
}
I have a SELECT in a FORM.
This select is populated using js.
I need to add a "Selected" attribute to one of these options.
I get which one, by checking a MySql database to see the name of the community which needs to have a "selected attribute" added to it.
<select name="community" id="community">
//OPTIONS HERE
</select>
The filler() function:
function filler(com){
//com is the options which needs to be selected, this variables value comes from the mysql database
var community = document.getElementById("community");
var area = document.getElementById("area").value;
// area is just another input on the page which value also is fetched from mysql db. Each area has x communities, so I have alot of IF:s.
if(area == 'Blekinge') {
community.length = 6;
community.options[0].value = "Välj Kommun";
community.options[0].text = "-- Välj Kommun --";
community.options[0].id = "Välj Kommun";
community.options[1].value = "Karlshamn";
community.options[1].text = "Karlshamn";
community.options[1].id = "Karlshamn";
community.options[2].value = "Karlskrona";
community.options[2].text = "Karlskrona";
community.options[2].id = "Karlskrona";
community.selected = 0;
}
}
As you can see, "com" variable is the option which needs to have the "selected" attribute added to it.
I have over 30 of these if-statements, and I have no clue how to create a function to add this "Selected" attribute to the matching option.
So I have "com" which for example could be "Karlskrona" in the example above. How should I add the selected to it?
I need a simple function for this which works in all major browsers...
Set the selectedIndex property of the SELECT to whichever index you need. Zero-based, of course.
Just do
community.value = com;
example at http://www.jsfiddle.net/jMapA/
for(var i = 0; i < community.options.length; i++) {
if(community.options[i].id == com)
community.selectedIndex = i;
}
function selectOptionValue(selectId, value)
{
select = document.getElementById(selectId);
if (select)
{
for (var i = 0; i < select.options.length)
{
if (select.options[i].value == value)
{
select.options[i].selected = 'selected';
return true;
}
}
}
return false;
}
Use my function like this:
selectOptionValue('community', 'Karlskrona');