Not able to replace checkboxes Javascript - javascript

I am creating a mozilla add on for a web page. Using the attached Javascript code I am able to create checkbox. The checkbox should replace with other checkbox depending on the selected value in dropdown. Onclick on dropdown I am calling fun_sub_cat function which is creating checkbox and also replacing but it replace only once. For eg: If there are 2 option in dropdown 1 and 2, Selecting option 1 checkbox values should 1,2,3 and for option 2 checkbox values should be a,b,c.
On Click function it creates checkbox and changing the value for the first time replaces the checkbox value as well however when I click 3rd time on dropdown or change the value, it does not work. It attains the 2nd time changed checkbox values.
var k = 0;
function fun_cat_sub() {
console.log("Value Changed");
var Myarry = "";
if(document.getElementById('sub_cat').value == 'Password Reset'){
Myarry = check_list1;
if(k == 0){
console.log("creating checkbox for the first time");
k = k+1;
for (var i = 0; i < Myarry.length; i++) {
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.id = "checkBox"+i;
checkbox.value = Myarry[i];
checkbox.class = "_class";
checkbox.appendAfter(br_3);
var lab_chk = document.createElement('label');
lab_chk.innerHTML = Myarry[i];
lab_chk.id = "lab_chk"+i;
lab_chk.value = Myarry[i];
lab_chk.style.marginLeft = "10px";
lab_chk.appendAfter(checkbox);
document.createElement('br').appendAfter(lab_chk);
}
}
else if(k != 0){
console.log("I am in 1st Loop");
checking(Myarry);
}
}
else {
Myarry = check_list2;
console.log("I am in 2nd Loop");
checking(Myarry);
}
}
function checking(Myarry){
console.log(Myarry.length);
for (var i = 0; i < Myarry.length; i++) {
var old_chk = document.getElementById('checkBox'+i);
var new_chk = document.createElement("input");
new_chk.type = "checkbox";
new_chk.id = "checkBox"+i;
new_chk.value = Myarry[i];
old_chk.parentNode.replaceChild(new_chk, old_chk);
var old_lab_chk = document.getElementById('lab_chk'+i);
var new_lab_chk = document.createElement('label');
new_lab_chk.innerHTML = Myarry[i];
new_lab_chk.style.marginLeft = "10px";
old_lab_chk.parentNode.replaceChild(new_lab_chk, old_lab_chk);
}
}

Related

Unable to edit input field added via javascript

I have a simple table with cells. When the user clicks on a cell, a textbox is added inside the cell where they can edit the content. However, when i double click a cell to edit it's content, the attributes of the input field show up. It does not allow me to edit and add another value. Here is the script I'm using.
window.onload = function() {
var cells = document.getElementsByTagName("td");
var theads = document.getElementsByTagName("th");
for (let i = 0; i < cells.length; i++) {
cells[i].addEventListener("click", function() {
highlightCell(i);
});
}
function highlightCell(x) {
var txtBox = document.createElement("input");
txtBox.id = "myTxt";
txtBox.type = "text";
for (var i = 0; i<9; i++) {
if (i == x) {
txtBox.value = cells[i].innerHTML;
cells[i].innerHTML = "";
cells[i].appendChild(txtBox);
cells[i].style.backgroundColor = "lightBlue";
}
}
}
}
Found the solution, just needed to use select(). This highlights the selected field, adds a input box which the user can update, then save the value in the cell when enter is pressed.
function highlightCell(x) {
//add input field inside cell
var txtBox = document.createElement("input");
txtBox.id = x;
txtBox.type = "text";
for (var i = 0; i<9; i++) {
if (i == x) {
txtBox.value = cells[i].innerHTML;
cells[i].innerHTML = "";
cells[i].appendChild(txtBox);
txtBox.select();
cells[i].style.backgroundColor = "lightBlue";
cells[x].onkeypress = function(){
var event = window.event;
var btnPress = event.keyCode;
if(btnPress == 13)
{
var elem = document.getElementById(x);
cells[x].innerHTML = elem.value;
elem.parentNode.removeChild(elem);
}
}
} else {
cells[i].style.backgroundColor = "white";
}
}
}

Dynamic checkbox to hide dynamic inputbox

