Set an array of the checkbox values with another array of values - javascript

I have a set of input checkboxes on a form that look like this:
<input type="checkbox" value=""><span value="Atlanta">Atlanta</span>
<input type="checkbox" value=""><span value="Charleston">Charleston</span>
<input type="checkbox" value=""><span value="Chicago">Chicago</span> and etc.
The above is due to running this, $dataTable.ajax.reload(), and for some reason this erases the values of the checkboxes in my form. These checkboxes are not hardcoded and are being dynamically generating.
Instead of doing the below, I realize I can just refresh the page and get all the value back, but I'd like to see if there is another way to do what I'm trying to do below.
Anywho, I took the span text of each checkbox, turned that into an array and called it spanarr. I also turned the input checkboxes into an array, called emergcheck.
var emergspanarr = $('#emergencyForm span').toArray();
var spanarr = [];
var emergcheck = $('#emergencyForm input[type="checkbox"]');
emergspanarr.map(function(item){
spanarr.push(item.innerHTML.trim());
});
I'm trying to insert one span value (from spanarr) into each of input checkbox (from emergcheck).
What I have so far:
for (var j = 0; j < emergcheck.length; j++){
for (var k = 0; k < spanarr.length; k++){
emergcheck.attr("value", function(i, val){
return val + spanarr[k];
})
}
}
But it's producing this:
<input value="AtlantaCharlestonChicagoHouston (Sales)Houston (Terminal)Long BeachMarseillesMiamiMontreal....Santa Ana SavannahSeattleSecaucusTorontoVancouverAtlantaCharlestonChicagoHouston (Sales)Houston (Terminal)Long BeachMarseillesMiamiMontrealSanta Ana .....Santa AnaSavannahSeattleSecaucusTorontoVancouver" type="checkbox"><span value="Atlanta">Atlanta</span>
<input value="AtlantaCharlestonChicagoHouston (Sales)Houston (Terminal)Long BeachMarseillesMiamiMontreal....Santa Ana SavannahSeattleSecaucusTorontoVancouverAtlantaCharlestonChicagoHouston (Sales)Houston (Terminal)Long BeachMarseillesMiamiMontrealSanta Ana .....Santa AnaSavannahSeattleSecaucusTorontoVancouver" type="checkbox"><span value="Charleston">Charleston</span> and etc.
I want it to be this instead:
<input type="checkbox" value="Atlanta"><span value="Atlanta">Atlanta</span>
<input type="checkbox" value="Charleston"><span value="Charleston">Charleston</span>
<input type="checkbox" value="Chicago"><span value="Chicago">Chicago</span
I feel like I am close. What am I missing? In need of another pair of eyes. Thanks,

Just try to change code with below code -
JS Code -
for (var j = 0; j < emergcheck.length; j++){
emergcheck.eq(j).val(spanarr[j]);
}
Maybe it can help you.

I think you just want the value of the input. You can use .val() from jQuery or just .value as pure js.
jQuery way:
var emergspanarr = $('#emergencyForm span').toArray();
var emergcheck = $('#emergencyForm input[type="checkbox"]').toArray();
for (var j = 0; j < emergcheck.length; j++) {
emergcheck[j].val(emergspanarr[j].val());
}
Pure js way:
var emergspanarr = $('#emergencyForm span').toArray();
var emergcheck = $('#emergencyForm input[type="checkbox"]').toArray();
for (var j = 0; j < emergcheck.length; j++){
emergcheck[j].value = emergspanarr[j].value;
}

Related

How do I use getElementById on dynamically created inputs?

