I am trying to use .on to listen for an event.
html:
<div class="form-group" id="group_names">
<label> Names: </label><br>
<input type="text" class="form-control name" placeholder="name1" id="name1" name ="name1"><br>
</div>
JS:
for (n = 1; n < inputLength+3 ; ++n) {
var test2 = document.getElementById(dude+n);
$(test2).on('change', '#group_names', forFunction);
}
The change to the input field is not being recognized.
Additionally, I am hoping .on will recognize changes made to new html i am injecting using the following function:
var dude = "name";
function forFunction() {
for (m = 1; m < inputLength + 1; ++m) {
var test = document.getElementById(dude + m)
if (test.value != "") {
var txt = "<input type=\"text\" class=\"form-control name\" placeholder=" + dude + (m + 1) + " id=" + dude + (m + 1) + " name=" + dude + (m + 1) + "><br>";
document.getElementById('group_names').insertAdjacentHTML('beforeend', txt);
//function updateHTML(txt)
}
}
}
I am not sure if my syntax for .on is correct. I am trying to use "#group_names" as the selector, but not sure if I am doing it right.
Thanks
You probably want to use event delegation on the parent div instead.
$('#group_names').on('change', 'input.form-control.name', forFunction);
Consider the following jQuery code.
$(function() {
var inputFields = $("input[id*='name']");
function forFunction(evt) {
console.log(evt.type);
inputFields.each(function(i, el) {
var n = i + 1;
if ($(el).val() != "") {
console.log("Value Detected");
$("<input>", {
type: "text",
class: "form-control name",
placeholder: "group" + n,
id: "group" + n,
name: "group" + n
}).insertBefore("#group_names");
}
});
}
inputFields.on("change", forFunction);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group" id="group_names">
<label> Names: </label><br>
<input type="text" class="form-control name" placeholder="name1" id="name1" name="name1"><br>
</div>
This should work for all of the Input items.
So I have these divs that are essentially results, I am trying to filter through said results using checkboxes and data-category tags.
Here is the code I am using below it works except for it should only show the divs if its data category tags match all checkboxes selected. But in this script if you select boditrak, trackman, and indoor it will show each result that has any of those not just the ones that contain each tag
JSFiddle
<html>
<head>
<title>Test</title>
</head>
<body>
<input type='checkbox' name="sq-filter" value="trackman" id="trackman">trackman<br>
<input type='checkbox' name="sq-filter" value="boditrak" id="boditrak"> boditrak<br>
<input type="checkbox" name="sq-filter" value="kvest" id="kvest">kvest<br>
<input type="checkbox" name="sq-filter" value="slowmotion" id="slowmotion">slowmotion<br>
<input type="checkbox" name="sq-filter" value="indoor" id="indoor">indoor<br>
<p>
<div class="filters">
<div data-id="golfer" data-category="boditrak trackman slowmotion">
<p>Golfer Name - boditrak trackman slowmotion</p>
</div>
<div data-id="golfer" data-category="indoor slowmotion trackman">
<p>Golfer Name - indoor slowmotion trackman</p>
</div>
<div data-id="golfer" data-category="kvest boditrak trackman">
<p>Golfer Name - kvest boditrak trackman</p>
</div>
<div data-id="golfer" data-category="indoor slowmotion">
<p>Golfer Name - indoor slowmotion</p>
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var byProperty = [];
$("input[name=sq-filter]").on( "change", function() {
if (this.checked) byProperty.push("[data-category~='" + $(this).attr("value") + "']");
else removeA(byProperty, "[data-category~='" + $(this).attr("value") + "']");
});
$("input").on( "change", function() {
var str = "Include items \n";
var selector = '', cselector = '', nselector = '';
var $lis = $('.filters > div'),
$checked = $('input:checked');
if ($checked.length) {
if (byProperty.length) {
if (str == "Include items \n") {
str += " " + "with (" + byProperty.join(',') + ")\n";
$($('input[name=sq-filter]:checked')).each(function(index, byProperty){
if(selector === '') {
selector += "[data-category~='" + byProperty.id + "']";
} else {
selector += ",[data-category~='" + byProperty.id + "']";
}
});
} else {
str += " AND " + "with (" + byProperty.join(' OR ') + ")\n";
$($('input[name=fl-size]:checked')).each(function(index, byProperty){
selector += "[data-category~='" + byProperty.id + "']";
});
}
}
$lis.hide();
console.log(selector);
console.log(cselector);
console.log(nselector);
if (cselector === '' && nselector === '') {
$('.filters > div').filter(selector).show();
} else if (cselector === '') {
$('.filters > div').filter(selector).filter(nselector).show();
} else if (nselector === '') {
$('.filters > div').filter(selector).filter(cselector).show();
} else {
$('.filters > div').filter(selector).filter(cselector).filter(nselector).show();
}
} else {
$lis.show();
}
$("#result").html(str);
});
function removeA(arr) {
var what, a = arguments, L = a.length, ax;
while (L > 1 && arr.length) {
what = a[--L];
while ((ax= arr.indexOf(what)) !== -1) {
arr.splice(ax, 1);
}
}
return arr;
}
</script>
</html>
The problem is with comma , which you are adding between each [data-category~=] in selector variable. So jQuery is looking for element which has any one of these data-category. So just remove comma, then only jQuery will start looking for those element which have all those data-category
Your selector value should be [data-category~='trackman'][data-category~='boditrak'] instead of [data-category~='trackman'],[data-category~='boditrak']
var byProperty = [];
$("input[name=sq-filter]").on( "change", function() {
if (this.checked) byProperty.push("[data-category~='" + $(this).attr("value") + "']");
else removeA(byProperty, "[data-category~='" + $(this).attr("value") + "']");
});
$("input").on( "change", function() {
var str = "Include items \n";
var selector = '', cselector = '', nselector = '';
var $lis = $('.filters > div'),
$checked = $('input:checked');
if ($checked.length) {
if (byProperty.length) {
if (str == "Include items \n") {
str += " " + "with (" + byProperty.join(',') + ")\n";
$($('input[name=sq-filter]:checked')).each(function(index, byProperty){
selector += "[data-category~='" + byProperty.id + "']";
});
} else {
str += " AND " + "with (" + byProperty.join(' OR ') + ")\n";
$($('input[name=fl-size]:checked')).each(function(index, byProperty){
selector += "[data-category~='" + byProperty.id + "']";
});
}
}
$lis.hide();
console.log(selector);
console.log(cselector);
console.log(nselector);
if (cselector === '' && nselector === '') {
$('.filters > div').filter(selector).show();
} else if (cselector === '') {
$('.filters > div').filter(selector).filter(nselector).show();
} else if (nselector === '') {
$('.filters > div').filter(selector).filter(cselector).show();
} else {
$('.filters > div').filter(selector).filter(cselector).filter(nselector).show();
}
} else {
$lis.show();
}
$("#result").html(str);
});
function removeA(arr) {
var what, a = arguments, L = a.length, ax;
while (L > 1 && arr.length) {
what = a[--L];
while ((ax= arr.indexOf(what)) !== -1) {
arr.splice(ax, 1);
}
}
return arr;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='checkbox' name="sq-filter" value="trackman" id="trackman">trackman<br>
<input type='checkbox' name="sq-filter" value="boditrak" id="boditrak"> boditrak<br>
<input type="checkbox" name="sq-filter" value="kvest" id="kvest">kvest<br>
<input type="checkbox" name="sq-filter" value="slowmotion" id="slowmotion">slowmotion<br>
<input type="checkbox" name="sq-filter" value="indoor" id="indoor">indoor<br>
<p>
<div class="filters">
<div data-id="golfer" data-category="boditrak trackman slowmotion">
<p>Golfer Name - boditrak trackman slowmotion</p>
</div>
<div data-id="golfer" data-category="indoor slowmotion trackman">
<p>Golfer Name - indoor slowmotion trackman</p>
</div>
<div data-id="golfer" data-category="kvest boditrak trackman">
<p>Golfer Name - kvest boditrak trackman</p>
</div>
<div data-id="golfer" data-category="indoor slowmotion">
<p>Golfer Name - indoor slowmotion</p>
</div>
</div>
I have a form with 2 sections. From each section, at least one value must be selected.
I know how to pass compulsory parameters but passing the appropriate parameters based on user selection is what I am not sure of.
Any ideas please?
Template plunker here
<form>
<div>
<label>Section 1</label></br>
<input type="checkbox" name="chkBox1" value="chkBox1">chkBox1<br>
<input type="checkbox" name="chkBox2" value="chkBox2">chkBox2<br>
<input type="checkbox" name="chkBox3" value="chkBox3">chkBox3<br>
</div>
<div>
<label>Section 2</label>
<div>
Optional 1:
<input type="text" name="fname" value="fname" />
</div>
<div>
Optional 2:
<input type="text" name="lname" value="lname" />
</div>
</div>
<button ng-click="getAll()">Get result</button>
</form>
Controller function
$scope.getAll = function() {
return $http.get('/api/testing?chbox1='+ 1 +'&chbox3=' + 1
+'&chbox2=' + 0 +'&optional1=' + fname +'&optional2=' + lname);
},
You can concat your URL depending of fname & lname defined or not:
return $http.get('/api/testing?chbox=' + 1 + '&chbox3=' + 1 + '&chbox2=' + 0 + ((fname !== undefined) ? '&optional1=' + fname : '') + ((lname !== undefined) ? '&optional2=' + lname : ''));
},
I used ternary conditions for writing it faster, but you can use multiple conditions for this case too:
$scope.getAll = function(){
var url;
if (fname !== undefined && lname !== undefined)
url = '/api/testing?chbox1='+ 1 +'&chbox3=' + 1 +'&chbox2=' + 0 +'&optional1=' + fname +'&optional2=' + lname;
else
if (fname !== undefined)
url = '/api/testing?chbox1='+ 1 +'&chbox3=' + 1 +'&chbox2=' + 0 +'&optional1=' + fname;
if (lname !== undefined)
url = '/api/testing?chbox1='+ 1 +'&chbox3=' + 1 +'&chbox2=' + 0 +'&optional2=' + lname;
}
Second option is less elegant!
I have the following, which shows upcoming matches and allow users to vote who will win
Team names and fixtures are dynamically pulled from db, it is unlikely that number of matches will be the same for each round, thus nr matches vary for each round.
When user made his selection before he clicks submit, I would like to display something like:
You have selected:
Force (Selected) To Win Crusaders(not selected)
Highlanders (Selected) To Win Cheetahs(not selected)
:
I got this working correctly like so:
But Im stuggling to put the "VS" part team not selected in the string. I.E it is easy enough to put the selected teams value in the string but im struggling to get the name from team not selected.
Perhaps this fiddle will give you a better idea to what im trying to achieve:
https://jsfiddle.net/timcoetzee/L9gna8a0/3/
function handleClick() {
// Get all the inputs.
var inputs = makePicks.elements;
var radios = [];
//Loop and find only the Radios
for (var i = 0; i < inputs.length; ++i) {
if (inputs[i].type == 'radio') {
radios.push(inputs[i]);
}
}
myradiovalue = "";
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
if (myradiovalue == "") myradiovalue = radios[i].value
else myradiovalue = myradiovalue + ", " + radios[i].value
}
}
document.getElementById("dispPicks").innerHTML = "YOU HAVE SELECTED " + myradiovalue;
return false;
}
<form name="makePicks">
<label class="green">
<input type="radio" id="x" onclick="handleClick()" name="picks1" value="Chiefs"><span>Chiefs</span>
</label>
<label class="yellow">
<input type="radio" onclick="handleClick()" name="picks1" value="Hurricanes"><span>'Hurricanes'</span>
</label>
<label class="pink">
<input type="radio" name="picks1" value="draw" onclick="handleClick()"><span>Draw</span>
</label>
<br />
<label class="green">
<input type="radio" id="x" onclick="handleClick()" name="picks2" value="Lions"><span>Lions</span>
</label>
<label class="yellow">
<input type="radio" onclick="handleClick()" name="picks2" value="Stormers"><span>'Stormers'</span>
</label>
<label class="pink">
<input type="radio" name="picks2" value="draw" onclick="handleClick()"><span>Draw</span>
</label>
<br />
</form>
<div id="dispPicks"></div>
Any help or advise very much appreciated
function ff() {
var msg = "you have selected:<br/>" ;
var radios = makePicks.querySelectorAll('input[type=radio]');
for(var i = 0; i < radios.length; i++) {
if(radios[i].checked) {
msg += getMessage(radios[i].getAttribute('name')) + "<br/>";
}
}
document.getElementById("dispPicks").innerHTML = msg;
}
function getMessage(nm) {
var rds = makePicks.querySelectorAll('input[type=radio][name=' + nm + ']');
var checked = 0;
for(var i = 0; i < rds.length; i++) {
if(rds[i].checked)
checked = i;
}
if(checked == 2)
return rds[0].value + " (not selected) to draw " + rds[1].value + " (not selected)";
else if(checked == 1)
return "<b>" + rds[1].value + "</b> (selected) to win " + rds[0].value + " (not selected)";
else
return "<b>" + rds[0].value + "</b> (selected) to win " + rds[1].value + " (not selected)";
}
jsfiddle DEMO
So, like the title says I'm trying to figure out how to define a modal dialog that will update or create customers. And then I can show it on the orders page or other pages simply by calling it...
I'm new to JavaScript but not to programming. In windows app I would create a class that I could call and show to the user but I'm not sure how to do that in js.
I've figured out how to use the modal dialog with a div and with an iframe but making it usable on multiple pages is eluding me.
Please help,
Thanks,
Dave
Edit: I don't want to use an iframe since I would like yo be able to access fields both ways from the page to the dialog and back again.
Edit 2:
So (remember im new to this)... I created the main page (default.aspx) and a customer page (customer.html) and a customer single instance module (customer.js).
From default.aspx I load up the customer module, add an event handler for the "loaded" custom event i created, and it works, loads the data in the form. Then I open the customer dialog, it works, dialog loads its own data from the customer module, however, when i click the save button in the dialog, the data is saved properly but the customer module after saving fires a "datasaved" event and its not getting caught on default.aspx...
can you see anything wrong with this?? this web site was picky as to what i can paste in here so let me know if something got missed...
default.aspx
<script type="text/javascript">
var customer;
var customerDialog;
function showCustomerPopup(closedCallback) {
var width = $(window).innerWidth;
if (width > 420)
width = 420;
$('#divCustomerPopup').remove();
$("body").append("<div id='divCustomerPopup' style='display: none;'></div>");
var divPopup = $("#divCustomerPopup");
$.get("templates/customer.html", function (data) {
divPopup.html(data);
});
customerDialog = $("#divCustomerPopup").dialog({
autoOpen: true,
height: 300,
width: width,
modal: true,
});
}
$(function () {
var custIDField = $("#CustomerID");
customer = Customer.getInstance();
if ($.isNumeric(custIDField.val())) {
customer.load(custIDField.val());
} else {
var qID = getParameterByName('customerid');
if ($.isNumeric(qID)) {
customer.load(qID);
} else {
customer.create();
}
}
$('#CustomerName').on('change', function () {
showCustomerPopup();
});
$("#customer-form").on("submit", function (e) {
e.preventDefault();
addCustomer();
});
$(customer).on("dataloaded", function (e, data) {
console.log("dataloaded");
custIDField.val(data.CustomerID);
$('#CustomerName').val(data.CustomerName);
$('#CustomerOnHold').val(data.OnHoldReason);
});
$(customer).on("datasaved", function (e, data) {
console.log("datasaved");
custIDField.val(data.CustomerID);
$('#CustomerName').val(data.CustomerName);
$('#CustomerOnHold').val(data.OnHoldReason);
customerDialog.dialog('close');
});
});
customer.js
<script type="text/javascript">
var Customer = (function () {
var instance;
function init() {
var dr = {};
function FailedCallback(xhr, ajaxOptions, thrownError) {
if (xhr.responseJSON.Message != undefined) {
var msg = new String(xhr.responseJSON.Message);
var event = jQuery.Event("ajaxerror")
event.data = msg
$(instance).trigger(event);
if (msg.contains("login") > 0) {
window.location.href = websiteBaseUrl + "login.aspx?from=" + encodeURIComponent(window.location.href);
} else {
}
} else {
alert(xhr.status + ' - ' + thrownError + '\n\n' + xhr.responseText);
}
};
function WebServerCallback(rawresult) {
var data = jQuery.parseJSON(rawresult.d);
dr = data;
var event = jQuery.Event("dataloaded");
jQuery(instance).trigger(event, dr);
if (!event.isDefaultPrevented())
refreshForm();
};
function WebServerSaveCallback(rawresult) {
var data = jQuery.parseJSON(rawresult.d);
dr = data;
var event = jQuery.Event("datasaved");
jQuery(instance).trigger(event, dr);
if (!event.isDefaultPrevented()) {
refreshForm();
}
};
function NewCustomer() {
WebServerCall("GetCustomerData", WebServerCallback, FailedCallback, "{'CustomerID':'-1'}")
};
function LoadCustomer(CustomerID) {
WebServerCall("GetCustomerData", WebServerCallback, FailedCallback, "{'CustomerID':'" + CustomerID + "'}")
};
function refreshForm() {
if (dr.CustomerID == undefined) {
throw "Customer not loaded... Call New or Load";
}
$('#customer-CustomerID').val(dr.CustomerID);
$('#customer-CustomerName').val(dr.CustomerName);
$('#customer-CustomerSince').val(new Date(dr.CustomerSince).toDateInputValue());
checkBoxCheck($('#customer-VIP'), dr.VIP);
checkBoxCheck($('#customer-OnHold'), dr.OnHold);
checkBoxCheck($('#customer-Tax1Exempt'), dr.Tax1Exempt);
checkBoxCheck($('#customer-Tax2Exempt'), dr.Tax2Exempt);
$('#customer-OnHoldReason').val(dr.OnHoldReason);
$('#customer-PrimaryContactID').val(dr.PrimaryContactID);
$('#customer-DefaultEmployeeID').val(dr.DefaultEmployeeID);
$('#customer-Phone1').val(dr.Phone1);
$('#customer-Phone2').val(dr.Phone2);
$('#customer-Address1').val(dr.Address1);
$('#customer-Address2').val(dr.Address2);
$('#customer-Address3').val(dr.Address3);
$('#customer-City').val(dr.City);
$('#customer-Province').val(dr.Province);
$('#customer-Country').val(dr.Country);
$('#customer-PostalCode').val(dr.PostalCode);
$('#customer-Description').val(dr.Description);
};
function refreshDR() {
if (dr.CustomerID == undefined) {
throw "Customer not loaded... Call New or Load";
}
dr.CustomerID = $('#customer-CustomerID').val();
dr.CustomerName = $('#customer-CustomerName').val();
dr.CustomerSince = new Date($('#customer-CustomerSince').val());
dr.VIP = checkBoxCheck($('#customer-VIP'));
dr.OnHold = checkBoxCheck($('#customer-OnHold'));
dr.Tax1Exempt = checkBoxCheck($('#customer-Tax1Exempt'));
dr.Tax2Exempt = checkBoxCheck($('#customer-Tax2Exempt'));
dr.OnHoldReason = $('#customer-OnHoldReason').val();
dr.PrimaryContactID = $('#customer-PrimaryContactID').val();
dr.DefaultEmployeeID = $('#customer-DefaultEmployeeID').val();
dr.Phone1 = $('#customer-Phone1').val();
dr.Phone2 = $('#customer-Phone2').val();
dr.Address1 = $('#customer-Address1').val();
dr.Address2 = $('#customer-Address2').val();
dr.Address3 = $('#customer-Address3').val();
dr.City = $('#customer-City').val();
dr.Province = $('#customer-Province').val();
dr.Country = $('#customer-Country').val();
dr.PostalCode = $('#customer-PostalCode').val();
dr.Description = $('#customer-Description').val();
};
function SaveCustomer() {
if (dr.CustomerID == undefined) {
throw "Customer not loaded... Call New or Load";
}
var data = "{'CustomerID':'" + $("#customer-CustomerID").val() + "','json':'" + JSON.stringify(dr) + "'}";
WebServerCall("UpdateCustomerData", WebServerSaveCallback, FailedCallback, data)
};
return {
datarow: function () { return dr; },
create: NewCustomer,
load: LoadCustomer,
save: SaveCustomer,
loadData: refreshDR,
loadForm: refreshForm
};
};
return {
getInstance: function () {
if (!instance) {
instance = init();
}
return instance;
},
hasInstance: function () {
return (instance);
}
};
})();
Customer.html
<div class="ui-corner-all fieldcontainer">
<div class="ui-corner-all fielddiv">
<label class="ui-corner-all " for="customer-CustomerName">Name:</label>
<input class="ui-corner-all " type="text" id="customer-CustomerName" />
<input type="hidden" id="customer-CustomerID" />
</div>
<div class="ui-corner-all fielddiv">
<label class="ui-corner-all " for="customer-CustomerSince">Since:</label>
<input class="ui-corner-all " type="date" id="customer-CustomerSince" />
<input class="ui-corner-all " type="checkbox" id="customer-VIP" title="VIP" />
<label class="ui-corner-all" for="customer-VIP">VIP</label>
</div>
<div class="ui-corner-all fielddiv">
<input class="ui-corner-all " type="checkbox" id="customer-OnHold" title="On Hold" />
<label class="ui-corner-all" for="customer-OnHold">On Hold</label>
<input class="ui-corner-all " type="checkbox" id="customer-Tax1Exempt" title="GST Exempt" />
<label class="ui-corner-all" for="customer-Tax1Exempt">GST Exempt</label>
<input class="ui-corner-all " type="checkbox" id="customer-Tax2Exempt" title="PST Exempt" />
<label class="ui-corner-all" for="customer-Tax2Exempt">PST Exempt</label>
</div>
<div class="ui-corner-all fielddiv ">
<label class="ui-corner-all " for="customer-OnHoldReason">On Hold/Acct:</label>
<textarea class="ui-corner-all " style="vertical-align: middle;" id="customer-OnHoldReason"></textarea>
</div>
<div class="ui-corner-all fielddiv ">
<label class="ui-corner-all " for="customer-PrimaryContactID">Primary Contact:</label>
<select id="customer-PrimaryContactID" class="ui-corner-all "></select>
<input type="button" id="customer-NewContact" class="ui-corner-all " value="New Contact" />
</div>
<div class="ui-corner-all fielddiv ">
<label class="ui-corner-all " for="customer-DefaultEmployeeID">Default Employee:</label>
<select id="customer-DefaultEmployeeID" class="ui-corner-all "></select>
</div>
<div class="ui-corner-all fielddiv ">
<label class="ui-corner-all " for="customer-Phone1">Phone 1:</label>
<input class="ui-corner-all " type="text" id="customer-Phone1" />
</div>
<div class="ui-corner-all fielddiv ">
<label class="ui-corner-all " for="customer-Phone2">Phone 2:</label>
<input class="ui-corner-all " type="text" id="customer-Phone2" />
</div>
<div class="ui-corner-all fielddiv ">
<label class="ui-corner-all " for="customer-Address1">Address 1:</label>
<input class="ui-corner-all " type="text" id="customer-Address1" /><br />
<label class="ui-corner-all " for="customer-Address2">Address 2:</label>
<input class="ui-corner-all " type="text" id="customer-Address2" /><br />
<label class="ui-corner-all " for="customer-Address3">Address 3:</label>
<input class="ui-corner-all " type="text" id="customer-Address3" />
</div>
<div class="ui-corner-all fielddiv ">
<label class="ui-corner-all " for="customer-City">City:</label>
<input class="ui-corner-all " type="text" id="customer-City" /><br />
<label class="ui-corner-all " for="customer-Province">Province:</label>
<input class="ui-corner-all " type="text" id="customer-Province" /><br />
<label class="ui-corner-all " for="customer-Country">Country:</label>
<input class="ui-corner-all " type="text" id="customer-Country" />
</div>
<div class="ui-corner-all fielddiv ">
<label class="ui-corner-all " for="customer-PostalCode">PostalCode:</label>
<input class="ui-corner-all " type="text" id="customer-PostalCode" />
</div>
<div class="ui-corner-all fielddiv ">
<label class="ui-corner-all " for="customer-Description">Description:</label>
<textarea class="ui-corner-all " style="vertical-align: middle;" id="customer-Description"></textarea>
</div>
<div style="width: 100%; text-align:center;">
<input class="ui-corner-all " id="customer-Submit" type="submit" value="Create" /> <input class="ui-corner-all " id="customer-Cancel" type="button" value="Cancel" />
</div>
</div>
<script type="text/javascript" src="../common.js"></script>
<script type="text/javascript" src="../Customer.js"></script>
<script type="text/javascript" >
var custIDField = $('#customer-CustomerID');
var customer; // dataloaded, datasaved events passing dr
var employees;
var contacts;
function getEmployeesCallback(rawresult) {
employees = jQuery.parseJSON(rawresult.d);
loadEmployeesDropDown();
};
function loadEmployeesDropDown() {
var ddl = $("#customer-DefaultEmployeeID");
ddl.empty();
$.each(employees, function (i, item) {
var option = $('<option>').val(item.EmployeeID).text(item.EmployeeName);
if (item.EmployeeID == customer.datarow().EmployeeID) {
option.attr('selected', 'selected');
}
option.appendTo(ddl);
});
};
function getContactsCallback(rawresult) {
contacts = jQuery.parseJSON(rawresult.d);
loadContactsDropDown();
};
function loadContactsDropDown() {
var ddl = $("#customer-PrimaryContactID");
ddl.empty();
$.each(contacts, function (i, item) {
var option = $('<option>').val(item.ContactID).text(item.ContactName);
if (item.ContactID == customer.datarow().PrimaryContactID) {
option.attr('selected', 'selected');
}
option.appendTo(ddl);
});
};
$(function () {
customer = Customer.getInstance();
if (customer.datarow().CustomerID == undefined) {
if ($.isNumeric(custIDField.val())) {
customer.load(custIDField.val());
} else {
var qID = getParameterByName('customerid');
if ($.isNumeric(qID)) {
customer.load(qID);
} else {
customer.create();
}
}
}
// customer.loadForm();
$(customer).on("ajaxerror", function (msg) {
//alert("Ajax Error " + msg);
});
$(customer).on("dataloaded", function (e, data) {
customer.loadForm();
//contacts
if (contacts == undefined) {
var withid = -1;
if (customer.datarow().CustomerID != undefined) {
if (customer.datarow().CustomerID > 0) {
withid = customer.datarow().CustomerID;
}
}
if (withid != -1) {
WebServerCall("GetCustomerContacts", getContactsCallback, FailedCallback, "{'CustomerID':'" + customer.datarow().CustomerID + "'}");
} else {
WebServerCall("GetContacts", getContactsCallback, FailedCallback);
}
} else {
loadContactsDropDown();
}
});
$(customer).on("datasaved", function (e, data) {
alert("Customer " + data.CustomerID + " has been saved.");
});
$("#customer-form").on("submit", function (e) {
e.preventDefault();
customer.loadData();
customer.save();
});
$("#customer-Cancel").on("click", function (e) {
e.preventDefault();
customer.load($("#customer-CustomerID").val());
});
//employees
if (employees == undefined) {
WebServerCall("GetEmployees", getEmployeesCallback, FailedCallback);
} else {
loadEmployeesDropDown();
}
});
</script>
</form>
common.js
`var webserviceBaseUrl = '/WebService.asmx/';
var websiteBaseUrl = '/';
if (!('contains' in String.prototype)) {
String.prototype.contains = function (str, startIndex) {
if (startIndex == undefined)
startIndex = 0;
return ''.indexOf.call(this, str, startIndex) !== -1;
};
}
if (!('contains' in Array.prototype)) {
Array.prototype.contains = function (arr, startIndex) {
if (startIndex == undefined)
startIndex = 0;
return ''.indexOf.call(this, arr, startIndex) !== -1;
};
}
Date.prototype.toDateTimeLocal = (function () {
var now = new Date(this);
var month = (now.getMonth() + 1);
var day = now.getDate();
var hour = now.getHours();
var min = now.getMinutes();
if (month < 10)
month = "0" + month;
if (day < 10)
day = "0" + day;
if (hour < 10)
hour = "0" + hour;
if (min < 10)
min = "0" + min;
var today = now.getFullYear() + '-' + month + '-' + day + 'T' + hour + ':' + min;
return today;
});
Date.prototype.toDateInputValue = (function () {
var now = new Date(this);
var month = (now.getMonth() + 1);
var day = now.getDate();
if (month < 10)
month = "0" + month;
if (day < 10)
day = "0" + day;
var today = now.getFullYear() + '-' + month + '-' + day;
return today;
});
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
function checkBoxCheck(checkBox, checked) {
if(checked){
if (checked == 'true') {
checkBox.attr('checked', 'checked');
return true;
} else {
checkBox.removeAttr('checked');
return false;
}
} else {
if (checkBox.attr('checked') == 'checked') {
return true;
} else {
return false;
}
}
}
function WebServerCall(functionName, successCallback, failedCallback, datatoSend) {
$.ajax({
type: "POST",
url: webserviceBaseUrl + functionName,
data: datatoSend,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: successCallback,
error: failedCallback,
failure: failedCallback
});
}
function FailedCallback(xhr, ajaxOptions, thrownError) {
if (xhr.responseJSON.Message != undefined) {
var msg = new String(xhr.responseJSON.Message);
alert(msg);
if (msg.contains("login") > 0)
window.location.href = websiteBaseUrl + "login.aspx?from=" + encodeURIComponent(window.location.href);
} else {
alert(xhr.status + ' - ' + thrownError + '\n\n' + xhr.responseText);
}
}
`
Try something like this. Create a file where your JS resides, CustomerPopupForm.html and put your popup form html inside it:
<div id="dialog-form" title="Create new user">
<p class="validateTips">All form fields are required.</p>
<form>
<fieldset>
<label for="name">Name</label>
<input type="text" name="name" id="name" value="Jane Smith" class="text ui-widget-content ui-corner-all">
<label for="email">Email</label>
<input type="text" name="email" id="email" value="jane#smith.com" class="text ui-widget-content ui-corner-all">
<label for="password">Password</label>
<input type="password" name="password" id="password" value="xxxxxxx" class="text ui-widget-content ui-corner-all">
<!-- Allow form submission with keyboard without duplicating the dialog button -->
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>
Create your function to load the html and show the popup form:
function showPopup(closeCallback){
$("#divPopupHolder").remove(); //remove the holder div from a previous call
$("body").append("<div id='divPopupHolder'>" + + "</div>"); //add a div to document to hold the popup
$.get( "CustomerPopupForm.html", function( data ) {
$("#divPopupHolder").html(data); //add the popup to the new div.
});
dialog = $( "#dialog-form" ).dialog({ //show the dialog
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
"Create an account": addUser,
Cancel: function() {
dialog.dialog( "close" );
}
},
close: function() {
if (closeCallback){ //you could do this for other buttons as well so the caller is notified when the dialog is closed.
closeCallback();
}
}
});
}
then call showPopup() from where you need to show the dialog.
So, after much learning (this tutorial was very helpful: https://code.tutsplus.com/courses/30-days-to-learn-jquery) and much trying I eventually made it work... not exactly sure what my problem was but this is what I wish I could find before:
This shows how to create functional single instance "class" (prob not class, plugin, or module i guess is the better term) with "namespace"
I found it was very convenient to use the namespace var as the event "target"
What do you think?
file: test.js
var XMen = {
Customer: (function($, undefined) {
var instance;
var datarow = {};
function init() {
function privateLoadData(idNumber) {
//Load up data
datarow = {IDField: idNumber, ValueField: 'something'};
$(XMen).trigger('XMen.CustomerDataLoaded');
};
function privateDisplay() {
console.log(datarow);
$(XMen).trigger('XMen.CustomerDataDisplayed');
};
return {
dr: function() { return datarow; }, //needs to be wrapped in function to get changes
load: privateLoadData,
display: privateDisplay
};
};
return {
getInstance: function () {
if (!instance) {
instance = init();
}
return instance;
},
hasInstance: function () {
return (instance);
}
};
})(jQuery),
SalesOrder: (function($, undefined) { // another one like above? })(jQuery)
}
You would then include this file on your page
file: test.html
<body>
<h1>testing</h1>
<div id="testing"></div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="test.js"></script>
<script>
var customer = XMen.Customer.getInstance();
(function ($) {
$(XMen).on('XMen.CustomerDataDisplayed', function (e, data) {
console.log("test - XMen.CustomerDataDisplayed");//, e, data);
})
$(XMen).on('XMen.CustomerDataLoaded', function (e, data) {
console.log("test - XMen.CustomerDataLoaded");//, e, data);
})
console.log("test - Loading 8");
customer.load(8);
console.log("test - loading test2.html");
$("#testing").load("test2.html", function () {
console.log("test - finished loading test2.html");
});
setTimeout(function () {
console.log("test - displaying customer...");
customer.display();
}, 2000);
})(jQuery);
</script>
In test2.html we dont include any scripts since they are already included in test.html
file: test2.html
<div id="test2">
<h1>This is test2.html</h1>
<button id="btnTest">Test</button>
</div>
<script>
(function ($) {
$(XMen).on('XMen.CustomerDataDisplayed', function (e, data) {
console.log("test2 - XMen.CustomerDataDisplayed");//, e, data);
})
$(XMen).on('XMen.CustomerDataLoaded', function (e, data) {
console.log("test2 - XMen.CustomerDataLoaded");//, e, data);
})
})(jQuery);
console.log("test2 - displaying customer...");
customer.display();
</script>