I'm rendering a dynamic input and checkbox from an array object which is fine, however I'm not quite sure how to hide the input when I click on the checkbox relative to the input.
function dynamicStuff () {
var objs = ['Id', 'Name', 'Age'];
for (var i = 0; i < objs.length; i++) {
objs[i];
var cElement = document.createElement("input");
cElement.type = "checkbox";
cElement.name = objs[i];
cElement.id = objs[i];
var cElementInput = document.createElement("input");
cElementInput.type = "text";
cElementInput.name = objs[i];
cElementInput.id = objs[i];
cElementInput.placeholder = objs[i]
document.getElementById('chkBox').appendChild(cElement);
document.getElementById('chkBox').appendChild(cElementInput);
}
}
Live example.
Saving on localStroage:
function chkboxCookie() {
var indexOfItem = checkAllFields.indexOf(this.id);
if (indexOfItem >= 0) {
checkAllFields.splice(indexOfItem, 1);
} else {
checkAllFields.push(this.id);
}
/* it saves paramater name in the localStorage*/
localStorage.setItem("checkedUsers", JSON.stringify(checkAllFields));
}
How do I hide the input that I ticked and potentially save that input name/Id in the localStorage?
You'd add an event handler that does something to the input when the checkbox is checked
function dynamicStuff() {
var objs = ['Id', 'Name', 'Age'];
for (var j = 0; j < objs.length; j++) {
(function(i) {
objs[i];
var cElementInput = document.createElement("input");
cElementInput.type = "text";
cElementInput.name = objs[i];
cElementInput.id = objs[i];
cElementInput.placeholder = objs[i];
var cElement = document.createElement("input");
cElement.type = "checkbox";
cElement.name = objs[i];
cElement.id = objs[i];
cElement.addEventListener('change', function() {
cElementInput.style.display = this.checked ? 'none' : 'inline';
localStorage.setItem(objs[i], this.value);
});
var br = document.createElement('br');
document.getElementById('chkBox').appendChild(cElement);
document.getElementById('chkBox').appendChild(cElementInput);
document.getElementById('chkBox').appendChild(br);
document.getElementById('chkBox').appendChild(br.cloneNode());
})(j);
}
}
dynamicStuff()
<div id="chkBox"></div>
Working fiddle.
The id attribute should be unique in the same page so try to change the id of the input for example :
cElementInput.id = objs[i]+'_input';
And attach change event to the checkbox's where you'll show/hide related inputs:
cElement.addEventListener("change", toggleInput, false);
Then define your toggleInput() function :
function toggleInput(){
var input_id = this.id+'_input';
document.getElementById(input_id).style.display = this.checked ? 'inline' : 'none';
localStorage.setItem(this.id, this.value);
}
To check/uncheck the checkboxe's based on localStorage, get the data first :
var localStorageData = JSON.parse(localStorage.getItem("checkedUsers"));
var data = localStorageData==null?[]:localStorageData;
Then check for the the values presented in the array and check/uncheck checkboxe's :
if(data.indexOf(objs[i]) >= 0)
cElement.checked = true;
else
cElement.checked = false;
Hope this helps.

Passing One's Self to OnClick Event JavaScript

The on click event that I add to an input in javascript isn't working in the proper manner.
My code so far looks like so:
function order(option) {
if(option.checked) {
document.getElementId("col_order").value = document.getElementById("col_order").value + " " + option.value;
}
}
...//somewhere further down
for(var i = 0; i < options.length; i++) {
var check = document.createElement("input");
var label = document.createElement("label");
var description = document.createTextNode(options[i]);
check.type = "checkbox";
check.name = "order_list[]";
check.value = options[i];
check.onclick = "order(check)"; //Problem here
label.appendChild(check);
label.appendChild(description);
element.appendChild(label);
}
I have also tried:
check.onclick = (function() { var option = check; return function() {order(option);}})();
The problem that I am having is the check.onlick line of code. When I add this with normal HTML:
<input type = "checkbox" name = "order_list[]" onclick = "order(this)" value = "randVal">randVal</input>
I don't have any problem whatsoever; the method executes with the intended results. Any thoughts?
Let me clarify: I make it to the order function just fine, but I never get into the if statement, even though the checkbox was just clicked
Use addEventListener instead, and even if it looks like it should work, you're overwriting the same variables on each iteration as there is no closure in for loops, so I would probably add a closure to avoid issues.
For a checkbox you would listen for the change event, not click
for(var j = 0; j < options.length; j++) {
(function(i) {
var check = document.createElement("input");
var label = document.createElement("label");
var description = document.createTextNode(options[i]);
check.type = "checkbox";
check.name = "order_list[]";
check.value = options[i];
check.addEventListener('change', function() {
if (this.checked) {
var col_order = document.getElementById("col_order");
col_order.value = col_order.value + " " + this.value;
}
}, false);
label.appendChild(check);
label.appendChild(description);
element.appendChild(label);
})(j);
}
FIDDLE
check.onclick = "order(check)"; assigns a String as an on-click handler. That doesn't work; the browser expects a function there:
check.onclick = function() {
order(check);
}

