create a group of checkboxes with a click event associated Javascript - javascript

I'm creating a javascript function that builds a table with checkboxes.
I want associate a click event to them.
The event must be the same for all.
This is a part of my code:
var i = 0;
for (i = 0; i < data.Items.length; i++) {
var tr = $(document.createElement('tr'));
tr.addClass("MyBookings_table_content");
$("#MyBookings_table").append(tr);
//Create a CheckBox Element
var chkbox = document.createElement('input');
chkbox.type = "checkbox";
chkbox.id = "chk"+i.toString();
chkbox.name = "chk" + i.toString();
//Event here
}
Can anybody help me?

Since you are using jQuery, you can simply add this event listener :
$("#MyBookings_table").on("click", "input[type=checkbox]", clickCB);
function clickCB() {
var $cbx = $(this);
// some code on my checkbox
}
This code is to be appended after the loop, see this fiddle : http://jsfiddle.net/6f79pd5y/

create a function and link it with an addEventListener
function outerFunction(){
}
checkbox.addEventListener('click', outerFunction);

addEventListener("click",myFunction);
where you have the comments

How about:
var i = 0;
for (i = 0; i < data.Items.length; i++) {
var tr = $(document.createElement('tr'));
tr.addClass("MyBookings_table_content");
$("#MyBookings_table").append(tr);
//Create a CheckBox Element
var chkbox = document.createElement('input');
chkbox.type = "checkbox";
chkbox.id = "chk"+i.toString();
chkbox.name = "chk" + i.toString();
//Event here
$(chkbox).click(function()
{
alert("Click!");
});
tr.append(chkbox);
}
A working example:http://jsfiddle.net/mpup12z5/

If you reorganise your element-creation to use jQuery also, you can bind the click-handler at the point of creation:
var i = 0;
for (i = 0; i < data.Items.length; i++) {
var tr = $(document.createElement('tr'));
tr.addClass("MyBookings_table_content");
$("#MyBookings_table").append(tr);
$('<input />', {
'type' : 'checkbox',
'id' : chk + i, // i will be converted to a string automatically
'name' : chk + i,
'click' : functionToCall // note: no parentheses, you want to
}); // call the function, not use its return value
}
Or:
var i = 0;
for (i = 0; i < data.Items.length; i++) {
var tr = $(document.createElement('tr'));
tr.addClass("MyBookings_table_content");
$("#MyBookings_table").append(tr);
$('<input />', {
'type' : 'checkbox',
'id' : chk + i, // i will be converted to a string automatically
'name' : chk + i,
'on' : {
'click' : functionToCall
}
});
}
But, it really is preferable to delegate the event-handling to the closest ancestor element, presumably the <table>, unless a specific property of the created <input /> should call a different function, or do something somewhat different.

Related

How to apply an ajax funcion to all elements?

I have a function that shows a number on a button using ajax and ehn the button's is clicked I disable it.I would like to disable all buttons in a function. I tried it using a class, but it doesn't work.
This is my script code:
$(document).ready(function(){
$(':button').on('click', function(event){
$('#ID').val(this.id);
var tmp = this.id;
$.ajax({
type: $('#klik').attr("method"),
url : $('#klik').attr("action"),
data : $('#klik').serialize(),
success: function(d){
$('#' + tmp).val(d);
const button = document.getElementById(tmp);
button.disabled = true;
if (d == 'bomba'){
alert('bb');
$(function(){
$('.gumb').attr('disabled', true);
});
}
//$('.fake').closest('tr').remove();
//$('#popup').dialog('close');
},
error: function(){
alert('Greska')
}
});
});
});
    var docFrag = document.createDocumentFragment();
    for (var i=0; i < 9 ; i++){
        var row = document.createElement("tr")
        for (var j=0; j < 9 ; j++){
                var elem = document.createElement('input');
elem.class = 'gumb';
                elem.type = 'button';
                elem.id = 'r'+i+'s'+j;
                elem.value = '';
                elem.innerHTML = elem.value;
                docFrag.appendChild(elem);
            }
        document.body.appendChild(docFrag);
        document.body.appendChild(row);
    }
