How do I call a function on button click inside a modal? - javascript

I have a modal that displays a product and a counter to select the # of items. There are up and down buttons to increase or decrease the quantity. Here is the modal:
<div id="productDetailModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="productDetailModal" aria-hidden="true">
<div id="productDetailDialog" class="modal-dialog">
<div class="modal-content">
<div id="counter" class="col-xs-6">
<label for="qty"><abbr title="Quantity">Qty</abbr></label>
<input id="qty" value="0" />
<button id="down" onclick="modify_qty(-1)">-1</button>
<button id="up" onclick="modify_qty(1)">+1</button>
</div>
And here is the script function:
function modify_qty(val) {
var qty = document.getElementById('qty').value;
var new_qty = parseInt(qty, 10) + val;
if (new_qty < 0) {
new_qty = 0;
}
console.log("Inside script.js function. new_qty= " + new_qty);
document.getElementById('qty').value = new_qty;
return new_qty;
}
The counter works fine if I take the #counter div and place it in the body of the html page. It's only in the modal, where it doesn't work. I output to console in the function, and it seems the function isn't getting called inside the modal. What am I doing wrong?

You're not showing how/where you include the javascript, but if you make sure it's in scope (check your console logs for errors), it should work.
Here's a working example:
jsfiddle.net
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#productDetailModal">Open Modal</button>
<div id="productDetailModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="productDetailModal" aria-hidden="true">
<script>
function modify_qty(val) {
var qty = document.getElementById('qty').value;
var new_qty = parseInt(qty, 10) + val;
if (new_qty < 0) {
new_qty = 0;
}
console.log("Inside script.js function. new_qty= " + new_qty);
document.getElementById('qty').value = new_qty;
return new_qty;
}
</script>
<div id="productDetailDialog" class="modal-dialog">
<div class="modal-content">
<div id="counter" class="col-xs-6">
<label for="qty"><abbr title="Quantity">Qty</abbr></label>
<input id="qty" value="0" />
<button id="down" onclick="modify_qty(-1)">-1</button>
<button id="up" onclick="modify_qty(1)">+1</button>
</div>
</div>
</div>
</div>

Related

Bootstrap modal not showing with JavaScript " $("#attributeUpdateModal").modal('show');"

I am new to JavaScript and I'm working on a project with openlayers and geoserver and I need to add features to a layer. I succeeded to draw a feature but for saving it I need to enter its attributes which I implemented in a bootstrap modal but when I finish drawing the modal doesn't show I get just a transparent page and it stays like that.
Here it is my html code :
<!-- Attribute Update Modal -->
<div class="modal " id="attributeUpdateModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title" id="exampleModalLabel">Attributes</h3>
<button class="btn-close btn-light" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="attribute-body">
<div id="attributeContainer"></div>
</div>
<div class="modal-footer">
<div class="col-md-12 text-center">
<button id="btnSave" type="button" class="btn btn-success">
Save
</button>
<button id="btnCancel" type="button" class="btn btn-warning">
Cancel
</button>
</div>
</div>
</div>
</div>
</div>
Here it is my JavaScript code :
drawInteraction.on("drawend", function (e) {
var feature = e.feature;
feature.set("geometry", feature.getGeometry());
modifiedFeatureList.push(feature);
var featureProperties = editGeoJSON
.getSource()
.getFeatures()[0]
.getProperties();
document.getElementById("attributeContainer").innerHTML = "";
for (var key in featureProperties) {
if (featureProperties.hasOwnProperty(key)) {
if (key != "geometry") {
if (key != "id") {
var div = document.createElement("div");
div.className = "mb-3";
var lbl = document.createElement("label");
lbl.className = "form-label";
lbl.innerHTML = key;
var inputBox = document.createElement("input");
inputBox.className = "form-control";
inputBox.id = key;
inputBox.value = "";
div.appendChild(lbl);
div.appendChild(inputBox);
document.getElementById("attributeContainer").appendChild(div);
}
}
}
}
$("#attributeUpdateModal").modal('show');
});
Does anyone have an idea about this issue?

Represent newline character from Javascript to HTML

