Jquery script not working without alert - javascript

When I remove the alert from the function, the script doesn't work anymore.
Any ideas about why it happens ?
Function with alert in front:
function conScroll(getID){
alert();
$('#con_'+getID).mCustomScrollbar({
theme: 'minimal',
autoHideScrollbar: true,
axis: 'y',
mouseWheelPixels: 250,
advanced:{
updateOnContentResize: true
}
});
}
$(document).on('click', 'a[id=cWin]', function(){
var ID = Math.floor(Math.random()*90000) + 10000;
var TITLE = jQuery(this).attr('title');
var PAGE = $(this).attr('href');
$('#content').append('<div id="'+ ID +'" class="draggable">'+
'<div class="moveband">'+
'<div class="title">'+ TITLE +'</div>'+
'<div id="buttons">'+
'<div id="m_'+ ID +'" class="minimize"></div>'+
'<div id="c_'+ ID +'" class="close"></div>'+
'</div>'+
'<div style="clear:both"></div>'+
'</div>'+
'<div id="con_'+ ID +'" class="draggcon">d</div>'+
'</div>');
$('#list').append('<div id="t_'+ ID +'" class="item">Chatbox #'+ ID +'</div>');
$('#con_' + ID).load('../php/' + PAGE + '.php');
WinControl();
conScroll(ID);
return false;
});

Add mCustomScrollbar initialization into settimeout. It will work.
setTimeout(function(){
$('#con_'+getID).mCustomScrollbar({
theme: 'minimal',
autoHideScrollbar: true,
axis: 'y',
mouseWheelPixels: 250,
advanced:{
updateOnContentResize: true
}
});
}, 1000);

Related

Boobtbox dialog closes when clicked and the page refreshes

I recently change the code of a page that I had in a html page to an aspx one because I needed to implement a master page. The code and the function worked perfectly fine in the htmlpage but since I had changed it to the aspx page the bootbox dialog stop working properly, as soon as I click on it, it closes immediately and refreshes the page. These are the scripts that Im using.
<script src="Scripts/jquery-3.1.1.js"></script>
<script src="Scripts/popper.js"></script>
<script src="Scripts/bootstrap.js"></script>
<script src="Scripts/bootbox.js"></script>
Here are some of the functions of the page:
function disableTool(Herramientaid) {
bootbox.confirm({
message: "¿Estas seguro que deseas eliminar este herramienta?",
buttons: {
confirm: {
label: 'Si',
className: 'btn-success'
},
cancel: {
label: 'No',
className: 'btn-danger'
}
},
callback: function (result) {
if (result) {
sendRequest('DisableTool', { "Herramientaid": Herramientaid },
function (response) {
if (response[0] == 'OK') {
gettool();
bootbox.alert('La herramienta se ha eliminado');
}
else {
bootbox.alert('Error! ' + response[0]);
}
});
}
}
});
}
function UpdateTool(ToolControl) {
var Herramientaid = $(ToolControl).parent().parent().find('td').eq(0).html();
var NombreH = $(ToolControl).parent().parent().find('td').eq(1).html();
var Adminid = $(ToolControl).parent().parent().find('td').eq(2).html();
var HDesc = $(ToolControl).parent().parent().find('td').eq(3).html();
bootbox.dialog({
title: "Actualizar herramientas",
message: '<div class="row"> ' +
'<div class="col-md-12"> ' +
'<div class="form-group"> ' +
'<label class="col-md-3 control-label" for="txNombreH">Nombre:</label> ' +
'<div class="col-md-9"> ' +
'<input type="text" id="txNombreH" class="form-control" placeholder="Nombre" value=""' + NombreH + '/>' +
'</div>' +
'</div>' +
'<div class="form-group"> ' +
'<label class="col-md-3 control-label" for="txAdminid">ID del Administrador:</label> ' +
'<div class="col-md-9"> ' +
'<input type="text" id="txAdminid" class="form-control" placeholder="Administrador ID" value=""' + Adminid + '/>' +
'</div>' +
'</div>' +
'<div class="form-group"> ' +
'<label class="col-md-3 control-label" for="txHDesc">Descripcion de la herramienta:</label> ' +
'<div class="col-md-9"> ' +
'<input type="text" id="txHDesc" class="form-control" placeholder="Descripcion" value=""' + HDesc + '/>' +
'</div>' +
'</div>' +
'</div>' +
'</div>',
buttons: {
No: {
label: "No",
className: "btn-danger",
callback: function () {
}
},
Yes: {
label: "Si",
className: "btn-success",
callback: function () {
var newNombreH = $('#txNombreH').val();
var newAdminid = $('#txAdminid').val();
var newHDesc = $('#txHDesc').val();
sendRequest('UpdateTool', {
"Herramientaid": Herramientaid, "NombreH": newNombreH, "Adminid": newAdminid, "HDesc": newHDesc
},
function (response) {
if (response[0] == 'OK') {
gettool();
bootbox.alert('Se ha configurado la herramienta');
}
else {
UpdateTool(ToolControl);
bootbox.alert('Error! ' + response[0]);
}
}
)
}
}
}
});
}
I had this same issue today, updating to latest and greatest bootbox didn't help. I eventually tracked down that the button click for "Close", "Ok", even "Esc" was triggering the submission of the form event.
I've had to add a propagation catcher after calling my dialog:
$(".dialog-class-name").on('hidden.bs.modal', function (e) {
e.preventDefault();
e.stopPropagation();
});
It feels hacky, but it doesn't involve editing the actual library, and it does work....