</script>
It does alert 'bb' but the function doesn't work.
Are you talking about elements is an array? you can use forEach()
if it’s html elements you can store it in array then use forEach(), but if you’re not editing then i don’t know
forEach(function(//params){//disable})

Adding onClick function to select elements

I have a select tag of dynamically added elements. I need to add an event listener to each of the elements in the select tag except the first which:
adds the text of the element to a list,
makes the focus of the list the first element again, and
removes or hides the clicked element.
The first element is a 'none' element which doesn't need any event listener.
I've tried something like
for (var i = 0; i < array.length; i++)
{
var name = array[i];
var selectElement = document.getElementById(selectElementId);
addToSelectNode(document.getElementById(selectElementId), name);
var thisNode = selectElement.childNodes[i];
if (thisNode.value != "none")
{
thisNode.addEventListener("click", function(event)
{
appendNodeToList("artist-list", i);
selectElement.selectedIndex = 0;
selectElement.remove(selectElement.i);
selectElement.style.display = "none";
});
}
}
function addToSelectNode(element, optionText)
{
var newSelectElement = document.createElement("option");
newSelectElement.text = optionText;
element.add(newSelectElement);
}
function appendNodeToList(listId, text)
{
var newNode = document.createElement("LI");
var textNode = document.createTextNode(text);
newNode.appendChild(textNode);
document.getElementById(listId).appendChild(newNode);
}
Didn't work at all though
A few hours later I've solved my own question. The problem stemmed from trying to remove items in the select tag which just wasn't working - I'm nut sure if it's possible but making it disabled solved it. Anyway here's the result.
HTML:
<select id="artist-select-list">
<option value="none">none</option>
</select>
JavaScript:
window.onload = function()
{
var dropdown = document.getElementById("sampleDropdown");
var n = array.length;
// Loop to add to <select> dropdown
for (var i = 1; i <= n; i++)
{
addToSelectNode(dropdown, array[i - 1]);
}
// Loop to add id's to each element in the dropdown
for (var i = 0; i <= n; i++)
{
dropdown[i].id = "selectNum" + i;
}
// Loop to add event listener
for (var i = 0; i < dropdown.length; i++)
{
dropdown[i].addEventListener("click", function(event)
{
// Regardless of which option the user clicks move shown option to "none" (first index in dropdown)
dropdown.selectedIndex = 0;
if (event.target.id != "selectNum0")
{
// Disable once clicked
event.target.disabled = true;
// Do other things here in relation to event.target
}
});
}
}
var array =
[
"sampleText1", "sampleText2"
];
function addToSelectNode(element, optionText)
{
var newSelectElement = document.createElement("option");
newSelectElement.text = optionText;
element.add(newSelectElement);
}

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)
}

JavaScript add new input fields on click

I have this JavaScript Code that currently adds new textareas, inputs etc. inside a table and adds a unique number on each id/name
var i=1;
function addRow() {
var tbl = document.getElementById('table1');
var lastRow = tbl.rows.length;
var iteration = lastRow - 1;
var row = tbl.insertRow(lastRow);
var descriptionCell = row.insertCell(0);
var elDescription = document.createElement('textarea');
elDescription.type = 'textarea';
elDescription.name = 'description' + i;
elDescription.id = 'description' + i;
elDescription.cols = 70;
elDescription.rows = 2;
descriptionCell.appendChild(elDescription);
var unitpriceCell = row.insertCell(1);
var elUnitPrice = document.createElement('input');
elUnitPrice.type = 'text';
elUnitPrice.name = 'unitprice' + i;
elUnitPrice.id = 'unitprice' + i;
elUnitPrice.size = 20;
unitpriceCell.appendChild(elUnitPrice);
i++;
form1.number.value=i;
//alert(i);
document.getElementById("line").innerHTML = "whatever";
}
I have removed the table and now this is not working. How can I make the same thing work with text inputs and text areas without the table?
A relatively simple approach to the problem:
function createFieldset(opts){
// default settings:
var s = {
// finds the first form, could use "document.forms[0]" instead
'appendTo' : document.querySelector('form'),
// an array of elements you want to create:
'create' : ['input', 'textarea'],
// the element you want to wrap those elements with:
'wrapper' : 'fieldset',
// the className to apply to the wrapping-element:
'wrapperClassName' : 'group',
// the prefix of the 'legend' tag (if you want to use one):
'legendPrefix' : 'Group '
},
// finding out where the count should start (by finding
// the number of current wrapping elements), could use
// 'document.getElementsByTagName(s.wrapper).length' or
// 'document.getElementsByClassName(s.wrapperClassName).length':
count = document.querySelectorAll(s.wrapper).length,
// creating the wrapper element:
container = document.createElement(s.wrapper),
// finding out whether to use textContent or innerText:
textProp = 'textContent' in document.body ? 'textContent' : 'innerText',
// caching temporary variables for later:
created,
tmp;
// iterating through any user-set properties to update the
// default settings:
for (var prop in opts) {
if (opts.hasOwnProperty(prop)) {
s[prop] = opts[prop];
}
}
// if we have a prefix of length > 0 once leading/trailing white-space
// is removed, then:
if (s.legendPrefix.trim().length > 0) {
// create a 'legend' element:
var legend = document.createElement('legend');
// set the text of that legend element to 's.legendPrefix n'
legend[textProp] = s.legendPrefix + count;
// append that legend element to the container element:
container.appendChild(legend);
}
// iterating over the array of elements to be created:
for (var i = 0, len = s.create.length; i < len; i++){
// caching the string of the element at position i in the array:
tmp = s.create[i];
// creating the element at that position:
created = document.createElement(tmp);
// setting the id, and name, to element-type + n:
created.id = tmp + (count);
created.name = tmp + (count);
// appending the element to the wrapping element:
container.appendChild(created);
}
// setting the className of the wrapping element:
container.className = s.wrapperClassName;
// inserting the element to the appendTo node, before its lastElementChild:
s.appendTo.insertBefore(container, s.appendTo.lastElementChild);
}
createFieldset({
'wrapperClassName' : 'first'
});
var button = document.querySelector('#addMore');
button.addEventListener('click', function (event) {
event.preventDefault();
createFieldset();
}, false);
JS Fiddle demo.
References:
document.createElement().
document.getElementsByClassName().
document.getElementsByTagName().
document.querySelector().
document.querySelectorAll().
EventTarget.addEventListener().
Node.appendChild().
Node.insertBefore().
Object.hasOwnProperty().
String.prototype.trim().

Categories

Resources