How to call jQuery with button - html

I am editing a website that is automated with java, I am creating a menu to hide few divs that are repated with same id and same class. I managed to do it already with jQuery with this:
$(document).ready(function () {
$('[id]').each(function () {
var ids = $('[id=catalog_container' + this.id + ']');
if (ids.length > 1 && ids[0] == this) {
$(ids[0]).remove();
}
});
});
I need to do it in another way, but I don't know how to do it. I want to do it with button.
<li><a><button onclick="myFunction()">1 Catalog</button></a></li>
Something like that, when I press that button, to remove first duplicated id, when I press another button to remove second duplicated ID, and so on.
Help me please.
I'd like to know how to do it like this too: not to load script automatically as it does, I want to know how to call it.

I managed to find a solution, I will post it for anyone to see it, and give feedback if you want!
<!-- Hide second id -->
$(document).ready(function () {
$("#Catalog").click(function () {
$('[id]').each(function () {
var ids = $('[id=' + this.id + ']');
if (ids.length > 1 && ids[0] == this) {
$(ids[1]).hide();
$(ids[0]).show();
}
});
});
});
$(document).ready(function () {
$("#Catalog2").click(function () {
$('[id]').each(function () {
var ids = $('[id=' + this.id + ']');
if (ids.length > 1 && ids[0] == this) {
$(ids[0]).hide();
$(ids[1]).show();
}
});
});
});
<!-- Hide First ID -->
$(document).ready(function () {
$("#Catalog").click(function () {
$('[class]').each(function () {
var ids = $('[class=category-title' + this.id + ']');
if (ids.length > 1 && ids[0] == this) {
$(ids[1]).hide();
$(ids[0]).show();
}
});
});
});
$(document).ready(function () {
$("#Catalog2").click(function () {
$('[class]').each(function () {
var ids = $('[class=category-title' + this.id + ']');
if (ids.length > 1 && ids[0] == this) {
$(ids[0]).hide();
$(ids[1]).show();
}
});
});
});
<ul>
<li><a><button style="color:black;" id="Catalog">1 Catalog</button></a></li>
<li><a><button style="color:black;" id="Catalog2">2 Catalog</button></a></li>
</ul>

Related

