Bootstrap modal won't close on click - javascript

I am very new to web dev. Still not too familiar with JavaScript. I am making an error message using that will load using code one of our dev guys created for a different page. I created modals that show on a click event and then close on a click event. For this one I am having the modal show based on returned URL parameters. And I am using code I copied from another page one of our dev guys made (not with Bootstrap modals).
The code below makes the modal show, but the buttons used to close the modal don't work. Not sure why.
This is the tag that will append the URL when returned:
(**...?companyName=ACME47 & err1=0 & err2=0 & err3=1**)
When the error values are 1 is loads the page to show the error modal with the text for that error in it.
Here is the code I'm using for the form (not attaching the style sheet, so it looks different).
jQuery(document).ready(function() {
// jQuery code snippet to get the dynamic variables stored in the url as parameters and store them as JavaScript variables ready for use with your scripts
$.urlParam = function(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results == null) {
return null;
} else {
return results[1] || 0;
}
}
// Get url parameters
var err1 = new Number($.urlParam('err1'));
if (isNaN(err1)) {
err1 = new Number(0);
}
var err2 = new Number($.urlParam('err2'));
if (isNaN(err2)) {
err2 = new Number(0);
}
var err3 = new Number($.urlParam('err3'));
if (isNaN(err3)) {
err3 = new Number(0);
}
console.log('err1: ' + err1); // Writes a message to the browser console [f12]
console.log('err2: ' + err2); // Writes a message to the browser console [f12]
console.log('err3: ' + err3); // Writes a message to the browser console [f12]
console.log('CompanyName: ' + $.urlParam('companyName')); // Writes a message to the browser console [f12]
// Display error message function
// Read a page's GET URL variables and return them as an associative array.
if (err1 > 0) {
$("#error-box").show();
$("#error-1").show();
};
if (err2 > 0) {
$("#error-box").show();
$("#error-2").show();
};
if (err3 > 0) {
$("#error-box").show();
$("#error-3").show();
};
});
<div class="modal" id="error-box" style="display: none;" tabindex="-1" role="dialog" aria-labelledby="error-boxLabel">
<div class="modal-dialog" role="document" style="height:200px;">
<div class="modal-content" style="height: 100%;">
<div class="modal-header alert-danger">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
</button>
<h4 class="modal-title text-danger">Form Submission Error</h4>
</div>
<div class="modal-body alert-danger" style="height: 100%;">
<div class="textWrapper">
<ul>
<li id="error-1" style="display: none;">That email address is already in use. (01)</li>
<li id="error-2" style="display: none;">A company with that name already has an account in this system. (02)</li>
<li id="error-3" style="display: none;">An unknown error has occurred. If your E-Mail or Phone Number was correctly filled in, you will be contacted shortly. (03)</li>
</ul>
</div>
</div>
<div class="modal-footer modal-footer-text">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>

You shouldn't be using jQuery's show() method to show the modal. Doing so doesn't register it with Bootstrap, so there's nothing to close with elements possessing the data-dismiss attribute. Use Bootstrap's method:
$("#error-box").modal('show');
Note that you may also need to use Bootstrap's show.bs.modal callback to show your error containers. It's possible that they won't be available to jQuery until the modal is initiated.

This is what I think you want see fiddle https://jsfiddle.net/sxh0n7d1/53/
Note: I set all the errors to visible in the fiddle, so that there is something to see how it works.
add this to your javascript
$('.close, .btn-danger').click(function() {
$( "#error-box" ).hide();
});

Related

Prestashop 1.6.1.16 - My js file is loaded, but my functions aren't seen