How to append a dialog into a main div on your page on button click

I have a log in button that when a user clicks on it a terms and condition dialog pops up and overlaps the contents on a page as follows
TermsSuccess: function (result, context) {
var topTerms = findSetByInArray(result.Data, 'ParentId', 0);
var termsHTML = '<div id="terms"><ul class="termsList">';
for (var i = 0; i < topTerms.length; i++) {
var cls = (topTerms[i].isNew) ? 'newTerm' : 'Term';
termsHTML += '<li id=' + topTerms[i].ID + ' class=' + cls + '>'
termsHTML += topTerms[i].PageIndex + '. ' + topTerms[i].Detail;
termsHTML += getChildrenTerms(result.Data, topTerms[i].ID, topTerms[i].PageIndex + '. ');
termsHTML += '</li>';
}
termsHTML += '</ul></div>';
$(termsHTML).dialog({
modal: true,
resizable: false,
width: 400,
height: 600,
closeOnEscape: false,
open: function (event, ui) {
$(this).parent().children().children('.ui-dialog-titlebar-close').hide();
},
title: "Terms & Conditions",
buttons: [{
text: "Decline",
"class": 'btnDialog',
click: function () {
$(this).dialog("close");
}
},
{
text: "Accept",
"class": 'btnDialog',
click: function () {
betEvents.btnAccept_onClick();
$(this).dialog("close");
}
}]
});
}
I want this dialog to be appended to the following div on the page instead of it poping up over all the contents
<div id="mainarea"></div>
i tried to do something as the following but it doesnt work
function onClick(){
if $("#btnLogin").click(function(){
$('termsHTML').append('#mainarea');
});
}
your guidance will be appreciated.
Change this line:
$('termsHTML').append('#mainarea');
to
$(#mainarea).append(termsHTML);
and try again.
Explanation: $('termsHTML').append('#mainarea'); // here your selector is wrong

jQuery: function in dynamic generated list item doesn't work

I build a function to display a value in a HTML element for a
<input type="range">
object.
My function works fine:
var rangeValues = { "50": "Fifty" , "100": "Hundred" , "...": "..." };
$(function Skilllevel() {
$('#rangeText').text(rangeValues[$('#rangeInput').val()]);
$('#rangeInput').on('input change', function ()
{
$('#rangeText').text(rangeValues[$(this).val()]);
});
});
See example in jsfiddle
My problem now is the following:
I putted the function Skilllevel() into a $.each(result, function and into it, it doesn't work, because every entry from my second JSON file var urlBewerbungID = "json.php"; generated one separate list element in $("#ergebnisSkill").append(
The second JSON looks very simple, like this:
[
"item1",
"item2",
"item3"
]
My complete function:
//Skills selektieren
var rangeValues = {
"0": "Keine",
"33": "Anfänger",
"66": "Fortgeschritten",
"99": "Profi"
};
//Abfrage, welche Stelle gewählt wurde
$('#bewerbungID').on('change', function() {
var bewerbungID = ($('#bewerbungID').val());
console.log("BewerbungsID gewählt: " + bewerbungID);
//Zuerst das #HTML Element leeren
$("#ergebnisSkill").empty();
$(document).ready(function() {
var urlBewerbungID = "json.php";
$.getJSON(urlBewerbungID, function(result) {
console.log(result);
$.each(result, function(i, field) {
var skill = field;
//Skill liste erstellen
$(function Skilllevel() {
$('#rangeText').text(rangeValues[$('#rangeInput').val()]);
$('#rangeInput').on('input change', function() {
$('#rangeText').text(rangeValues[$(this).val()]);
});
});
//Jetzt HTML Element neu befüllen
$("#ergebnisSkill").append(
'<li>' +
'<div class="item-content">' +
'<div class="item-media"><i class="icon f7-icons">star</i></div>' +
'<div class="item-inner">' +
'<div class="item-title label">' + skill + '<br> <span id="rangeText"></span></div>' +
'<div class="item-input">' +
'<div class="range-slider">' +
'<input type="range" id="rangeInput" min="0" max="99" value="0" step="33">' +
'</div>' +
'</div>' +
'</div>' +
'</div>' +
'</li>'
);
});
});
});
});
Your code is inside out.
You need document.ready to wrap the event handlers.
Use class instead of IDs, IDs need to be unique
use delegation - currently you have a function per result which does not work.
You need the skills functionality assigned to each result but delegated - see how a click on the ergebnisSkill will be captured by the rangeInput:
//Skills selektieren
var rangeValues = {
"0": "Keine",
"33": "Anfänger",
"66": "Fortgeschritten",
"99": "Profi"
};
$(document).ready(function() {
//Skill liste erstellen
$("#ergebnisSkill").on('input change', ".rangeInput", function() { // delegation
$(this).closest("item-inner") // a parent div
.find('.rangeText') // the input field
.text(rangeValues[$(this).val()]);
});
//Abfrage, welche Stelle gewählt wurde
$('#bewerbungID').on('change', function() {
var bewerbungID = ($('#bewerbungID').val());
console.log("BewerbungsID gewählt: " + bewerbungID);
//Zuerst das #HTML Element leeren
$("#ergebnisSkill").empty();
var urlBewerbungID = "json.php";
$.getJSON(urlBewerbungID, function(result) {
console.log(result);
$.each(result, function(i, field) {
var skill = field;
//Jetzt HTML Element neu befüllen
$("#ergebnisSkill").append(
'<li>' +
'<div class="item-content">' +
' <div class="item-media"><i class="icon f7-icons">star</i></div>' +
' <div class="item-inner">' +
' <div class="item-title label">' + skill + '<br> <span class="rangeText"></span></div>' +
' <div class="item-input">' +
' <div class="range-slider">' +
' <input type="range" class="rangeInput" min="0" max="99" value="0" step="33">' +
' </div>' +
' </div>' +
' </div>' +
'</div>' +
'</li>'
);
});
});
});
});

Input OnClick is not recognized

I have this method that is recursively called.
This method creates a li that ll be used on Iscroll plugin.
My problem is:
The input button does not works. On his CSS I set cursor:pointer to check if the input is recognized, and it is. But I can click it several times that does nothing.
createList: function(p_id)
{
var lv_linhaDoc = '<li id="lis_' + p_id + '" class="listItem">' +
'<div class = "alinhar1" onClick="lis.Click(' + p_id + ', false)">' +
'<div class="ui-grid-a" style="font-size: large">' +
'<div class="ui-block-a"><p class="header" style="font-size: medium"><strong>' + 4 + '</strong></p></div>' +
'<div class="ui-block-a"><p class="line label"><strong>Data Criação</strong></p></div>' +
'<div class="ui-block-b"><p class="line value" style="text-align: right">' + '13/2/14' + '</p></div>' +
'<div class="ui-block-a"><p class="line label total"><strong> Valor</strong></p></div>' +
'<div class="ui-block-b"><p class="line total" style="text-align: right">' + 13 + ' ' + 15 + '</p></div>' +
'</div></div>' +
' <input type="button" class=" button_add" onClick="lis.Detail(' + p_id + ')" />' +
'</li>';
return lv_linhaDoc;
},
The problem is not in the Detail() function bacause I can't enter in that function because the click is not recognized
UPDATE
I found that the input button stopped working after I add these to the IScroll initialization
click: true,
tap: true,
I really need those arguments in the IScroll to do other fucntions.
IScroll initialization:
initScroll: function(){
var wrapper = document.getElementById('id5');
myScroll = new IScroll(wrapper, {
// click: true,
// tap: true,
scrollX : false,
scrollY : true,
scrollbars : false,
interactiveScrollbars : true,
mouseWheel : false,
hScrollbar : false,
vScrollbar : true,
useTransition : false,
snap : 'li',
indicators : {
el : '#scroller',
fade : false,
ignoreBoundaries : false,
interactive : false,
listenX : false,
listenY : true,
resize : false,
shrink : false,
speedRatioX : 0,
speedRatioY : 0,
checkDOMChanges: true,
},
});
Instead of trying to add the click handler inline, you can save the p_id as a data-attribute on the input and then setup a click handler using event delegation. With delegation you can setup a handler on elements that will be created dynamically later.
When creating the listitem, put the p_id in a data-attribute of the input e.g. data-pid:
<input type="button" class="button_add" data-pid="' + p_id + '" value="+" />
Then add a click handler that delegates to the .button_add class. In that handler you can retrieve the p_id from the data-attribute:
$(document).on("click", ".button_add", function(e){
var p_id = $(this).data("pid");
alert(p_id);
//call detail function and pass in the p_id
});
DEMO
You need to do something like below :
createList: function(p_id)
{
var lis = new lisClass();
var lv_linhaDoc = '<li id="lis_' + p_id + '" class="listItem">' +
'<div class = "alinhar1" onClick="lis.Click(' + p_id + ', false)">' +
'<div class="ui-grid-a" style="font-size: large">' +
'<div class="ui-block-a"><p class="header" style="font-size: medium"><strong>' + 4 + '</strong></p></div>' +
'<div class="ui-block-a"><p class="line label"><strong>Data Criação</strong></p></div>' +
'<div class="ui-block-b"><p class="line value" style="text-align: right">' + '13/2/14' + '</p></div>' +
'<div class="ui-block-a"><p class="line label total"><strong> Valor</strong></p></div>' +
'<div class="ui-block-b"><p class="line total" style="text-align: right">' + 13 + ' ' + 15 + '</p></div>' +
'</div></div>' +
' <input type="button" class=" button_add" onClick="lis.Detail(' + p_id + ')" />' +
'</li>';
return lv_linhaDoc;
},
You see i have aded var lis = new lisClass();
Just found the solution:
There's a bug on IScroll that if the parameter click is enable then all the form elements, such as the submit button do not work with iScroll.
So, I did this:
myScroll = new IScroll(wrapper, {
click: false,
scrollX : false,
scrollY : true,
scrollbars : false,
interactiveScrollbars : true,
mouseWheel : false,
hScrollbar : false,
vScrollbar : true,
useTransition : false,
snap : 'li',
preventDefaultException: {tagName:/.*/},
indicators : {
el : '#scroller',
fade : false,
ignoreBoundaries : false,
interactive : false,
listenX : false,
listenY : true,
resize : false,
shrink : false,
speedRatioX : 0,
speedRatioY : 0,
checkDOMChanges: true,
},
});
Notice that the parameter clickis now as false and i add the preventDefaultException: {tagName:/.*/},
I found this here

Get the ID of a dynamic text field via dynamically created button

See below code. I'm creating two text fields dynamically. In one of those text fields 2 buttons are also created. When either of these buttons are clicked how could I get the ID of the text field that doesn't have buttons?
<button type="button" id="tfButton">Add text</button>
<div id="InputsWrapper"></div>
<div id="OuterWrapper"></div>
$(document).ready(function() {
var tfCont = 0;
var InputsWrapper = $("#InputsWrapper");
var x = InputsWrapper.length;
var namefield = $("#tfButton");
$(namefield).click(function() {
tfCont++;
$(InputsWrapper).append('<div>' + '<div class="name" id="InputsWrapper_0' + tfCont + '">' + '<input type="textarea" id="field_' + tfCont + '" class="fTypex" placeholder="Thought of the day..." data-tfcount="' + tfCont + '"/><button type="button" runclass0">Run</button><button type="button" class="removeclass0">Next</button>' + '<br>' + '</div>' + '</div>');
$("#OuterWrapper").append('<div id="textLayer_' + tfCont + '">' + '<input type="textarea" id="tf_' + tfCont + '" data-tfcount="' + tfCont + '">' + '</div>');
x++;
return false;
});
$(document).on("click blur keyup", "input.fTypex", function() {
var tfc = $(this).data("tfcount");
$("#tf_" + tfc).val(this.value);
});
});
Do you mean something like this?
I know I didn't make use of your data attributes. However, there are million ways to re-include them, I simply thought it was best to show you an easier way without relying on multiple similar ID's, found by using data. That way just seemed like more work and headache, to me anyway.
jsFiddle: live example
$(function() {
function createFields(e) {
var inWrap = $('<div />', { class: 'name-wrapper' }),
nameWrap = $('<div />', { class: 'name' }).appendTo(inWrap),
outWrap = $('<div />');
nameWrap.append(
$('<input />', { class: 'fTypex', placeholder: 'Thought of the day...', type: 'textarea' }),
$('<button />', { text: 'Run', type: 'button' }),
$('<button />', { text: 'Next', type: 'button' })
);
outWrap.append(
$('<input />', { type: 'textarea' })
);
$('#InputsWrapper').append(inWrap);
$('#OuterWrapper').append(outWrap);
}
$(document)
.on('click', '#tfButton', createFields)
.on('click', '#InputsWrapper button', function(e) {
var i = $(this).closest('.name-wrapper').index(),
inp = $('#OuterWrapper input')[i],
$inp = $(inp);
console.log(i, inp, $inp);
// could use like
$('.highlight').removeClass('highlight');
$inp.addClass('highlight');
})
})
And if you insist on your data attributes and that weird runclass0 attr and the other class, here's an alternate fiddle including those little items. You'll notice very little change in structure tho.
Alt jsFiddle
$(function() {
function createFields(e) {
var inWrap = $('<div />', { class: 'name-wrapper' }),
nameWrap = $('<div />', { class: 'name' }).appendTo(inWrap),
outWrap = $('<div />'),
iCnt = $('#InputsWrapper .name-wrapper').length + 1;
nameWrap.append(
$('<input />', { class: 'fTypex', 'data-tfcount': iCnt, id: 'field_'+iCnt, placeholder: 'Thought of the day...', type: 'textarea' }),
'<button runclass0 type="button">Run',
$('<button />', { class: 'removeclass0', text: 'Next', type: 'button' })
);
outWrap.append(
$('<input />', { 'data-tfcount': iCnt, id: 'tf_'+iCnt, type: 'textarea' })
);
$('#InputsWrapper').append(inWrap);
$('#OuterWrapper').append(outWrap);
}
$(document)
.on('click', '#tfButton', createFields)
.on('click', '#InputsWrapper button', function(e) {
var i = $(this).closest('.name-wrapper').index(),
inp = $('#OuterWrapper input')[i],
$inp = $(inp);
// see console for more info: F12 in most of today's browsers
if (console['log']) console.log(i, inp, $inp);
// could use like
$('.highlight').removeClass('highlight');
$inp.addClass('highlight');
})
})

Categories

Resources