How to change an href attribute through Javascript on a modal window - javascript

I've been searching and trying different ways to change an href attribute through Javascript. Few things have worked better than others.
The problem with this approach is that the variable on the href is not working. I guess there is a better way to include a variable within an html tag.
I'm really stuck on this so would appreciate any help.
Here is the code of the modal window:
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="modal-close">×</span>
<h1>¿Quieres seguir creando?</h1>
<a class="btn-ok" href=enlace target="_blank">OK</a>
</div>
</div>
And this the button that the user clicks on before the modal window is shown:
<script type="text/javascript">
var enlace;
</script>
<button onclick="enlace='https://cloqq.com/actividad/tu-aventura-interactiva';return false" id="" class="go-btn pink-bg">Empieza a crear
</button>

https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute
You can use setAttribute to reassign the href, the way you're using javascript in html doesnt work like that.
const itemYouWantToUpdateHref = document.querySelector('.btn-ok')
function changeHref(link) {
itemYouWantToUpdateHref.setAttribute('href', link);
}
<a class="btn-ok" href="www.google.com" target="_blank">My link will change</a>
<button onclick="changeHref('www.youtube.com')">click to change href from google to youtube</button>

You can use your code itself with only some changes and without any script tag. look at code below:
<button onclick="window.enlace='https://cloqq.com/actividad/tu-aventura-interactiva'" class="go-btn pink-bg">Empieza a crear</button>
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="modal-close">×</span>
<h1>¿Quieres seguir creando?</h1>
<a class="btn-ok" href="javascript:window.open(window.enlace||'defaultAddress', '_blank');">OK</a>
<!--
!! If you like to show an alert when the button is not clicked yet, try line below instead above line:
<a class="btn-ok" href="javascript:window.enlace?window.open(window.enlace, '_blank'):alert('Please click the Button first!');">OK</a>
-->
</div>
</div>
If you run above snippet and look at console, you can see all things is fine (but because Security problems this will not work with these URLs in current page and you should copy it in your project or an empty html file for seeing the result.)

Related

How to adjust this jQuery code to target div?

I have a reusable modal code that I use to easily load multiple modals. The problem I ran into was I had the div I use to display my errors set using an id. when I tried displaying errors in the second modal, obviously it didn't work because you can't have more than one element with the same id.
I would like to adjust my jQuery code in that erases any errors when the modal window opens.
Here is my code for the modals.
function loadModal($modalNum, $modalTitle, $modalFile) {
echo '<!-- The Modal -->
<div id="'.$modalNum.'" class="modal">
<!-- Modal content -->
<div class="modalContent">
<div class="modalHeader">
<span class="close">×</span>
<h2>'.$modalTitle.'</h2>
</div>
<div class="modalBody">
<!-- Error section -->
<div class="errors"></div>
<!-- include form to show -->';
include($modalFile);
echo ' </div>
</div>
</div>';
}
The piece of above code that I'm targeting.
<!-- Error section -->
<div class="errors"></div>
Here is my script that loads the window.
$('.openModal').on('click', function(){
$('#'+$(this).data('modal')).css('display','block');
$("#form")[0].reset();
while ($('.errors').firstChild) {
$('.errors').removeChild($('.errors').firstChild);
}
})
Here is the portion of code that I cannot figure out.
while ($('.errors').firstChild) {
$('.errors').removeChild($('.errors').firstChild);
}
Prior to changing it to try and read a class it looked like this. This was also when my html for the modal had the div as an id <div id='errors'></div>.
while (errors.firstChild) {
errors.removeChild(errors.firstChild);
}
How can I change this section of code to target my error div using the class
?
You can either scope your search or find the element inside the modal, both will return the same element. Also, the empty method is more convenient. And you can use the same approach for your other elements too, like the form you are targeting:
$('.openModal').on('click', function(){
targetModal = $('#'+$(this).data('modal'));
$("#form")[0].reset();
// Both are equivalent
errors = $(".errors", targetModal);
errors = targetModal.find(".errors");
errors.empty();
targetModal.css('display','block');
});

stop/pause video when modal closes/hides