I am currently using Javascript to build a string from an array and pass that to an HTML modal, however I am unclear as to how to display the string with line breaks in between, as now the HTML is representing the built string in Javascript as a single line. Any help would be appreciated.
Javascript:
function ShowCrashString(str) {
var temp_split = str.split(';');
temp_str = '';
for (var i=0; i < temp_split.length; i++) {
temp_str += temp_split[i] + '\n;'
}
document.getElementById("crash-modal").innerHTML = temp_str;
}
HTML Modal Code:
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Crash Analysis</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="crash-modal">
<!-- data gets populated here -->
</div>
<div class="modal-footer" id="to-copy">
<button type="button" class="btn btn-secondary" data-dismiss="modal"
id="closeModal">Close</button>
<button class="btn btn-primary" onClick="CopyToClipboard('crash-modal')">Copy</button>
</div>
</div>
</div>
</div>
You need to use <br/> instead \n for HTML
temp_str += temp_split[i] + '<br/>'
Two ways you could do this:
Put your text in a <pre> tag. This will show your newlines
Use str.replace(/\n/g,"<br>") to replace your newlines with <br /> tags
I think that will solve your problem
function ShowCrashString(str) {
var temp_split = str.split(';');
temp_str = '';
for (var i=0; i < temp_split.length; i++) {
temp_str += temp_split[i] + '<br/>'
}
document.getElementById("crash-modal").innerHTML = temp_str;
}

JQuery Close Modal After Inactivity