Javascript - Loop through select options clicking each one

I am trying to go through a select list with 200+ entries and click on each one. When an element is clicked on it executes a function selectCountry() which adds a line to a table. I want to have it create a table with every option selected. The page of interest is at: http://www.world-statistics.org/result.php?code=ST.INT.ARVL?name=International%20tourism,%20number%20of%20arrivals.
So far I have the following, but it doesn't seem to work:
var sel = document.getElementById('selcountry');
var opts = sel.options;
for(var opt, j = 0; opt = opts[j]; j++) {selectCountry(opt.value)}
I am trying to do this in the console in Chrome.
One of the most useful features of dev tools is that when you write the name of a function, you get back its source code. Here's the source code for the selectCountry function:
function selectCountry(select) {
if (select.value == "000") return;
var option = select.options[select.selectedIndex];
var ul = select.parentNode.getElementsByTagName('ul')[0];
var choices = ul.getElementsByTagName('input');
for (var i = 0; i < choices.length; i++)
if (choices[i].value == option.value) {
$("#selcountry:selected").removeAttr("selected");
$('#selcountry').val('[]');
return;
}
var li = document.createElement('li');
var input = document.createElement('input');
var text = document.createTextNode(option.firstChild.data);
input.type = 'hidden';
input.name = 'countries[]';
input.value = option.value;
li.appendChild(input);
li.appendChild(text);
li.onclick = delCountry;
ul.appendChild(li);
addCountry(option.firstChild.data, option.value);
$("#selcountry:selected").removeAttr("selected");
$('#selcountry').val('');
}
Your flaw is now obvious. selectCountry accepts the entire select element as an argument as opposed to the select's value (which is a terrible design but meh). Instead of passing the value of the element, change its index:
var sel = document.getElementById('selcountry');
var opts = sel.options;
for(var i = 0; i < opts.length; i++) {
sel.selectedIndex = i
selectCountry(sel)
}

Checkbox Select All functionality showing opposite behaviour after triggering click events

I have below javascript code which dynamically add the DIV with checkbox.
var mainDiv = document.createElement('div');
mainDiv.className = 'field';
var innerDiv = document.createElement('div');
innerDiv.className = 'SelectAllCheckBox';
var newlabel = document.createElement("Label");
newlabel.innerHTML = "Select All";
var selectCheckbox = document.createElement('input');
selectCheckbox.type = "checkbox";
selectCheckbox.name = "selectCheckbox";
selectCheckbox.id = "selectCheckboxID";
selectCheckbox.checked = true;
innerDiv.appendChild(selectCheckbox);
innerDiv.appendChild(newlabel);
mainDiv.appendChild(innerDiv);
var BusinessUnitsContainerID = document.getElementById('BusinessUnitsContainer');
BusinessUnitsContainerID.parentNode.insertBefore(mainDiv,BusinessUnitsContainerID);
//$j('.Publications input[type=checkbox]').removeAttr('checked');
$evt.addEventHandler(selectCheckbox, "click", this.getDelegate(this._onSelectAllCheckBoxClick));
function _onSelectAllCheckBoxClick()
{
//(.Publications input[type=checkbox]) these are multiple checkboxes which are also created dynamically
var checkboxes = document.querySelectorAll('.Publications input[type=checkbox]');
for (var i =0; i < checkboxes.length; i++)
{
checkboxes[i].checked = $j("#selectCheckboxID").checked;
$j(checkboxes[i]).click(); //calling the click for the child checkboxes as they have there click event and I can't change that as it is application generated click event for them.
}
};
Don't know why my select all check box it behaving differently, now on first click it is not unchecking all the child checkboxes, however on second click it works fine.
Any idea what could be the reason?
EDIT:
//alert("Inside Select All");
var checkboxes = document.querySelectorAll('.Publications input[type=checkbox]');
//alert($("#selectCheckboxID").checked);
if($("#selectCheckboxID").checked)
{
for (var i =0; i < checkboxes.length; i++)
{
checkboxes[i].checked = true;
$j("#lblSelectAll").text("Check All");
$j(checkboxes[i]).click();
}
}
else
{
for (var i =0; i < checkboxes.length; i++)
{
checkboxes[i].checked = false;
$j("#lblSelectAll").text('Uncheck All');
$j(checkboxes[i]).click();
}
}
Above code I have written to test, how to make it short
Replace your _onSelectAllCheckBoxClick function with below and try
function _onSelectAllCheckBoxClick()
{
$('.Publications input[type=checkbox]').click(); // jQuery default selector format
// if above doesn't work use your format, comment above code and uncomment below code
// $j('.Publications input[type=checkbox]').click();
return true;
}

Categories

Resources