I am new in Prestashop (1.6.1.16).
I work in default prestashop theme (default-bootstrap).
What I did:
I put content in /themes/default-bootstrap/product.tpl:
right after top comments (those about LICENSE and others):
<script type="text/javascript" src="modules/ask_bid/js/ask.js">
</script>
<button onclick="take_asks({$product->id})">See asks</button>
<input type="hidden" id="product-id" value="{$product->id}" />
<input type="hidden" id="customer-id" value="{$id_customer}" />
<!-- Modal -->
<div id="modal" class="modal fade">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-
dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default"
data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Where {$product->id} comes from
/controllers/front/ProductController.php<br>
and {$id_customer} comes from
/override/controllers/front/ProductController.php
I created /modules/ask_bid/js/ask.js where I put next content:
function isJSON(data) {
var ret = true;
try {
JSON.parse(data);
}catch(e) {
ret = false;
}
return ret;
}
function take_asks (id_product) {
$.ajax({
type: 'POST',
url: baseDir + 'modules/ask_bid/ajax.php',
data: 'method=take_asks&id_product='+id_product,
dataType: 'text',
success: function(json) {
if(isJSON(json)) {
var json = JSON.parse(json);
//alert("json: " + json[0].comment);
}
},
error: function() {
alert("error");
}
});
}
Also the modal doesn't act like one
My modal is displayed (not hidden) and that is not normal.
It is right after button instead being "in the air" (I hope you know what I mean).
And I have js error:
The /modules/ask_bid/js/ask.js is loaded (I see this also in INSPECT->f12/Network), but the take_asks() is not seen.
I get next console error (when I press 'Take asks' button):
Uncaught ReferenceError: take_asks is not defined
at HTMLButtonElement.onclick (index.php?
id_product=6&controller=product&id_lang=1:413)
What I tried
-I deleted class_index.php
-I deleted cache (with CTRL-f5)
-I tried to add js file from /override/controllers/front/ProductController.php
but doesn't work and i also don't get errors:
public function setMedia()
{
$this->addJS('modules/ask_bid/js/ask.js');
parent::setMedia();
}
...or...
function init () {
$this->context->controller->addJS('modules/ask_bid/js/ask.js');
parent::init()
}
What do you think I can do?
You should create a hookheader in your module:
public function hookHeader($params)
{
$this->context->controller->addJS(($this->_path).'js/ask.js');
}
You can add it only on product pages with:
public function hookHeader($params)
{
if (!isset($this->context->controller->php_self) || $this->context->controller->php_self != 'product')
return;
$this->context->controller->addJS(($this->_path).'js/ask.js');
}
and in your module install hook to header with
$this->registerHook('header'))
To add content to the product page without changing the themes tpls (as mentioned in comments) you can use the displayFooterProduct that "Add new blocks under the product description.".
public function hookDisplayFooterProduct($params)
{
return "code you want to insert";
}
Inside this hook you can access the following parameters:
$params = array('product' => Product, 'category' => Category)
Also, remember to hook it on install with $this->registerHook('displayFooterProduct')) and if the module is already installed, reset it or manually hook it.

Angular2 and cookies

I have some notice code like this:
<div class="alert alert-success" [ngClass]="{hidden: showBanner('some-value')}">
<button type="button" class="close" data-dismiss="alert" (click)="hideBanner('some-value')">×</button>
<strong>NOTICE:</strong> Some notice text...
</div>
When a user closes this notice I set a cookie and when the page loads, I check to see if a cookie has been previously set before displaying it.
showBanner(value)
{
return (Cookie.check(value)) ? true : false;
}
hideBanner(value)
{
Cookie.set(value,'true',new Date().setFullYear(2300,1,1));
var cookies = Cookie.getAll();
Object.keys(cookies);
}
When I check the cookie in the browser it shows it as being set as a "session" cookie and not as a date based cookie.
Any idea how to resolve this?

Pass Anonymous function that requires a parameter, to another function as an argument which will be assigned to an onclick