I'm having a some trouble getting the state of dynamically created checkboxes. I used the code below to add several checkboxes, with dynamic Id's, to the body.
var html = ...;
for(var i = 0; i < options.checkTextArray.length; i++)
{
html +=
`
<label class="checkbox" [attr.for]="'myCheckboxId' + i">
<input class="checkbox__input" type="checkbox" [name]="'myCheckboxName' + i" [id]="'myCheckboxId' + i">
<div class="checkbox__box"></div>${options.checkTextArray[i]}:
</label>
<br>
`;
}
In another part of the code, I would like to get and/or set the state of the checkboxes but havent succeeded so far. I tried using the code below to achieve my goals, but "document.getElementById(...)" keeps returning "null".
var ckbStateBuffer = new Array();
var txtContenBuffer = new Array();
for(var i = 0; i < options.checkTextArray.length; i++) {
ckbStateBuffer.push(document.getElementById("'myCheckboxId' + i").checked);
}
As you can see, I'd like to save the checkbox states in an array and use it, to reset the new states to the old ones (for example when a button is pushed).
So how should I be adding the states to this buffer array? What am I doing wrong in the code above? Tried several other things but none of those worked.
It looks like you just have a simple error in your code. What you're trying to do is something to the affect of:
id=myCheckboxName1
id=myCheckboxName2
id=myCheckboxName3
...
However, your code is not correct:
<input class="checkbox__input" type="checkbox" [name]="'myCheckboxName' + i" [id]="'myCheckboxId' + i">
It's interpreting the entire id as a string and not inserting the numeric value so it looks like this: myCheckboxIdi
Perhaps try the following:
var html = ...;
for(var i = 0; i < options.checkTextArray.length; i++)
{
var checkboxId = `myCheckboxId${i}`;
html +=
`
<label class="checkbox" [attr.for]=${checkboxId}>
<input class="checkbox__input" type="checkbox" [name]=${checkboxId} [id]=${checkboxId}>
<div class="checkbox__box"></div>${options.checkTextArray[i]}:
</label>
<br>
`;
}
Notice how the value is now inserted in the string via the template string? This should work, but I didn't run it so it may need some modification. Your new code for accessing would be something like:
var ckbStateBuffer = new Array();
var txtContenBuffer = new Array();
for(var i = 0; i < options.checkTextArray.length; i++) {
ckbStateBuffer.push(document.getElementById(`myCheckboxId${i}`).checked);
}
Something to this affect should fix your code. Let me know if you need more clarification.
Okay so I found a solution. Apparently you can't use getElementById(checkboxId) to get the checkbox states. You have to create an array using getElementsByTagName("input") and afterwards itterate through this array while checking for inputs of the checkbox type.
var inputsArray = document.getElementsByTagName("input");
var ckbStateBuffer = new Array();
for (var i = 0; i < 3; i++)
{
if(inputsArray[i].type == "checkbox")
{
ckbStateBuffer.push(inputsArray[i].checked);
}
}
JSFiddle here: https://jsfiddle.net/Maximo40000/agL9opq6/
A big thanks to Jarred Parr!

Add attribute to specific elements in JavaScript

I wish to add a new attribute to all of my elements that their type is text
Can you please let me know where I'm wrong?
Firstly, I identify all my elements that their type is text as follows (input tag name is the tag name that contains text types)
var inputs = document.getElementsByTagName('input');
Secondly, I add my attribute to those with text type
if (inputs.type =='text') {var att = document.createAttribute("class")}
Then when I want to check if the new attribute is added or not
inputs.hasAttribute("class");
I got this error
Uncaught TypeError: inputs.hasAttribute is not a function
document.getElementsByTagName('input');
returns an array like list instead of just one element. Therefore, this is what you should do:
var inputs = document.getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++){
if(inputs[i].type == 'text'){
inputs[i].classList.add("some", "class");
}
}
An even better way would be this:
// Only works in recent browsers
document.querySelectorAll("input[type=text]").forEach(function(ele){
ele.classList.add("some", "class");
});
Try this:
var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++){
if(inputs[i].type == 'text'){
var att = document.createAttribute("class");
att.value = "testClass";
inputs[i].setAttributeNode(att);
console.log(inputs[i].hasAttribute("class"));
}
}
<input type="text"/>
<input type="text"/>

Javascript change font color onclick

So I'm trying to change the font color of my entire page when I click on a radio button, like so:
<input type="radio" name="textcol" value="#FOF8FF" onclick = "changeText('#FOF8FF');"> Alice Blue<br>
Which then calls this function:
function changeText(col)
{
console.log(col);
console.log(document.getElementsByName('boyo'));
var abc = document.getElementsByName('boyo');
for(var i = 0, length = abc.length; i < length; i++)
{
abc[i].style.color = col;
}
}
And just so you're aware, within all my h3 and p tags (the only text within my document), I give them a name "boyo", like this:
<h3 name = "boyo">My favorite food</h3>
But for some reason, it does nothing. I know it has the proper elements (I print them out to console as you can see), and no errors occur, but my font color doesn't change. What the hell am I doing wrong?
EDIT: When I compare the value of just the string "#80FF08" to the value I pass (which when printed out is also the exact same), it returns FALSE that they're equal - how could this be? When I manually set the color it works.
Your code would work fine if you change the O to 0 in your color Code #FOF8FF
function changeText(col) {
console.log(col);
console.log(document.getElementsByName('boyo'));
var abc = document.getElementsByName('boyo');
for (var i = 0, length = abc.length; i < length; i++) {
abc[i].style.color = col;
}
}
<input type="radio" name="textcol" value="#FOF8FF" onclick='changeText("#F0F8FF")'>Alice Blue
<br>
<h3 id="colorMe" name="boyo">My favorite food</h3>
Its because #FOF8FF does not exist, try using #000 or any other color in place of #FOF8FF.
If you want to be clear more about it and inspect your element and try to give color: #FOF8FF, It want work either. For your reference I am attaching screen shot of this.
Change the color to other color working correct, seems like #FOF8FF is not a valid HEX value :
function changeText(color) {
console.log(color);
console.log(document.getElementsByName('boyo'));
var abc = document.getElementsByName('boyo');
for (var i = 0, length = abc.length; i < length; i++) {
abc[i].style.color = color;
}
}
<input type="radio" name="textcol" value="#FOF8FF" onclick="changeText('#33ccff');">Alice Blue
<br>
<h3 name="boyo">My favorite food</h3>
#FOF8FF doesn't exists change to O to 0 and i added different color code and it's working fine
function changeText(col)
{
console.log(col);
console.log(document.getElementsByName('boyo')[0]);
var abc = document.getElementsByName('boyo')[0].style.color = col;
}
<h3 name = "boyo">My favorite food</h3>
<input type="radio" name="textcol" value="#d2d2d2" onclick = "changeText('#d2d2d2');"> Alice Blue<br>