I am creating a touch screen feedback kiosk that prompts users for their email address after they select a feedback option (good / bad).
Leaving their email address is optional, so the modal window should close after x seconds of inactivity.
How can I detect if a user is currently 'active' in the modal and close it if not (using JQuery)?
The countdown timer should be reset, and modal stay open if:
The user begins to type in the input.
The modal should be closed if;
The input has been inactive for x seconds (user leaves).
I have half of it complete, just need some help with the rest of it. Currently the timer only changes on each click of the input.
My current code is below;
Here's a link to a my fiddle.
HTML
<button type="button" class="btn btn-primary" id="feedbackFormBad">click</button>
<div aria-hidden="true" class="modal fade" id="memberNumberModal" role="dialog" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header modal-header-primary">
<h1>Hello</h1>
</div>
<div align="center" class="modal-body">
<p>Some text here.</p>
<p span id="countdown"></p>
<!-- show count down timer here -->
<form id="memberNumberForm" class="form-inline">
<div class="form-group mb-2">
<input type="text" name="Email" class="form-control" id="memberNumber" placeholder="enter email" required>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Send</button>
<button type="button" class="btn btn-secondary" id="closeModal" data-dismiss="modal">No Thanks</button>
</div>
</form>
</div>
</div>
</div>
</div>
JQuery
$(document).ready(function() {
$("#feedbackFormBad").on("touchstart, click", function(e) {
$('#memberNumberModal').modal('toggle');
var counter = 5;
var interval = setInterval(function() {
counter--;
$("#memberNumber").focus(function() {
$("#countdown").html('Window will close in ' + counter + ' seconds.');
});
if (counter == 0) {
$('#memberNumberModal').modal('hide');
clearInterval(interval);
}
}, 1000);
});
});
Any help is appreciated.
Try with the below javascript code
$(document).ready(function() {
$("#feedbackFormBad").on("touchstart, click", function(e) {
$('#memberNumberModal').modal('toggle');
var counter = 5;
var interval = setInterval(function() {
counter--;
$("#countdown").html('Window will close in ' + counter + ' seconds.');
if (counter == 0) {
$('#memberNumberModal').modal('hide');
clearInterval(interval);
}
}, 1000);
$('body').bind('mousedown keydown', function(event) {
counter = 5;
});
});
});
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<body>
<button type="button" class="btn btn-primary" id="feedbackFormBad">click</button>
<hr>
<p>The timer should be reset if:</p>
<ul>
<li>The user begins to type in the input.</li>
</ul>
<p>The modal should be closed if:</p>
<ul>
<li>The input has been inactive for x seconds (user leaves).</li>
</ul>
<div aria-hidden="true" class="modal fade" id="memberNumberModal" role="dialog" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header modal-header-primary">
<h1>Hello</h1>
</div>
<div align="center" class="modal-body">
<p>Some text here.</p>
<p span id="countdown"></p>
<!-- show count down timer here -->
<form id="memberNumberForm" class="form-inline">
<div class="form-group mb-2">
<input type="text" name="Email" class="form-control" id="memberNumber" placeholder="enter email" required>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Send</button>
<button type="button" class="btn btn-secondary" id="closeModal" data-dismiss="modal">No Thanks</button>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
You could use a combination of setInterval and all of the events to achieve this. I've commented the code below.
Update
Originally, I'd posted an answer using the keyup function - missing the touchscreen part of the requirements. However, the below listens for any change to the text input. Let me know if this works.
The events were taken from this answer here
Best way to track onchange as-you-type in input type="text"?
// Keep track of if user is active
var active = true;
// keep track of how long since the user has typed
var timeElapsed = 0;
// check every second
setInterval(function(){
timeElapsed += 1;
// example
$("#timer").html(timeElapsed + " seconds inactive");
// a minute has passed since the user has typed
if(timeElapsed == 60){
// close modal
$('#memberNumberModal').modal('hide');
}
}, 1000);
// if the user types, reset the timer
$("#test").on('change keydown paste input propertychange click keyup blur', function(){
// user is active, has typed
timeElapsed = 0;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="test" type="text">
<span id="timer"></span>

Modal only displays first image

I have got an issue where my modal only displays the first image. What I am trying to do is that i want to display a dynamic gallery. Every "post" can have 0-* images and based on how many images there are in the database for this post thats how many will appear. I came across this issue and have found others having similar issues but not exactly the same.
This code is basically a partial view where the post is generated. The Modal is displayd correct amount of times but only displays the first picture.
Thanks so much in advance
<ul class="imageRow">
#foreach (var item in Model)
{
<div class="col-lg-3 col-md-4 col-xs-6">
<a class="thumbnail" href="#" data-image-id="" data-toggle="modal" data-target="#image-gallery">
<img class=" img-responsive" id=" imageresource" src="data:image/jpeg;base64,#item">
</a>
</div>
<div class="modal fade" id="image-gallery" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="image-gallery-title"></h4>
</div>
<div class="modal-body">
<img class=" img-responsive" id=" imageresource" src="data:image/jpeg;base64,#item">
</div>
<div class="modal-footer">
<div class="col-md-2">
<button type="button" class="btn btn-primary" id="show-previous-image">Previous</button>
</div>
<div class="col-md-2">
<button type="button" id="show-next-image" class="btn btn-default">Next</button>
</div>
</div>
</div>
</div>
</div>
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js" type="text/javascript"></script>
<script>
$(document.body).on('hidden.bs.modal', function () {
$('#image-gallery').removeData('bs.modal');
});
$(document).ready(function () {
loadGallery(true, 'a.thumbnail');
//This function disables buttons when needed
function disableButtons(counter_max, counter_current) {
$('#show-previous-image, #show-next-image').show();
if (counter_max == counter_current) {
$('#show-next-image').hide();
} else if (counter_current == 1) {
$('#show-previous-image').hide();
}
}
function loadGallery(setIDs, setClickAttr) {
var current_image,
selector,
counter = 0;
$('#show-next-image, #show-previous-image').click(function () {
if ($(this).attr('id') == 'show-previous-image') {
current_image--;
} else {
current_image++;
}
selector = $('[data-image-id="' + current_image + '"]');
updateGallery(selector);
});
function updateGallery(selector) {
var $sel = selector;
current_image = $sel.data('image-id');
$('#image-gallery-caption').text($sel.data('caption'));
$('#image-gallery-title').text($sel.data('title'));
$('#image-gallery-image').attr('src', $sel.data('image'));
disableButtons(counter, $sel.data('image-id'));
}
if (setIDs == true) {
$('[data-image-id]').each(function () {
counter++;
$(this).attr('data-image-id', counter);
});
}
$(setClickAttr).on('click', function () {
updateGallery($(this));
});
}
});
</script>
}
You are using the same ID (id="image-gallery") for all of your modals. HTML element IDs are supposed to be unique! You need to generate different IDs for each of your modals.

how to get varying modal content

Hi I am trying to get the varying modal content but I am not sure where I am going wrong as I am new to JavaScript
My Code:
<a data-toggle="modal" data-target="#exampleModal" data-whatever="sampleText" >testData</a>
<div class="modal fade bs-example-modal-sm" tabindex="-1" id="exampleModal">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<h4 class="modal-title" id="exampleModalLabel">New message</h4>
<form>
<div class="form-group">
<label for="recipient-name" class="control-label">Recipient:</label>
<input type="text" class="form-control" id="recipient-name">
</div>
</form>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$('#exampleModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var recipient = button.data('whatever')
var modal = $(this)
modal.find('.modal-title').text('New message to ' + recipient)
modal.find('.modal-body input').val(recipient)
})
</script>
My aim is to display the "sampleText" in the input text box. But I dont get it. I am only getting empty box.
Also is there a way to display a list of strings in the input box.??
Sorry if my question is very basic.
S
There is no element with class of .modal-body in your markup, the selector should be .modal-content input.
modal.find('.modal-content input').val(recipient);
If by a list of strings you mean *-separated values, you can define an array and join the elements using Array.prototype.join method:
var list = ['an', 'array'];
var string = list.join('glue');
// ...
modal.find('.modal-content input').val(string);

Categories

Resources