I have a function that I want to reuse throughout my program. Basically it's a bootstrap dialog box that has a confirm and a cancel button. I setup the helper function to accept two anonymous functions, one for the cancel and one for the confirm. I have everything working except I am not sure how to properly assign it to the onclick when building the html. I want to avoid using a global variable but this is the only way I was able to get this to work.
Custom function:
function confirmMessageBox(msg, cancelFunc, confirmFunc) {
var html = ' <div class="container"><div class="modal fade" id="ConfirmMsgModal" role="dialog"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h4 class="modal-title">Confirmation Needed</h4></div><div class="locationTableCanvas"><div class="modal-body"><p>' + msg + '</p></div></div><div class="modal-footer"><table><tr><td><button type="button" class="btn btn-default" data-dismiss="modal" onclick = "(' + cancelFunc + ')()">Cancel</button></td><td><button type="button" class="btn btn-default" data-dismiss="modal" onclick = "(' + confirmFunc + ')()">Confirm</button></td></tr></table></div></div></div></div></div>';
$("#confirmMsgContainer").html(html);
$('#ConfirmMsgModal').modal('show');
}
I have to do, onclick = "(' + cancelFunc + ')()"> because if I do, onclick = "' + cancelFunc() + '"> it shows up as undefined. The current way will basically just print the anonymous function out and assign it to the onclick (almost as if I just typed out the anonymous function right at the onclick)
here is where I call the function:
var transTypeHolder;
$("input[name='transType']").click(function () {
var tabLength = $('#SNToAddList tbody tr').length;
if (tabLength == 0) {
var selection = $(this).attr("id");
serialAllowableCheck(selection);
resetSerialNumberCanvasAndHide();
$("#Location").val("");
$("#SerialNumber").val("");
}
else {
transTypeHolder = $(this).val();
var confirm = function () {
var $radios = $('input:radio[name=transType]');
$radios.filter('[value='+transTypeHolder+']').prop('checked', true);
resetSerialNumberCanvasAndHide();
$('#Location').val('');
$('#SerialNumber').val('');
};
var cancel = function () {};
confirmMessageBox("This is a test", cancel, confirm);
return false;
}
});
Is there a way to some how pass a variable to the anonymous function without using the global variable I have as, "transTypeHolder" ?
Before I get the, "Why are you doing it this way??" response; Javascript isn't a strong language of mine, as I am using ASP.NET MVC4. I haven't had a chance to sit down and learn Javascript in detail and I sort of picked it up and search what I need. So if there is a better way of tackling this, I am open for constructive criticism.
Don't make event handler assignments in HTML at all. If you want people to be able to supply their own functions for canceling and confirming use on:
function confirmMessageBox(msg, cancelFunc, confirmFunc) {
var html = ' <div class="container"><div class="modal fade" id="ConfirmMsgModal" role="dialog"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h4 class="modal-title">Confirmation Needed</h4></div><div class="locationTableCanvas"><div class="modal-body"><p>' + msg + '</p></div></div><div class="modal-footer"><table><tr><td><button type="button" class="btn btn-default cancel" data-dismiss="modal">Cancel</button></td><td><button type="button" class="btn btn-default confirm" data-dismiss="modal">Confirm</button></td></tr></table></div></div></div></div></div>';
$("#confirmMsgContainer").html(html);
$("#confirmMsgContainer").off('click', '.confirm').on('click', '.confirm', confirmFunc);
$("#confirmMsgContainer").off('click', '.cancel').on('click', '.cancel', cancelFunc);
$('#ConfirmMsgModal').modal('show');
}
Note that I've edited the HTML you're using to remove the onclicks and added a class to each button. I'm also using off to be sure any previously added event handlers are removed.
As far as passing the variable to the confirm function without using a global, use a closure:
var transTypeHolder = $(this).val();
var confirm = (function (typeHolder) {
return function () {
var $radios = $('input:radio[name=transType]');
$radios.filter('[value='+typeHolder+']').prop('checked', true);
resetSerialNumberCanvasAndHide();
$('#Location').val('');
$('#SerialNumber').val('');
};
})(transTypeHolder);
That tells JavaScript to create a function, which returns a function that does what you want it to do. That "function creator" takes in the variable you want to keep around, allowing it to be used elsewhere.
Now, I haven't tested this, so you may have some debugging in your future, but hopefully it gives you a jumping-off point.
You should be able to do it by having the function being acessible from global context under a generated name (which can be multiple if you have more than one instance of the box), like so:
function confirmMessageBox(msg, cancelFunc, confirmFunc) {
window['generatedCancelFunctionName1'] = cancelFunc;
window['generatedConfirmFunctionName1'] = confirmFunc;
var html = ' <div class="container"><div class="modal fade" id="ConfirmMsgModal" role="dialog"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h4 class="modal-title">Confirmation Needed</h4></div><div class="locationTableCanvas"><div class="modal-body"><p>' + msg + '</p></div></div><div class="modal-footer"><table><tr><td><button type="button" class="btn btn-default" data-dismiss="modal" onclick = "generatedCancelFunctionName1()">Cancel</button></td><td><button type="button" class="btn btn-default" data-dismiss="modal" onclick = "generatedConfirmFunctionName1()">Confirm</button></td></tr></table></div></div></div></div></div>';
$("#confirmMsgContainer").html(html);
$('#ConfirmMsgModal').modal('show');
}
This way you are not obliged to expose the function code. You can also set an id attribute to the element and set a jquery click() function like in the second part (but you would need the html to be created before you set the click)

