Bootstrap Warnings Image I have two different types of bootstraps alerts (warning and danger). Danger alerts are always suppose to be on the page no matter what. Warning alerts happen when user clicks on the dropdown list carriers it displays a bootstrap warning notification. User has to click on 'x' for it to close. I need it to work when user click anywhere on the page or by clicking on the 'x'.
HomeController.cs
case "Carrier":
var carrierid = (from foo in db.Carriers
where foo.ID == warningid
select foo.WarningID).Single();
if (carrierid != null)
{
warning = (from warnings in db.Warnings
where warnings.IsActive == true && warnings.Id == carrierid
select warnings.WarningBody).SingleOrDefault();
if (warning != null)
{
warning = ("<div class=\"alert alert-warning alert-dismissible\" id=\"myWarning\" role=\"alert\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\"><span aria-hidden=\"true\">×</span></button><strong>" +
warning + "</strong></div>");
}
else
{
warning = "";
}
}
else
{
warning = "";
}
return Json(warning, JsonRequestBehavior.AllowGet);
default:
break;
warningwriter.js
//// warning display script takes a value of warningid and warningcaller
$(document).ready(function () {
var warningid = 0;
var warningcaller = "Universal";
loadWarnings(warningid, warningcaller);
});
$('#Phones').change(function () {
var warningid = $(this).val();
var warningcaller = "Phone";
loadWarnings(warningid, warningcaller);})
$('#Carriers').change(function () {
var warningid = $(this).val();
var warningcaller = "Carrier";
loadWarnings(warningid, warningcaller);})
function loadWarnings(warningid, warningcaller) {
$.getJSON("../Home/LoadWarnings", { warningID: warningid, warningCaller: warningcaller },
function (warning) {
var select = $('#warnings');
select.append(warning);
});
};
As Martin suggested, it's something you need to do in javascript. I haven't tested this, but it would be something like:
$(document).click(function (event) {
$(".alert").hide();
});
This is basically, clicking anywhere on the page will hide any displayed alert.
Since you have two different types of bootstraps alerts (danger and warning). You have to use ".alert-warning" because that is the one you want to get rid of when user did a mouse click anywhere on page. ".alert" is all of the bootstraps alerts, however, if you need to get rid of a certain type you can call the contextual classes(e.g., .alert-success, .alert-info, .alert-warning, and/or .alert-danger. https://v4-alpha.getbootstrap.com/components/alerts/
$(document).click(function (event) {
$(".alert-warning").hide();
});
$(document).ready(function () {
$("#myWarning").click(function () {
$(".alert").alert("close");
});
});
By doing this, u are making two things wrong:
You are binding the click event to an element, that possibly
doesnt exist when the page is loaded.
You are binding the click
event to a restricted element. This means that the alert wont be
closed when u click anywhere on the page. In this case, only clicks on #myWarning will close the alert.
Finally, you should use what #Bryan already posted :)
Edit:
Assuming that u have a set of alerts that u always want to close on page load, add to this elements a way to identify them, for example a class "close-on-screenclick"
$(document).click(function () {
$(".close-on-screenclick.alert").alert("close");
});
.This should close those elements whenever a click is made on the screen
Related
I have this section of javascript in my html that grabs a form input, puts it through a function and returns a json. I then want to either hide or show certain form elements based on the values in this json.
At the moment, i can do all of this fine except for changing the style.display properties of the elements im trying to hide/show, i can find them okay with getElementbyId (have tested this with other stuff) but the changes i make to the style don't seem to do anything.
As you can see below, i have put in a few alerts to make sure everything is working, and they all seem to align with what i need from the function. The alert showing style.display even matches up with what i'm trying to change it to, however even if it says "none", the form element still shows up.
<script type="text/javascript">
let selected = document.getElementById('selection1');
let optional_toggle = document.getElementById("optional_element");
let button = document.getElementById("button")
button.onclick = function() {
choice1 = selected.value;
fetch('/form_choice/' + choice1).then(function(response) {
response.json().then(function(data) {
if (data.show_optional === "True") {
optional_toggle.style.display = ""
window.alert("first part of if");
window.alert(optional_toggle.style.display);
window.alert(data.show_optional);
}
else {
optional_toggle.style.display = "none"
window.alert("second part of if");
window.alert(optional_toggle.style.display);
window.alert(data.show_optional);
console.log(optional_toggle);
}
}
)
}
)
}
</script>
Edit: i added the console.log lines in but nothing seems to show in the console.
console log image
The issue was that the page was reloading to it's original state after the script had been executed, so i stopped this by adding "; return false" after the function like so:
<script type="text/javascript">
let selected = document.getElementById('selection1');
let optional_toggle = document.getElementById("optional_element");
let button = document.getElementById("button")
button.onclick = function() {
choice1 = selected.value;
fetch('/form_choice/' + choice1).then(function(response) {
response.json().then(function(data) {
if (data.show_optional === "True") {
optional_toggle.style.display = ""
window.alert("first part of if");
window.alert(optional_toggle.style.display);
window.alert(data.show_optional);
}
else {
optional_toggle.style.display = "none"
window.alert("second part of if");
window.alert(optional_toggle.style.display);
window.alert(data.show_optional);
console.log(optional_toggle);
}
}
)
}
); return false
}
</script>
So I have a button that whenever clicked appends whatever the user entered below the input field. I want to make it so when clicked with an empty field nothing appends (essentially the function does not run).
Here is my code:
var ingrCount = 0
$("#addIngrButton").on('click', function() {
var ingredientInput = $("#ingredients").val().trim();
var ingredientSpace = $("<p>");
ingredientSpace.attr("id", "ingredient-" + ingrCount);
ingredientSpace.append(" " + ingredientInput);
var ingrClose = $("<button>");
ingrClose.attr("data-ingr", ingrCount);
ingrClose.addClass("deleteBox");
ingrClose.append("✖︎");
// Append the button to the to do item
ingredientSpace = ingredientSpace.prepend(ingrClose);
// Add the button and ingredient to the div
$("#listOfIngr").append(ingredientSpace);
// Clear the textbox when done
$("#ingredients").val("");
// Add to the ingredient list
ingrCount++;
if (ingredientInput === "") {
}
});
So I wanted to create an if statement saying when the input is blank then the function does not run. I think I may need to move that out of the on click function though. For the if statement I added a disabled attribute and then removed it when the input box contains something. But that turns the button another color and is not the functionality I want. Any ideas I can test out would help. If you need any more information please ask.
If you're testing if ingredientInput is empty, can you just return from within the click event?
$("#addIngrButton").on('click', function() {
var ingredientInput = $("#ingredients").val().trim();
if(ingredientInput === '') { return; }
// rest of code
Simply use :
$("#addIngrButton").on('click', function() {
var ingredientInput = $("#ingredients").val().trim();
if (ingredientInput.length == 0) {
return false;
}
// ..... your code
I am using the Angular directives for bootstrap.
I have a popover as in their example:
<button popover="Hello, World!" popover-title="Title" class="btn btn-default ng-scope">Dynamic Popover</button>
It closes when you click on the button again. I'd like to close it -- and any other open popovers -- when the user clicks anywhere.
I don't see a built-in way to do this.
angular.element(document.body).bind('click', function (e) {
var popups = document.querySelectorAll('.popover');
if(popups) {
for(var i=0; i<popups.length; i++) {
var popup = popups[i];
var popupElement = angular.element(popup);
if(popupElement[0].previousSibling!=e.target){
popupElement.scope().$parent.isOpen=false;
popupElement.remove();
}
}
}
});
This feature request is being tracked (https://github.com/angular-ui/bootstrap/issues/618). Similar to aet's answer, you can do what is recommended in the feature request as a work-around:
$('body').on('click', function (e) {
$('*[popover]').each(function () {
//Only do this for all popovers other than the current one that cause this event
if (!($(this).is(e.target) || $(this).has(e.target).length > 0)
&& $(this).siblings('.popover').length !== 0
&& $(this).siblings('.popover').has(e.target).length === 0)
{
//Remove the popover element from the DOM
$(this).siblings('.popover').remove();
//Set the state of the popover in the scope to reflect this
angular.element(this).scope().tt_isOpen = false;
}
});
});
(source: vchatterji's comment in feature request mentioned above)
The feature request also has a non-jQuery solution as well as this plnkr: http://plnkr.co/edit/fhsy4V
angular.element(document.body).bind('click', function (e) {
var popups = document.querySelectorAll('.popover');
if (popups) {
for (var i = 0; i < popups.length; i++) {
var popup = popups[i];
var popupElement = angular.element(popup);
console.log(2);
if (popupElement[0].previousSibling != e.target) {
popupElement.scope().$parent.isOpen = false;
popupElement.scope().$parent.$apply();
}
}
}
});
What you say it's a default settings of the popover, but you can control it with the triggers function, by putting blur in the second argument of the trigger like this popover-trigger="{mouseenter:blur}"
One idea is you can change the trigger to use mouse enter and exit, which would ensure that only one popover shows at once. The following is an example of that:
<button popover="I appeared on mouse enter!"
popover-trigger="mouseenter" class="btn btn-default"
popover-placement="bottom" >Hello World</button>
You can see this working in this plunker. You can find the entire list of tooltip triggers on the angular bootstrap site (tooltips and popovers have the same trigger options). Best of luck!
Had the same requirement, and this is how we did it:
First, we modified bootstrap, in the link function of the tooltip:
if (prefix === "popover") {
element.addClass('popover-link');
}
Then, we run a click handler on the body like so:
$('body').on('click', function(e) {
var clickedOutside = true;
// popover-link comes from our modified ui-bootstrap-tpls
$('.popover-link').each(function() {
if ($(this).is(e.target) || $(this).has(e.target).length) {
clickedOutside = false;
return false;
}
});
if ($('.popover').has(e.target).length) {
clickedOutside = false;
}
if (clickedOutside) {
$('.popover').prev().click();
}
});
I am using below code for same
angular.element(document.body).popover({
selector: '[rel=popover]',
trigger: "click"
}).on("show.bs.popover", function(e){
angular.element("[rel=popover]").not(e.target).popover("destroy");
angular.element(".popover").remove();
});
Thank you Lauren Campregher, this is worked.
Your code is the only one that also runs the state change on the scope.
Only configured so that if you click on the popover, the latter closes.
I've mixed your code, and now also it works if you click inside the popover.
Whether the system, whether done through popover-template,
To make it recognizable pop up done with popover-template, I used classes popover- body and popover-title, corresponding to the header and the body of the popover made with the template, and making sure it is pointing directly at them place in the code:
angular.element(document.body).bind('click', function (e) {
var popups = document.querySelectorAll('.popover');
if(popups) {
for(var i=0; i<popups.length; i++) {
var popup = popups[i];
var popupElement = angular.element(popup);
var content;
var arrow;
if(popupElement.next()) {
//The following is the content child in the popovers first sibling
// For the classic popover with Angularjs Ui Bootstrap
content = popupElement[0].querySelector('.popover-content');
// For the templating popover (popover-template attrib) with Angularjs Ui Bootstrap
bodytempl = popupElement[0].querySelector('.popover-body');
headertempl= popupElement[0].querySelector('.popover-title');
//The following is the arrow child in the popovers first sibling
// For both cases.
arrow = popupElement[0].querySelector('.arrow');
}
if(popupElement[0].previousSibling!=e.target && e.target != content && e.target != arrow && e.target != bodytempl && e.target != headertempl){
popupElement.scope().$parent.isOpen=false;
popupElement.remove();
}
}
}
});
Have ever a good day, thank you Lauren, thank you AngularJS, Thank You So Much Stack Family!
Updated:
I updated all adding extra control.
The elements within the popover were excluded from the control (for example, a picture inserted into the body of the popover.). Then clicking on the same closed.
I used to solve the command of API Node.contains, integrated in a function that returns true or false.
Now with any element placed inside, run the control, and keeps the popover open if you click inside :
// function for checkparent with Node.contains
function check(parentNode, childNode) { if('contains' in parentNode) { return parentNode.contains(childNode); } else { return parentNode.compareDocumentPosition(childNode) % 16; }}
angular.element(document.body).bind('click', function (e) {
var popups = document.querySelectorAll('.popover');
if(popups) {
for(var i=0; i<popups.length; i++) {
var popup = popups[i];
var popupElement = angular.element(popup);
var content;
var arrow;
if(popupElement.next()) {
//The following is the content child in the popovers first sibling
// For the classic popover with Angularjs Ui Bootstrap
content = popupElement[0].querySelector('.popover-content');
// For the templating popover (popover-template attrib) with Angularjs Ui Bootstrap
bodytempl = popupElement[0].querySelector('.popover-body');
headertempl= popupElement[0].querySelector('.popover-title');
//The following is the arrow child in the popovers first sibling
// For both cases.
arrow = popupElement[0].querySelector('.arrow');
}
var checkel= check(content,e.target);
if(popupElement[0].previousSibling!=e.target && e.target != content && e.target != arrow && e.target != bodytempl && e.target != headertempl&& checkel == false){
popupElement.scope().$parent.isOpen=false;
popupElement.remove();
}
}
}
});
I need to change the back button functionality of my phonegap project, which I've succeeded in doing without any problem. The only issue now, is that I need to further change the functionality based on if the user has a certain field selected.
Basically, if the user has clicked in a field with the id of "date-selector1", I need to completely disable the back button.
I was attempting to use document.activeElement, but it only returns the type of the element (input in this case), but I still want the functionality to work when they are in a general input, but not when they are in an input of a specific id.
EDIT
I tried all of the suggestions below, and have ended up with the following code, but still no success.
function pluginDeviceReady() {
document.addEventListener("backbutton", onBackKeyDown, false);
}
function onBackKeyDown() {
var sElement = document.activeElement;
var isBadElement = false;
var eList = ['procedure-date', 'immunization-date', 'lab-test-done', 'condition-onset', 'condition-resolution', 'medication-start-date', 'medication-stop-date', 'reaction-date'];
console.log("[[ACTIVE ELEMENT: --> " + document.activeElement + "]]");
for (var i = 0;i < eList.length - 1;i++) {
if (sElement == $(eList[i])[0]) {
isBadElement = true;
}
}
if (isBadElement) {
console.log('Back button not allowed here');
} else if ($.mobile.activePage.is('#main') || $.mobile.activePage.is('#family') || $.mobile.activePage.is('#login')) {
navigator.app.exitApp();
} else {
navigator.app.backHistory();
}
}
if you're listening for the back button you can add this if statement:
if (document.activeElement == $("#date-selector1")[0]) {
/*disable button here, return false etc...*/
}
or even better (Thanks to Jonathan Sampson)
if (document.activeElement.id === "date-selector1") {
/*disable button here, return false etc...*/
}
You can have a flag set when a user clicks on a field or you can have a click event (or any other type of event) when a user clicks on the field that should disable the back button.
From the documentation it looks like for the specific page that the backbuton is conditional on you can drop back-btn=true removing that back button.
http://jquerymobile.com/test/docs/toolbars/docs-headers.html
If you need complex conditional functionality you can just create your own button in the header or footer, style it using jquery-mobile widgets and implement your own click functionality.
I am not much of a JavaScript guru, so I would need help with a simple code.
I have a button that clears the value of an input field.
I would like it (the button) to be hidden if input field is empty and vice versa (visible if there is text inside the input field).
The solution can be pure JavaScript or jQuery, it doesn't matter. The simpler, the better.
$("input").keyup(function () {
if ($(this).val()) {
$("button").show();
}
else {
$("button").hide();
}
});
$("button").click(function () {
$("input").val('');
$(this).hide();
});
http://jsfiddle.net/SVxbW/
if(!$('input').val()){
$('#button').hide();
}
else {
$('#button').show();
}
In it's simplest form ;)
to do this without jQuery (essentially the same thing others already did, just pure js). It's pretty simple, but I've also added a few comments.
<body>
<input type="text" id="YourTextBox" value="" />
<input type="button" id="YourButton" value="Click Me" />
<script type="text/javascript">
var textBox = null;
var button = null;
var textBox_Change = function(e) {
// just calls the function that sets the visibility
button_SetVisibility();
};
var button_SetVisibility = function() {
// simply check if the visibility is set to 'visible' AND textbox hasn't been filled
// if it's already visibile and the text is blank, hide it
if((button.style.visibility === 'visible') && (textBox.value === '')) {
button.style.visibility = 'hidden';
} else {
// show it otherwise
button.style.visibility = 'visible';
}
};
var button_Click = function(e) {
// absolutely not required, just to add more to the sample
// this will set the textbox to empty and call the function that sets the visibility
textBox.value = '';
button_SetVisibility();
};
// wrap the calls inside anonymous function
(function() {
// define the references for the textbox and button here
textBox = document.getElementById("YourTextBox");
button = document.getElementById("YourButton");
// some browsers start it off with empty, so we force it to be visible, that's why I'll be using only chrome for now on...
if('' === button.style.visibility) { button.style.visibility = 'visible'; }
// assign the event handlers for the change and click event
textBox.onchange = textBox_Change;
button.onclick = button_Click;
// initialize calling the function to set the button visibility
button_SetVisibility();
})();
</script>
</body>
Note: I've written and tested this in IE9 and Chrome, make sure you test it in other browsers. Also, I've added this fiddle so you can see it working.
You can use $('selector').hide() to hide an element from view and $('selector').show() to display it again.
Even better, you can use $('selector').toggle() to have it show and hide without any custom logic.
First hide the button on page load:
jQuery(document).ready(function() {
jQuery("#myButton").hide();
});
Then attach an onChange handler, which will hide the button whenever the contents of the text-field are empty. Otherwise, it shows the button:
jQuery("#myText").change(function() {
if(this.value.replace(/\s/g, "") === "") {
jQuery("#myButton").hide();
} else {
jQuery("#myButton").show();
}
});
You will also need to hide the button after clearing the input:
jQuery("#myButton").click(function() {
jQuery("#myInput").val("");
jQuery(this).hide();
});