Jquery replaceWith(html) not replacing element; appending it to end instead - javascript

I have the following HTML. Its a form inside of a modal window:
<div class="modal fade" id="requestModal" tabindex="-1" role="dialog" aria-labelledby="requestModalLabel">
<div class="modal-dialog wide-modal" role="document">
<form novalidate>
<div class="modal-content">
....
</div>
</form>
</div>
</div>
Whenever the form is opened, I want to render a fresh version of the form, free of any old inputs or error messages. The following handler gets the data for hidden fields plus the form's HTML I can obtain the data for the form along with the raw HTML for the form via an Ajax request:
$(document).on('click', '#por-detail-tbl .dropdown-menu', e => {
// This route will get fresh form HTML also.
$.get(`/projects/${$(e.target).attr('project-id')}`, res => {
$('#requestModal').replaceWith(res.html)
...more code here to populate hidden fields...
})
})
I would expect the $('#requestModal') element to be replaced with whatever res.html is (in this case, a new version of the form). Instead, res.html is getting inserted as the last element in the document body. The old $('#requestModal') is still there.
Here is a snippet from res.html:
<div class="modal fade" id="requestModal" tabindex="-1" role="dialog" aria-labelledby="requestModalLabel">
<div class="modal-dialog wide-modal" role="document">
<form novalidate>
<div class="modal-content">
...
</div>
</form>
<div>
</div>
I'm able to use this technique successfully in other Ajax callbacks. Any ideas why this one is behaving strangely?

You actually want jQuery's .html() function here.
In your original code, the replaceWith() function replaces $('#requestModal'). But the element you replaced is the element that's been manipulated by Bootstrap to perform the modal behavior you expect.
So I think you really want to set the content of the div.modal-dialog element to just the form and its children. If you can pare down res.html to just the form and children, you can change $('#requestModal').replaceWith(res.html) to $('#requestModal').find('div.modal-dialog').html(res.html).

Related

Getting data from text file via data-src using jQuery

I am trying to retrieve text from a .txt file using jQuery (I am also using Bootstrap). I am very new to web design but I am familiar somewhat with coding. I have the following button in my HTML:
<button type="button" class="btn btn-primary-outline-btn text-btn" data-toggle="modal" data-src="test.txt" data-target="#textModal"><img class="video_icon" src="assets/icons/parchment_icon.png" alt="text"</button>
As you can see, the target of the button is a modal which loads up text like so:
<!-- Text Modal -->
<div class="modal fade" id="textModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p id="outputText">File not found.</p>
</div>
</div>
</div>
</div>
My JS file looks like this (changed following one of the answers):
$(".text-btn").on("click", textFunction);
function textFunction() {
var el = document.getElementById('test');
console.log(el.getAttribute('data-src'));
jQuery.get(el.getAttribute('data-src'), function(data) {
$( '#outputText' ).html(data.replace('n',''));
});
}
Whilst the filepath outputs to the console correctly, I am unsure how to use jQuery to utilise this so that it will input the file contents into the modal-body. Additionally, my issue is now how to make the variable assigned through getElementById correctly correspond to the button pressed. Moreover, I am not sure how to use getAttribute or attr in jQuery to obtain the data source in javascript.
This is an issue as I will have multiple buttons with multiple file sources so I would like the jQuery to retrieve from each button's respective data source. Is there a way in which I can do this...?
You have to set the full file url in data-src then use:
$('.text-btn').on('click', function() {
$.get($(this).data('src'), function(data) {
$('#outputText').html(data);
});
});
For the case of multiple buttons, you can use an onclick event on each, which will fire textFunction. Then, inside the text function, you can retrieve the correct button's data-src using jQuery's data() function:
//assuming all your relevant buttons have class `text-btn`
//call textFunction on button click
$(".text-btn").on("click", textFunction);
function textFunction() {
//inside event handler, `this` points to the button that triggered the event
jQuery.get($(this).data('src'), function(data) {
alert(data);
$( '#outputText' ).html(data.replace('n',''));
});
}

display a modal in a JavaScript function trigger in jVectorMap

I am working with jVectorMap and I need to show a modal that will fetch data from database and display the result in a modal.
I want to trigger a modal for the following JavaScript function:
onMarkerSelected: function (event, index, isSelected, selectedMarkers) {
$('#myModal').modal('show');
}
My Modal is:
<div class="modal fade" id="largeModal" tabindex="-1" role="dialog" aria-labelledby="myModal" aria-hidden="true">
// fetch data from db by id
</div>
Apparently this doesn't work.
Looking at the HTML of your modal, you are defining it with id "largeModal". So your JS call should be:
$('#largeModal').modal('show');

Change image source inner modal on the fly

I am trying to change the source image of an image HTML element <img src="/some/dynamic/path"></img>.
How I take the this.id is very complex and is outside the context of this question, but suffice to know that it is obtained by PHP and at the time of click, on a list item (not showed here), the identifier is already set and ready for use. The console.log ensures that.
The problem is that when I click on the element, the modal appears to me, but I do not see the image. By debugging on the browser I noticed that the src field is always empty.
I suppose the cause of the problem is to be found in the Javascript code I posted. In particular, the execution of the two instructions is somewhat asynchronous.
What do you think about it? Do you need further details?
The modal code:
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-body text-center">
<img id="modalImage" src="">
</div>
</div>
</div>
</div>
And the JS code:
$(".listShowCard").click(function() {
console.log("/images/cards/"+this.id+".png");
$("#modalImage").src="/images/cards/"+this.id+".png";
$("#myModal").modal('show');
});
use:
document.getElementById('modalImage').src=`/images/cards/${this.id}.png`;
When you're using elements with IDs, try to avoid jQuery, since the call is so much slower than pure JS call.
$("#modalImage").attr('src', "/images/cards/" + this.id + ".png")

Is it possible for me to make my controller return data for my modal window? MVC5 ASP.NET

Im busy making my ASP.NET web-app.
I will start with explaining the flow of my application.
User submits form
Form data gets posted to controller
Controller generates table with numbers in it using tagbuilder, returning it as mvcHtmlString.
Every number in this table is surrounded by an anchor tag (a).
When this number is clicked i want to open a modal window that shows data relevant to the number being clicked.
Clicking this number currently has an url.action as href so it jumps into my controller, passing the number to the controller.
Showing the modal is not a problem since i can just pass a data-toggle and a data-target into my anchor tag, but i want to show data that the controller returns in it's body.
What i am currently doing is in my view which contains the form i do
#{Html.RenderPartial("_Details");}
_Details contains the whole modal code:
<div class="modal fade" id="competenceModal" tabindex="-1" role="dialog" aria-labelledby="competenceModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<p>Competence details</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
My anchor tag being returned to the view containg the form:
UrlHelper url = new UrlHelper(HttpContext.Request.RequestContext);
var url2 = url.Action("LevelDetails", "Knowledge", new { level = level.Value });
var anchor = new TagBuilder("a");
anchor.Attributes.Add("href", url2);
anchor.Attributes.Add("data-target", "#competenceModal");
anchor.Attributes.Add("data-toggle", "modal");
This is correctly acessing my controller, but my big question is:
Is it possible to make the controller return data, such as a mvcHtmlString or any other content and put it in the body of my modal window? If so, what would be the best way to do so?
I would like to suggest you following things,
1. Use data-id field while building your modal link in controller. Like data-id="1".
2. In your partial view use this id to call an ajax method like "getData"
3. Return your data in json format from "getData".
4. Now bind that returned data to your form controls using jquery.
Hope this helps you !

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);
});

Categories

Resources