Run function on every table entry

I got a table that has an entry that looks like this:
<tr>
<td><input type="checkbox" name="ids[]"/><a style="cursor: pointer;" onclick="addtopath('parameter1', 'parameter2')" class="btn_addpath"> Add</a></td>
</tr>
As you can see every table entry countains the function "addtopath('parameter1', 'paramter2');"
The parameters are generated via php; so each item is different. Also, every entry has a checkbox. This is where the trouble occurs.
I want to create a function that runs the "addtopath" function for every table item, that is checked, as if the user clicked the "Add" button.
Hope it makes sense.
Modern browsers...
function runChecked() {
var links = mytable.querySelectorAll("input[name='ids[]']:checked + a.btn_addpath");
[].forEach.call(links, function(link) {
link.onclick();
});
}
IE8+...
function runChecked() {
var inputs = mytable.querySelectorAll("input[name='ids[]']");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked)
inputs[i].nextSibling.onclick();
}
}
IE6+...
function runChecked() {
var inputs = mytable.getElementsByTagName("input");
for (var i = 0, len = inputs.length; i < len; i++) {
if (inputs[i].name === "ids[]" && inputs[i].checked)
inputs[i].nextSibling.onclick();
}
}
I would add the parameters to data attributes in case you want to move to jQuery at some point. It's also good practice.
<td><input type="checkbox" data-one="one" data-two="two" class="btn_addpath"/>Add</td>
<td><input type="checkbox" data-one="three" data-two="four" class="btn_addpath"/>Add</td>
<td><input type="checkbox" data-one="five" data-two="six" class="btn_addpath"/>Add</td>
<td><input type="checkbox" data-one="seven" data-two="eight" class="btn_addpath"/>Add</td>
function addToPath(p1, p2) {
console.log(p1, p2);
}
var checkboxes = document.getElementsByClassName('btn_addpath');
var checkboxArr = [].slice.call(checkboxes);
checkboxArr.forEach(function (el) {
var p1 = el.getAttribute('data-one');
var p2 = el.getAttribute('data-two');
el.onchange = function () {
if (this.checked) { addToPath(p1, p2); }
};
});
If you use jQuery you can use the following code:
$("input[type=checkbox]:checked").siblings('a').click();
Test it at http://jsfiddle.net/tMe46/
This should emulate onClick event at all links in checked boxes
$("input[type=checkbox]:checked + a").click();

Multiple checkbox can't access from JavaScript function

I have dynamic multiple check boxes which is used to restore multiple files. It works perfectly when I have more than 1 check boxes. Here is my php code for check boxes:
<form name="RestoreFile">
<input type="checkbox" title="'.$FldDoc['FldDocumentName'].'" name="restore_checkbox" value="'.$FldDoc['FldDocumentID'].'" id="restore_'.$NodeId.'_'.$FldDoc['FldDocumentID'].'"/>
<input type="button" value="Restore" onclick="RestoreDocFile(\''.$NodeId.'\',this.form.restore_checkbox);" />
</form>
And the definition of function RestoreDocFile() is given below:
function getSelected(opt)
{
var selected = new Array();
var index = 0;
for (var intLoop = 0; intLoop < opt.length; intLoop++) {
if (opt[intLoop].checked)
{
index = selected.length;
selected[index] = new Object;
selected[index].value = opt[intLoop].value;
selected[index].index = intLoop;
}
}
return selected;
}
function RestoreDocFile(nodeid, opt)
{
var getSelectDocIds = getSelected(opt);
//alert(nodeid+','+getSelectDocIds);
var strSelectedDocIds = "";
var i=0;
for (var item in getSelectDocIds)
{
if(i!=0)
{
strSelectedDocIds+=":";
}
strSelectedDocIds += getSelectDocIds[item].value ;
i++;
}
}
The problem is that if there has 1 checkbox at the time of form load it doesn't work properly.
Try replacing
onclick="RestoreDocFile(\''.$NodeId.'\',this.form.restore_checkbox);"
with
onclick="RestoreDocFile(\''.$NodeId.'\',this.form.getElementsByName(\'restore_checkbox\'));"
This will ensure you get a NodeList regardless of how many checkboxes there are.

Categories

Resources