jQuery ui-tabs .bind("tabsactivate", function (event, ui) does not work when reloaded

I am dynamically creating a table (on click of a button) and storing the current tab index when the tab is activated (clicked on). This works the first time I create the table; however, if I recreate the tab to load different data (hide this form, go back to the previous form and click the button to display) then the following does not work:
$('#dayTabs').tabs();
$('#dayTabs').bind("tabsactivate", function (event, ui) {
alert('oldTab = ' + ui.oldTab.index());
alert('newTab = ' + ui.newTab.index());
sessionStorage.setItem('ssCurrentTab', ui.newTab.index());
});
However, the following still works:
$("#menuTabs a").click(function(e){
The full context is:
$('#updateDailyProgram').click(function() {
sessionStorage.setItem('ssFromDate', $("#updateFromDate").val());
$("#menuDetails").empty();
sessionStorage.setItem('ssCurrentDate', $("#updateFromDate").val());
sessionStorage.setItem('ssCurrentTab', 0);
$("#menuDetails").append("<ul id='menuTabs' class='nav nav-tabs'></ul>").find('ul');
var newDateString = $("#updateFromDate").val();
var firstTab = "Y";
for (var i = 0; i < sessionStorage.getItem('ssProgramDays'); i++){
if (firstTab === "Y"){
$("#menuTabs").append("<li class='nav-item'><a href='#home' class='nav-link active' name='"+newDateString+"'>"+newDateString+"</a></li>");
firstTab = "N";
}else{
$("#menuTabs").append("<li class='nav-item'><a href='#home' class='nav-link' name='"+newDateString+"'>"+newDateString+"</a></li>");
}
//Add 1 day to date
newDateString = moment(newDateString, 'DD/MM/YYYY').add(1, 'days');
newDateString = newDateString.format('DD/MM/YYYY');
};
$('#showProgramUpdateForm').hide();
$('#programEditForm').show();
//Show first tab
loadProgramDailyTable($("#updateFromDate").val());
$("#menuTabs a:eq(0)").tab('show');
$('#dayTabs').tabs();
$('#dayTabs').bind("tabsactivate", function (event, ui) {
alert('oldTab = ' + ui.oldTab.index());
alert('newTab = ' + ui.newTab.index());
sessionStorage.setItem('ssCurrentTab', ui.newTab.index());
});
$("#menuTabs a").click(function(e){
e.preventDefault();
sessionStorage.setItem('ssCurrentDate', $(this).attr('name'));
loadProgramDailyTable($(this).attr('name'));
$(this).tab('show');
});
});
HTML:
<div id="dayTabs" class="container">
<span id="menuDetails">
</span>
</div>
I realised that I was mixing bootstrap tabs with jQuery ui-tabs. The solution wss to:
Delete:
$('#dayTabs').tabs();
$('#dayTabs').bind("tabsactivate", function (event, ui) {
alert('oldTab = ' + ui.oldTab.index());
alert('newTab = ' + ui.newTab.index());
sessionStorage.setItem('ssCurrentTab', ui.newTab.index());
});
And add:
sessionStorage.setItem('ssCurrentTab', $(e.target).closest('li').index());
As per:
$("#menuTabs a").click(function(e){
e.preventDefault();
sessionStorage.setItem('ssCurrentTab', $(e.target).closest('li').index());
sessionStorage.setItem('ssCurrentDate', $(this).attr('name'));
loadProgramDailyTable($(this).attr('name'));
$(this).tab('show');
});

AngularJS ng-if does not work in all modules?

I am trying to show/hide my drag and drop when a document comes to the screen. I used AngularJS and it worked. However, it does not work in all modules. Although I same always the same code but from other modules :
working code :
<div ngf-drop ngf-select ng-model="files" ngf-multiple="true" ngf-allow-dir="true" ng-show="dropIsVisible === true">
<div class="drop-area-full-page">
<div class="drop-area-full-page__graphic"></div>
<div class="drop-area-full-page__info" id="drop-area-full-page__info" ng-bind-html="dropText"></div>
</div>
</div>
And in AngularJS:
$window.addEventListener("dragenter", function (e) {
if (isFile(e)) {
lastTarget = e.target;
$scope.dropIsVisible = true;
name = getName($scope, getParent());
$scope.dropText =
"<b> Dokument ablegen zu </b>" + "<b>" + name+ "</b>";
}
});
$window.addEventListener("dragleave", function (e) {
e.preventDefault();
if (e.target === document || e.target === lastTarget) {
$scope.dropIsVisible = false;
}
});
$window.addEventListener("dragover", function (e) {
e.preventDefault();
$scope.dropIsVisible = true;
});
function getParent() {
return {
entityName: $stateParams.entity,
id: $scope.parentId
};
}
$window.addEventListener("drop", function (e) {
e.preventDefault();
$scope.dropIsVisible = true;
var qs = e.dataTransfer.files[0].name;
var parent = getParent();
DokumentUploadMixin.Prepare(qs, e.dataTransfer.files[0], $scope, parent, projection, qs);
//$window.location.href = routeUtils.getCreateDokumentUrl("Dokument", getParent(), projection, qs);
});
};
And the code that is not working:
<div ngf-drop ngf-select ng-model="files" ngf-multiple="true" ngf-allow-dir="true" ng-show="dropIsVisible === true">
<div class="drop-area-full-page">
<div class="drop-area-full-page__graphic"></div>
<div class="drop-area-full-page__info" id="drop-area-full-page__info" ng-bind-html="dropText"></div>
</div>
</div>
Which is the same ....
Are there any tips that I should do for making it work in all modules?
the answer was that i showld apply the scope to event listener cause i added custom event listeners, which are not tracked by Angularjs. In order to make it work applying inside addEventListener callback with $scope.$apply to tell angular update the model.
$window.addEventListener("dragenter", function (e) {
$scope.$apply(function() {
if (isFile(e)) {
lastTarget = e.target;
$scope.dropIsVisible = true;
name = getName($scope, getParent());
$scope.dropText =
"<b> Dokument ablegen zu </b>" + "<b>" + name+ "</b>";
}
});
});
$window.addEventListener("dragleave", function (e) {
$scope.$apply(function() {
e.preventDefault();
if (e.target === document || e.target === lastTarget) {
$scope.dropIsVisible = false;
}
});
});
$window.addEventListener("dragover", function (e) {
$scope.$apply(function() {
e.preventDefault();
$scope.dropIsVisible = true;
});
});

How to create function for Reset Form with use kendo element and other HTML element

I want create function for reset form with use kendo element and other HTML element. I create this function:
function resetForm() {
var formName = $(this).data("form");
var form = $(formName);
if (form) {
//orginal reset
form.trigger("reset");
//custom reset
$(formName + " input").each(function () {
var cb = $(this).data("kendoDropDownList");
if (cb) {
cb.value("");
cb.text("");
}
});
}
}
Not work correctly!
I found this way:
if (form) {
//custom reset
$(formName + " input[data-role='dropdownlist']").each(function () {
var item = $(this).data("kendoDropDownList");
if (item && $(this).attr('id') != 'AgeType' && $(this).attr('id') != 'AllAnyType') {
item.value("");
item.text("");
}
});
$(formName + " input.k-textbox").each(function () {
$(this).val("");
});
$(formName + " input[data-role='numerictextbox']").not("#TopNumber").each(function () {
var item = $(this).data("kendoNumericTextBox");
if (item) {
item.value("");
}
});
$(formName + " textarea").each(function () {
$(this).val("");
});
$(formName + " :checkbox").each(function () {
this.checked = !this.checked;
});
$(formName + " input[type=text]").each(function () {
$(this).val("");
});
}

Polyfill HTML5 form attribute (for input fields)

This is the markup I use:
<input type="text" form="myform" name="inp1" />
<form id="myform" name="myform">
...
</form>
Now I realized that it does not work for old IE and therefore I am searching for a HTML 5 polyfill.
Anyone aware of a certain polyfill which covers this HTML5 feature?
I wrote this polyfill to emulate such feature by duplicating fields upon form submission, tested in IE6 and it worked fine.
(function($) {
/**
* polyfill for html5 form attr
*/
// detect if browser supports this
var sampleElement = $('[form]').get(0);
var isIE11 = !(window.ActiveXObject) && "ActiveXObject" in window;
if (sampleElement && window.HTMLFormElement && (sampleElement.form instanceof HTMLFormElement || sampleElement instanceof window.HTMLFormElement) && !isIE11) {
// browser supports it, no need to fix
return;
}
/**
* Append a field to a form
*
*/
$.fn.appendField = function(data) {
// for form only
if (!this.is('form')) return;
// wrap data
if (!$.isArray(data) && data.name && data.value) {
data = [data];
}
var $form = this;
// attach new params
$.each(data, function(i, item) {
$('<input/>')
.attr('type', 'hidden')
.attr('name', item.name)
.val(item.value).appendTo($form);
});
return $form;
};
/**
* Find all input fields with form attribute point to jQuery object
*
*/
$('form[id]').submit(function(e) {
// serialize data
var data = $('[form='+ this.id + ']').serializeArray();
// append data to form
$(this).appendField(data);
}).each(function() {
var form = this,
$fields = $('[form=' + this.id + ']');
$fields.filter('button, input').filter('[type=reset],[type=submit]').click(function() {
var type = this.type.toLowerCase();
if (type === 'reset') {
// reset form
form.reset();
// for elements outside form
$fields.each(function() {
this.value = this.defaultValue;
this.checked = this.defaultChecked;
}).filter('select').each(function() {
$(this).find('option').each(function() {
this.selected = this.defaultSelected;
});
});
} else if (type.match(/^submit|image$/i)) {
$(form).appendField({name: this.name, value: this.value}).submit();
}
});
});
})(jQuery);
The polyfill above doesn't take into account the Edge browser. I have amended it to use feature detection, which I have tested in IE7+, Edge, Firefox (mobile/desktop), Chrome (mobile/desktop), Safari (mobile/desktop), and Android browser 4.0.
(function($) {
/**
* polyfill for html5 form attr
*/
// detect if browser supports this
var SAMPLE_FORM_NAME = "html-5-polyfill-test";
var sampleForm = $("<form id='" + SAMPLE_FORM_NAME + "'/>");
var sampleFormAndHiddenInput = sampleForm.add($("<input type='hidden' form='" + SAMPLE_FORM_NAME + "'/>"));
sampleFormAndHiddenInput.prependTo('body');
var sampleElementFound = sampleForm[0].elements[0];
sampleFormAndHiddenInput.remove();
if (sampleElementFound) {
// browser supports it, no need to fix
return;
}
/**
* Append a field to a form
*
*/
$.fn.appendField = function(data) {
// for form only
if (!this.is('form')) return;
// wrap data
if (!$.isArray(data) && data.name && data.value) {
data = [data];
}
var $form = this;
// attach new params
$.each(data, function(i, item) {
$('<input/>')
.attr('type', 'hidden')
.attr('name', item.name)
.val(item.value).appendTo($form);
});
return $form;
};
/**
* Find all input fields with form attribute point to jQuery object
*
*/
$('form[id]').submit(function(e) {
// serialize data
var data = $('[form='+ this.id + ']').serializeArray();
// append data to form
$(this).appendField(data);
}).each(function() {
var form = this,
$fields = $('[form=' + this.id + ']');
$fields.filter('button, input').filter('[type=reset],[type=submit]').click(function() {
var type = this.type.toLowerCase();
if (type === 'reset') {
// reset form
form.reset();
// for elements outside form
$fields.each(function() {
this.value = this.defaultValue;
this.checked = this.defaultChecked;
}).filter('select').each(function() {
$(this).find('option').each(function() {
this.selected = this.defaultSelected;
});
});
} else if (type.match(/^submit|image$/i)) {
$(form).appendField({name: this.name, value: this.value}).submit();
}
});
});
})(jQuery);
I improved patstuart's polyfill, such that:
a form can now be submitted several times, e.g. when using the target attribute (external fields were duplicated previously)
reset buttons now work properly
Here it is:
(function($) {
/**
* polyfill for html5 form attr
*/
// detect if browser supports this
var SAMPLE_FORM_NAME = "html-5-polyfill-test";
var sampleForm = $("<form id='" + SAMPLE_FORM_NAME + "'/>");
var sampleFormAndHiddenInput = sampleForm.add($("<input type='hidden' form='" + SAMPLE_FORM_NAME + "'/>"));
sampleFormAndHiddenInput.prependTo('body');
var sampleElementFound = sampleForm[0].elements[0];
sampleFormAndHiddenInput.remove();
if (sampleElementFound) {
// browser supports it, no need to fix
return;
}
/**
* Append a field to a form
*
*/
var CLASS_NAME_POLYFILL_MARKER = "html-5-polyfill-form-attr-marker";
$.fn.appendField = function(data) {
// for form only
if (!this.is('form')) return;
// wrap data
if (!$.isArray(data) && data.name && data.value) {
data = [data];
}
var $form = this;
// attach new params
$.each(data, function(i, item) {
$('<input/>')
.attr('type', 'hidden')
.attr('name', item.name)
.attr('class', CLASS_NAME_POLYFILL_MARKER)
.val(item.value).appendTo($form);
});
return $form;
};
/**
* Find all input fields with form attribute point to jQuery object
*
*/
$('form[id]').submit(function(e, origSubmit) {
// clean up form from last submit
$('.'+CLASS_NAME_POLYFILL_MARKER, this).remove();
// serialize data
var data = $('[form='+ this.id + ']').serializeArray();
// add data from external submit, if needed:
if (origSubmit && origSubmit.name)
data.push({name: origSubmit.name, value: origSubmit.value})
// append data to form
$(this).appendField(data);
})
//submit and reset behaviour
$('button[type=reset], input[type=reset]').click(function() {
//extend reset buttons to fields with matching form attribute
// reset form
var formId = $(this).attr("form");
var formJq = $('#'+formId);
if (formJq.length)
formJq[0].reset();
// for elements outside form
if (!formId)
formId = $(this).closest("form").attr("id");
$fields = $('[form=' + formId + ']');
$fields.each(function() {
this.value = this.defaultValue;
this.checked = this.defaultChecked;
}).filter('select').each(function() {
$(this).find('option').each(function() {
this.selected = this.defaultSelected;
});
});
});
$('button[type=submit], input[type=submit], input[type=image]').click(function() {
var formId = $(this).attr("form") || $(this).closest("form").attr("id");
$('#'+formId).trigger('submit', this); //send clicked submit as extra parameter
});
})(jQuery);
after reading thru the docs of webshim it seems it has a polyfill for that.
http://afarkas.github.io/webshim/demos/demos/webforms.html
I made a vanilla JavaScript polyfill based on the above polyfills and uploaded it on GitHub: https://github.com/Ununnilium/form-attribute-polyfill.
I also added a custom event to handle the case when submit is processed by JavaScript and not directly by the browser. I tested the code only shortly with IE 11, so please check it yourself before use. The polling should maybe be replaced by a more efficient detection function.
function browserNeedsPolyfill() {
var TEST_FORM_NAME = "form-attribute-polyfill-test";
var testForm = document.createElement("form");
testForm.setAttribute("id", TEST_FORM_NAME);
testForm.setAttribute("type", "hidden");
var testInput = document.createElement("input");
testInput.setAttribute("type", "hidden");
testInput.setAttribute("form", TEST_FORM_NAME);
testForm.appendChild(testInput);
document.body.appendChild(testInput);
document.body.appendChild(testForm);
var sampleElementFound = testForm.elements.length === 1;
document.body.removeChild(testInput);
document.body.removeChild(testForm);
return !sampleElementFound;
}
// Ideas from jQuery form attribute polyfill https://stackoverflow.com/a/26696165/2372674
function executeFormPolyfill() {
function appendDataToForm(data, form) {
Object.keys(data).forEach(function(name) {
var inputElem = document.createElement("input");
inputElem.setAttribute("type", "hidden");
inputElem.setAttribute("name", name);
inputElem.value = data[name];
form.appendChild(inputElem);
});
}
var forms = document.body.querySelectorAll("form[id]");
Array.prototype.forEach.call(forms, function (form) {
var fields = document.querySelectorAll('[form="' + form.id + '"]');
var dataFields = [];
Array.prototype.forEach.call(fields, function (field) {
if (field.disabled === false && field.hasAttribute("name")) {
dataFields.push(field);
}
});
Array.prototype.forEach.call(fields, function (field) {
if (field.type === "reset") {
field.addEventListener("click", function () {
form.reset();
Array.prototype.forEach.call(dataFields, function (dataField) {
if (dataField.nodeName === "SELECT") {
Array.prototype.forEach.call(dataField.querySelectorAll('option'), function (option) {
option.selected = option.defaultSelected;
});
} else {
dataField.value = dataField.defaultValue;
dataField.checked = dataField.defaultChecked;
}
});
});
} else if (field.type === "submit" || field.type === "image") {
field.addEventListener("click", function () {
var obj = {};
obj[field.name] = field.value;
appendDataToForm(obj, form);
form.dispatchEvent(eventToDispatch);
});
}
});
form.addEventListener("submit", function () {
var data = {};
Array.prototype.forEach.call(dataFields, function (dataField) {
data[dataField.name] = dataField.value;
});
appendDataToForm(data, form);
});
});
}
// Poll for new forms and execute polyfill for them
function detectedNewForms() {
var ALREADY_DETECTED_CLASS = 'form-already-detected';
var newForms = document.querySelectorAll('form:not([class="' + ALREADY_DETECTED_CLASS + '"])');
if (newForms.length !== 0) {
Array.prototype.forEach.call(newForms, function (form) {
form.className += ALREADY_DETECTED_CLASS;
});
executeFormPolyfill();
}
setTimeout(detectedNewForms, 100);
}
// Source: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent
function polyfillCustomEvent() {
if (typeof window.CustomEvent === "function") {
return false;
}
function CustomEvent(event, params) {
params = params || {bubbles: false, cancelable: false, detail: undefined};
var evt = document.createEvent('CustomEvent');
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
return evt;
}
CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent;
}
if (browserNeedsPolyfill()) {
polyfillCustomEvent(); // IE is missing CustomEvent
// This workaround is needed if submit is handled by JavaScript instead the browser itself
// Source: https://stackoverflow.com/a/35155789/2372674
var eventToDispatch = new CustomEvent("submit", {"bubbles": true, "cancelable": true});
detectedNewForms(); // Poll for new forms and execute form attribute polyfill for new forms
}
I take some time to send an update for this polyfill because it doesn't work with MS Edge.
I add 2 line to fix it :
var isEdge = navigator.userAgent.indexOf("Edge");
if (sampleElement && window.HTMLFormElement && sampleElement.form instanceof HTMLFormElement && !isIE11 && isEdge == -1) {
// browser supports it, no need to fix
return;
}
UPDATE: Edge now support it:
https://caniuse.com/#feat=form-attribute

How to make a single button appear on only 1 jquery function

I have a button called add to profile, all I need to know is how do I make it so its only on the last jQuery div, after the last next.
Like question 1, then next, question 2 back and next, question 3, back and add button.
So if you can really help me out here quick I'd really appreciate it.
Here's my code:
<script>
$(document).ready(function () {
var oldOption;
var counter = 1;
var maxThings = 4;
var minThings = 1;
$("#2").hide();
$("#3").hide();
$("#4").hide();
$('#back').hide();
$("#forward").click(function () {
$("#1").hide();
$("#2").hide();
$("#3").hide();
$("#4").hide();
if (!(counter >= maxThings)) {
counter++;
}
$("#" + counter).show();
$('#back').show();
if (counter === maxThings) {
$('#forward').hide();
}
});
$("#back").click(function () {
$("#1").hide();
$("#2").hide();
$("#3").hide();
$("#4").hide();
if (!(counter <= 1)) {
counter--;
}
$("#" + counter).show();
$('#forward').show();
if (counter === minThings) {
$('#back').hide();
}
});
});
</script>
...
if (counter === maxThings) {
$('#forward').hide();
$("#AddToProfile").show();
} else {
$("#AddToProfile").hide();
}
...
And I really don't like youre coding :) You'll have to change code every time you'll add new div.
I would do something like that:
- Every div would have class question
- Every div's START visibility attribute would be defined in html (every div except first would have in style something like visibility:hidden)
<script>
$(document).ready(function () {
var oldOption;
var counter = 1;
var maxThings = 4;
var minThings = 1;
$('#back').hide();
$("#forward").click(function () {
$("div.question").hide();
if (!(counter >= maxThings)) {
counter++;
}
$("#" + counter).show();
$('#back').show();
if (counter === maxThings) {
$('#forward').hide();
}
});
$("#back").click(function () {
$("div.question").hide();
if (!(counter <= 1)) {
counter--;
}
$("#" + counter).show();
$('#forward').show();
if (counter === minThings) {
$('#back').hide();
}
});
});
</script>