I know this has been asked and answered, but I'm not having any luck with any of the options that I've found. I'm trying to have the video stop playback or pause the video when the modal closes. One problem I'm having is the ability to target the close button. I've put console.logs in the functions I've tried and they weren't registering in the console at all. Thanks for any insights able to be offered.
<div id="myModal<%= index + 1 %>" data-id='<%= list.video_id %>'class="modal fade videoModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content bmd-modalContent" >
<div class="modal-body modal-header">
<div class="close-button">
<button id='single' type="button" class="close fancybox-close" data-dismiss="modal" aria-label='Close' ><span aria-hidden="true">×</span></button>
</div>
<div class='embed-responsive embed-responsive-16by9'>
<iframe id='player' class='embed-responsive-item' src="https://youtube.com/embed/<%= list.video_id %>?rel=0&enablejsapi=1" allowFullScreen='true' frameborder="0"></iframe>
</div>
</div>
</div>
</div>
</div>
EDIT:
Sorry, I'had tried so much jQuery that I didn't have any in my app.js folder at the time. Here is what I'm working with now.
$('[id^=myModal]').on('hidden.bs.modal', function(event) {
console.log(player);
event.target.stopVideo();
});
Update the question with more details
Its really hard to tell what is the problem because you only posted html. You having problem with locating close button and your console.log doesnt trigger. Obviously your javascripe file has some errors above your console.log line.
To detect if modal is closed you can use this EVENT
$('#myModal').on('hidden.bs.modal', function (e) {
// do something...
})
I would not change id of modals when generating them, instead I would put data-attr on this element to have one .on('hidden.bs.modal') and to have control over every modal
UPDATE:
from youtube-api docs https://developers.google.com/youtube/iframe_api_reference#Loading_a_Video_Player
It has been said that if you embed in your html iframe with the youtube video then in the moment u make something like this in js:
function onYouTubeIframeAPIReady(){
var iframe = document.getElementById("my-video");
video = new YT.Player(iframe);
}
you dont have to define attributes of Player that you create, it will take it from the iframe.
fiddle: http://jsfiddle.net/ux86c7t3/2/
Well, you can simply remove the src of the iframe and then put back again like; so the iframe stops running.
<iframe id="videosContainers" class="yvideo" src="https://www.youtube.com/embed/kjsdaf ?>" w></iframe>
<span onclick="stopVideo(this.getAttribute('vdoId'))" vdoId ="yvideo" id="CloseModalButton" data-dismiss="modal"></span>
now the Jquery part
function stopVideo(id){
var src = $j('iframe.'+id).attr('src');
$j('iframe.'+id).attr('src','');
$j('iframe.'+id).attr('src',src);
}

Bootstrap $('#myModal').modal('show') is not working

