How to apply an ajax funcion to all elements? - javascript

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

Related

hide show does not work after insertAfter jQuery

I'm appending some rows to my table and when I click on one row different rows should open, I'm using slideToggle and hide show, but it doesn't work.. the click does work(I added console.log to check)- if I'm writing the rows inside the html it does work.
this is the function:
$('#table').on('click','.good_light_tags_reg',function(){
console.log("hey");
if ($('.good_light_sub_tag_reg').is(":visible")){
$('.good_light_sub_tag_reg').hide();
}
else{
$('.good_light_sub_tag_reg').show();
}
});
the insert part..
var identified_correctly = {};
var rows = "";
for (var i=1 ; i<(table.rows.length -1) ; i++){
if (table.rows[i].className.includes('_tags_reg')){
if (table.rows[i].className != table.rows[i+1].className) {
val = table.rows[i].cells[6].innerHTML;
var pos = val.indexOf("<br>");
var res = parseFloat(val.substring(0, pos));
identified_correctly[table.rows[i].className]=parseFloat(res);
}
}
}
var items = Object.keys(identified_correctly).map(function(key) {
return [key, identified_correctly[key]];
});
items.sort(function(first, second) {
return first[1] - second[1];
});
for (var i=0;i<items.length;i++){
var class_name = items[i][0];
var tags_rows = document.getElementsByClassName(class_name);
var sub_tags_rows = document.getElementsByClassName(class_name.replace("_tags_","_sub_tag_"));
for (var tag=0;tag<tags_rows.length;tag++){
rows += tags_rows[tag].outerHTML;
for (var sub_tag=0;sub_tag<sub_tags_rows;sub_tag++){
rows += sub_tags_rows[sub_tag].outerHTML;
}
}
}
for (var i=0;i<items.length;i++){
$("#table").find("."+items[i][0]).remove();
$("#table").find("."+items[i][0].replace("_tags_","_sub_tag_")).remove();
}
$(rows).insertAfter($(".tag_list_reg").last());
try this using $(document)
$(document).on('click','.good_light_tags_reg',function(){
$('.good_light_sub_tag_reg').toggle();
});
and if the element to show or hide is inside new row, try this
$(document).on('click','.good_light_tags_reg',function(){
$(this).find('.good_light_sub_tag_reg').toggle();
});

Stop output printing multiple times if function activated more than once

I'm activating a javascript function with a Jquery onclick button:
$('#on').click(function() {
var a = document.getElementsByTagName('a');
for (i = 0; i < a.length; i++) {
a[i].addEventListener('click', function() {
var span = document.createElement('span');
var text = document.createTextNode(this.innerHTML + " ");
span.appendChild(text);
document.getElementsByClassName('output')[0].appendChild(span);
})
}
});
The problem is if the button is clicked more than once the function will repeat more than once. In this case it will print the output multiple times. How can I modify the javascript function to only print one character per click?
Example:
http://jsfiddle.net/874Ljaq1/
Use the jQuery event binding method one
$('#on').one("click", function() {
var a = document.getElementsByTagName('a');
for (i = 0; i < a.length; i++) {
a[i].addEventListener('click', function() {
var span = document.createElement('span');
var text = document.createTextNode(this.innerHTML + " ");
span.appendChild(text);
document.getElementsByClassName('output')[0].appendChild(span);
})
}
});
You can use the jQuery .data() function to set a flag when the button has been clicked once, and only proceed if the flag is not set.
The code:
$('#on').click(function () {
// if we have a flag that indicates this button has been clicked before,
// don't do anything.
if ($(this).data('clicked'))
return;
$(this).data('clicked', true); // set the flag
var a = document.getElementsByTagName('a');
for (i = 0; i < a.length; i++) {
a[i].addEventListener('click', function () {
var span = document.createElement('span');
var text = document.createTextNode(this.innerHTML + " ");
span.appendChild(text);
document.getElementsByClassName('output')[0].appendChild(span);
})
}
});

create a group of checkboxes with a click event associated 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.

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

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