Set flash message after redirect in angularjs

I am just starting with Angular js. I have a doubt in that. I want to set flash messsage after redirect.
In my case, I have a form and am saving the data through http requst. In the success function I put window.location(). It is another page. I want to set a flash message in that page.
js
$scope.Save_Details = function (id)
{
$http.post(base_url+"sur/sur/save_data/"+id,{data:$scope.Surdata}).
success(function(response) {
// $scope.successTextAlert = "Saved";
// $scope.showSuccessAlert = true;
window.location = "#/surpage/nextpage?show_message= true";
});
}
new update
var messageFlag = $location.search().show_message;
if(messageFlag && messageFlag === 'true'){
alert(messageFlag);
$scope.successTextAlert = "Saved";
$scope.showSuccessAlertMsg = true;
}
view
<div class="alert alert-success" ng-show="showSuccessAlert">
<button type="button" class="close" data-ng-click="switchBool('showSuccessAlert')">×</button> <strong> {{successTextAlert}}</strong>
</div>
Anyone help me?
Put this code in HTML -
<!-- message text -->
<div class=" panel-{{alerts.class}}" ng-show="alerts.messages" >
<div ng-repeat="alert in alerts.messages track by $index" class="panel-body alert-{{alerts.class}}" >{{alert}}</div>
</div>
Put this code in angular model -
$rootScope.alert = function(type,msg){
$rootScope.message.push(msg);
$rootScope.alerts = {
class: type,
messages:$rootScope.message
}
}
For success message -
$rootScope.alert('success',"Success !!!");
For Error message -
$rootScope.alert('danger',"Error.");
You can use toastr JS specially for flash.
http://codeseven.github.io/toastr/demo.html
By using below js code, you can display a flash message.
For success message :
toastr"success";
For Error message :
toastr"success";
EDIT - Adding code
yourAppModule.controller('nextPageController', function($location){
var messageFlag = $location.search().show_message;
if(messageFlag && messageFlag === 'true'){
//show your message
}
});
When you navigate to "nextpage" pass a flag along -> #/surpage/nextpage?show_message= true
In the "nextpage" controller, read the query string value for
"show_message" ( inject $location to your controller and get value
using $location.search().show_message)
if that value == true, show your flash message

Twitter Bootstrap alert message closes without pressing close button

I have a problem with alert messages. I want to use the alert message as a warning to the user after a particular action has been performed. The issue I am facing is that the message shows and then closes on its own without user closing the message.
<div class="row-fluid">
<div class="alert span10 offset1" style="display: none" id="changeStatusMsg">
<a class="close" onclick="$('.alert').hide()" href="#">×</a>
<strong>Status has been changed.</strong>
</div>
I am using jquery to show the message -- $('#changeStatusMsg').show();
I used the solution mentioned here
But it does not help in my case.
function changeStatus(status, widgetExternalId){
$.ajax({
url : 'Controller',
data : { 'widget' : widgetExternalId,
'method' : (status == 'I' ? "activate" : "inactivate")
},
success : function(data) {
window.location = "myaccount.jsp";
$('#changeStatusMsg').show();
}
}
});
}
It is probably do to the fact you are not calling the action that is opening it. So the page is refreshing.
If you are doing it inline:
onclick="$('#changeStatusMsg').show();return false;"
If with a click event
$(".foobar").on("click",function (event) {
event.preventDefault();
$("#changeStatusMsg').show();
});

Categories