I'm not sure why but all the modal functions are not working with me.
I checked the version and the load they are fine.
I keep getting this error message:
Uncaught TypeError: $(...).modal is not a function
for the hide I already found an alternative.
instead of:
$('#myModal').modal('hide');
I used this :
$('#myModal .close').click();
And it works perfectly.
The problem now is with the show
$('#myModal').modal("show");
I also tried both
$('#myModal').modal("toggle");
And:
$('#myModal').modal();
but unfortunately none of them is working.
Here html code -when the button is clicked I will do some verification and handle a json data from the web service if it succeed then I want show my modal- everything is working except the show.
<button type="button" id="creatNewAcount" class="btn btn-default" data-toggle="modal">Sign up</button>
if there's any alternative I would like to know it.
Most common reason for such problems are
1.If you have defined the jquery library more than once.
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="modal fade" id="myModal" aria-hidden="true">
...
...
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
The bootstrap library gets applied to the first jquery library but when you reload the jquery library, the original bootstrap load is lost(Modal function is in bootstrap).
2.Please wrap your JavaScript code inside
$(document).ready(function(){});
3.Please check if the id of the modal is same
as the one you have defined for the component(Also check for duplication's of same id ).
<div class="modal fade" id="myModal" aria-hidden="true">
...
...
</div>
Note: Remove fade class from the div and enjoy it should be worked
This can happen for a few reasons:
You forgot to include Jquery library in the document
You included the Jquery library more than once in the document
You forgot to include bootstrap.js library in the document
The versions of your Javascript and Bootstrap does not match. Refer bootstrap documentation to make sure the versions are matching
The modal <div> is missing the modal class
The id of the modal <div> is incorrect. (eg: you wrongly prepended # in the id of the <div>)
# sign is missing in the Jquery selector
I got same issue while working with Modal Popup Bootstrap , I used Id and trigger click event for showing and hidding modal popup instead of $("#Id").modal('show') and $("#id").modal('hide'),
`
<button type="button" id="btnPurchaseClose" class="close" data dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span></button>
<a class="btn btn-default" id="btnOpenPurchasePopup" data-toggle="modal" data target="#newPurchasePopup">Select</a>
$('#btnPurchaseClose').trigger('click');// for close popup
$('#btnOpenPurchase').trigger('click');`// for open popup
My root cause was that I forgot to add the # before the id name. Lame but true.
From
$('scheduleModal').modal('show');
To
$('#scheduleModal').modal('show');
For your reference, the code sequence that works for me is
<script>
function scheduleRequest() {
$('#scheduleModal').modal('show');
}
</script>
<script src="<c:url value="/resources/bootstrap/js/bootstrap.min.js"/>">
</script>
<script
src="<c:url value="/resources/plugins/fastclick/fastclick.min.js"/>">
</script>
<script
src="<c:url value="/resources/plugins/slimScroll/jquery.slimscroll.min.js"/>">
</script>
<script
src="<c:url value="/resources/plugins/datatables/jquery.dataTables.min.js"/>">
</script>
<script
src="<c:url value="/resources/plugins/datatables/dataTables.bootstrap.min.js"/>">
</script>
<script src="<c:url value="/resources/dist/js/demo.js"/>">
</script>
Use .modal({show:true}) and .modal({show:false}) instead of ('show') and ('hide') ... it seems to be bootstrap / jquery version combination dependent. Hope it helps.
the solution of 'bootstrap modal is not opening' is, put your Jquery CDN first in the head tag (after starting head tag).
I wasted two days in finding this problem.
Please,
try and check if the triggering button has attribute type="button".
Working example:
<button type="button" id="trigger" style="visibility:visible;" onclick="modal_btn_click()">Trigger Modal Click</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-sm">
<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>This is a small modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script >
function modal_btn_click() {
$('#myModal').modal({ show: true });
}
</script>
Try This without paramater
$('#myModal').modal();
it should be worked
are you sure that the id of the modal is "myModal"? if not then the call will not trigger it.
also - just from reading your post - you are triggering a function / validation with this button
<button type="button" id="creatNewAcount" class="btn btn-default" data-toggle="modal">Sign up</button>
and then if all is well - you want to trigger the modal. - if this is hte case - then you should remove the toggle from this button click. I presume you have an event handler tied to this click? you need the .modal("show") as a part of that function. not toggled from this button. also - is this id correct "creatNewAcount" as opposed to this spelling "createNewAccount"
<button type="button" id="creatNewAcount" class="btn btn-default" >Sign up</button>
use the object to call...
<a href="#" onclick='$("#myModal").modal("show");'>Try This</a>
or if you using ajax to show that modal after get result, this is work for me...
$.ajax({ url: "YourUrl",
type: "POST", data: "x=1&y=2&z=3",
cache: false, success: function(result){
// Your Function here
$("#myModal").modal("show");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script><script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.min.js"></script>
the first googleapis script is not working now a days use this second scripe given by jquery
jQuery lib has to be loaded first. In my case, i was loading bootstrap lib first, also tried tag with target and firing a click trigger. But the main issue was - jquery has to be loaded first.
Please also make sure that the modal div is nested inside your <body> element.
After trying everything on the web for my issue, I needed to add in a small delay to the script before trying to load the box.
Even though I had put the line to load the box on the last possible line in the entire script. I just put a 500ms delay on it using
setTimeout(() => { $('#modalID').modal('show'); }, 500);
Hope that helps someone in the future. 100% agree it's prob because I don't understand the flow of my scripts and load order. But this is the way I got around it
In my case, bootstrap.css and bootstrap.js versions are mismatched.
It is working if I remove the fade class. But the background is disappeared.
I added the same version of bootstrap files. Now it is working perfectly.
Thank you #Mohammed Shareef C.
Another use case that may be the cuplrit
My problem was that I had a jquery selector that was using a variable that was not assigned immediately.
My modal had a dynamic ID
<div class="modal fade" id="{{scope.modalId}}"... >
This is in angularJS, so the valud of scope.modalID wasn't being bound until $scope.onInit
vm.$onInit = function () {
$( `#${vm.modalId}` ).on('shown.bs.modal', function(){
console.log('WORKS')
});
zzz
Make sure your script tag is closed with another script tag like below
before
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"/>
After
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Setting a Bootstrap 3 modal title dynamically

I have the same modal dialog for three different buttons.
However, depending upon which button is clicked, I need to dynamically set the title of the modal dialog.
I thought this would be simple setting the title in the appropriate javascript function using jQuery. However, when debugging, I can see the title is set accordingly in the code, but after the modal is displayed, the modal title is blank.
How can I properly display the modal title accordingly?
Here is the pertinent part of the HTML:
<div class="modal fade" id="btnJournalVoucherEditGrid" tabindex="-1" role="dialog" aria-labelledby="btnJournalVoucherEditGrid-label" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="btnJournalVoucherEditGrid-label"></h4>
Here is the JS
function onEditJournalVoucher(gdId, rwID)
{
$('#btnJournalVoucherEditGrid-label').val("Edit Journal Voucher")
Well, you're trying to use .val() on an H4 tag. Should it not be:
$('#btnJournalVoucherEditGrid-label').text("Edit Journal Voucher");
or
$('#btnJournalVoucherEditGrid-label').html("Edit Journal Voucher");
.val() is the right mindset, but what it does in JQuery is why it won't work in this situation. Take an element that has a value="something" attribute, for example:
<input id="example" type="text" name="something" value="something"/>
Targeting this id using $("#example") and calling .val() can access or change the value="something" attribute. Now take a look at a <label> element:
<label id="example"> This is some text </label>
Notice the lack of a value="something" attribute? In this case, since "This is some text" is simply plain-text, using:
$("#example").text("Updated Text");
is the correct way to go about this. Hope that helps clear things up!
.val() is used for form elements (like inputs, checkboxes, etc.)
For divs/other elements (e.g. h4 in your situation) use either .text() or .html() depending on the situation you want to do.
In this case since this is just text change your line to:
$('#btnJournalVoucherEditGrid-label').text("Edit Journal Voucher");
It should be
function onEditJournalVoucher(gdId, rwID)
{
$('#btnJournalVoucherEditGrid-label').html("Edit Journal Voucher")
Try text() function instead of val():
$('#btnJournalVoucherEditGrid-label').text("Edit Journal Voucher")
I would set the title in the button:
<button id="edit-journal-voucher" data-title="Edit Journal Voucher" data-toggle="modal" data-target="#btnJournalVoucherEditGrid">Edit this Journal</button>
Then in the JS do something like:
$("#edit-journal-voucher").on("click", funtion(e){
e.preventDefault();
var title = $(this).data('title');
$("h4#btnJournalVoucherEditGrid-label").html(title);
});

can't get popeasy jquery modal lightbox plugin to work

So, after looking at many jquery modal plugins, I like the PopEasy ( http://thomasgrauer.com/popeasy/ ), but I copy and paste the provided code into a page on my server and no-workey.
Do the same with jsFiddle, same problem. The overlay fires, but the modal doesn't pop up. I'm sure that I'm doing one simple thing wrong.
http://jsfiddle.net/birchy/Kkw2L/5/
<a class="modalLink" href="#">Click Me
<div class="overlay"></div>
<div class="modal">
Close Me
content here
</div>
It appears to be a missing anchor close tag in the author's code.

Categories

Resources