I'm trying to figure out how to apply jQuery methods, functions etc for elements that have been created with ajax.
In my page there is a dropdown list #cat_id and depending on the selection made, a set of UL elements are created. I then need to call the following function for each element created:
$('#allowSpacesTagsX').tagit({ itemName: 'itemX', fieldName: 'tagsX', availableTags: sampleTagsX, allowSpaces: true });
where allowSpacesTagsX (X=1,2,3,....) is the id of the created UL elements. This method binds the UL to an auto-complete tagging widget similar to the tagging element used in StackOverflow.
Normally the code above would be included in the document.ready for the static elements but I need to add it for each element created with ajax.
This is a small sample of code to understand my question better:
<script src="../js/tag-it.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$('#cat_id').live('change', function(e){
$.post('../includes/ajax.php', {
cat_id : $(this).find("option:selected").attr('value')}, function(data) {
$("#tagholder").html(data);
});
});
});
</script>
Edit:
example added to demonstrate an example of the code that should be produced:
$(function(){ // Creates the arrays of tags to be assigned to each tag field
var sampleTags1 = ['USB', 'DVB', 'GSM', 'OEM'];
var sampleTags2 = ['Alfa Romeo', 'Audi', 'Chevrolet', 'Mazda', 'Mercedes'];
var sampleTags3 = ['20cm', '21cm', '8in'];
$('#allowSpacesTags1').tagit({ itemName: 'item1', fieldName: 'tags1', availableTags: sampleTags1, allowSpaces: true });
$('#allowSpacesTags2').tagit({ itemName: 'item2', fieldName: 'tags2', availableTags: sampleTags2, allowSpaces: true });
$('#allowSpacesTags3').tagit({ itemName: 'item3', fieldName: 'tags3', availableTags: sampleTags3, allowSpaces: true });
});
<script src="../js/tag-it.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$('#cat_id').live('change', function(e){
$.post('../includes/ajax.php', {
cat_id : $(this).find("option:selected").attr('value')},
function(data) {
$("#tagholder").html(data);//places your ajax content
//grab that element again and then apply any jquery function to it
//example add a class to an arbitary h1 tag inside #tagholder
$("#tagholder h1").css('class','heading');//like so
});
});
});
</script>
Related
I have a dropdown on a form. I have it set as unique entry for the list. That works fine, when a user selects an option that was already selected in a previous list entry they are notified when the save or submit the form. However I would rather remove the choice from the dropdown list if that selection was already made and exists in the list, that way they can't select something already selected.
Thanks for your help
We can use REST API to get all the exists dropdown items and then remove the downdown options in the new/edit form page. The following code for your reference.
<script src="//code.jquery.com/jquery-3.3.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
removeDuplicateDropDowm("FilterDropDown");
});
function removeDuplicateDropDowm(fieldName){
var listId = _spPageContextInfo.pageListId.replace("{","").replace("}","");
var fieldHTML="";
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists(guid'"+listId+"')/items?$select="+fieldName;
$.ajax({
url: url,
method: "GET",
async:false,
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
var items = data.d.results;
$("select[title='"+fieldName+"'] option").each(function(){
for(var i=0;i<items.length;i++){
if(items[i][fieldName]==$(this).val()){
$(this).remove();
}
}
});
},
error: function (error) {
console.log(JSON.stringify(error));
}
});
return fieldHTML;
}
</script>
I am just beginning to learn AJAX and am trying to build a cascading dropdown that pulls information from a database. My AJAX.Updater code works, but not only for one of the dropdowns. How do I make multiple AJAX.Updater calls?
<script type="text/javascript" src="jQuery/jquery-latest.js"></script>
<script type="text/javascript" src="jQuery/prototypejs.js"></script>
<script language="javascript">
jQuery(document).ready(function()
{
jQuery('#regiondropdown').change(function() {
dropdowns(jQuery(this).val(),"foo");
});
jQuery('#foodropdown').change(function() {
dropdowns(jQuery(this).val(),"bar");
});
}
);
function dropdowns(str,type)
{
if (type=="foo") {
new Ajax.Updater('foo', 'foo_dropdown.php', { method: 'get', parameters: {foo: str} });
} else if (type=="bar") {
new Ajax.Updater('bar', 'bar_dropdown.php', { method: 'get', parameters: {bar: str} });
}
}
</script>
I can't see what it is so I suggest you fire up your debugger.
1) Check the value of jQuery(this).val() for both cases. "this" might not be what you believe in Javascript.
2) Check what happens if you switch the if.. and else... in dropdowns. Maybe there is a (, { or ; out of place.
HTH
i am working on an asp.net mvc3 application.
I am trying to load a google map inside a partial view but it is not working:
My partial view _Map.cshtml
<style type="text/css">
#map_canvas
{
position:absolute;
top:40px;
left:12px;
width:576px;
height: 450px;
}
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<div class="sTitle">Name</div>
<div id="map_canvas"></div>
<script type="text/javascript">
var map;
$(document).ready(function () {
var map;
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
google.maps.event.addDomListener(window, 'load', initialize);
});
</script>
The map is loaded Via an AJAX Call:
$.ajax({
type: 'GET',
url: '#Url.Action("GetMapById", "Map")',
data: { 'id': sId },
success: function (html) {
$("#content").html(html);
},
complete: function () {
},
error: function () {
alert("There was an error opening the Map. Please try again or contact an administrator");
}
});
The partial is loaded in a div named Content
And in the controller I just return the Partial View
return PartialView("_Map");
The View is loading but the map is not visible.
I used Firebug to track the problem and I got this error:
“google is not defined”
Any idea about the problem?
Thanks a lot
I solved this by putting this
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
in the Layout page nad not in the subview
You have to load google map in this way:
<script type="text/javascript">
var map;
google.load("maps", "3", { other_params:"sensor=false" });
$(document).ready(function () {
And you reinitialize "var map" two times.
I didn't want to load the maps in a Layout page... Doing that would mean that if the script was taking long to load, it would slow the whole page and besides, if it is not needed there, then why make the browser download it?
To get around that, I found that you can load the maps API in your partial view like this:
$.getScript('http://maps.googleapis.com/maps/api/js',function (){
google.maps.event.addDomListener(window, 'load', initialize);
});
I have the following code working nicely:
$field2.on("change", "#selector", function(){
$field2.load("./index.php?show-options=true", { value: $(this).val() }, function() {
$("#options").buttonset();
});
});
It loads the #options div and applies button to anchor tags within it.
Is there a way to declare
$("#options").buttonset();
BEFORE the #options div is loaded?
I looked through jQuery docs with no success, and also found this answer:
Apply jQuery UI widgets to ajax loaded elements
which I think might be on track, but haven't understood it fully nor managed to implement.
Help appreciated, thanks.
Doing the following:
$field2.on("change", "#selector", function(){
$field2.load("./index.php?show-options=true", { value: $(this).val() }, function() {
$field2.find("#options").buttonset();
});
});
Will make all option elements within $field2 into a button set (once the content has been updated).
Or alternatively you could make the button set on dom ready:
$(function() { $("#options").buttonset(); });
Update
jQuery selectors work on elements in the DOM (unless given a context), if the element is not in the DOM then unfortunately jQuery will not be able to affect it directly. If the load then call to buttonset is causing a FOUC (flash of unstyled content), you could try the following:
$field2.on("change", "#selector", function() {
$field2.empty();
$.get("./index.php?show-options=true", { value: $(this).val() }, function(data) {
var newContent = $(data);
$("#options", newContent).buttonset();
$field2.empty().append(newContent);
});
});
I have a JQuery function/script that I'm using for posts on a blog that upon hover of the post image shows the post title, excerpt, and link.
Additionally, I have an AJAX Fade Out/Fade In pagination script running and when I go to the next set of posts in the pagination, the first JQuery script doesn't run any longer. I know I need to be using the .live function somehow for jQuery, however I can't seem to figure it out. Here are the two scripts.
<script type="text/javascript">
$(function() {
$(".capslide_img").capslide({
caption_color : '#516077',
caption_bgcolor : '#dbe2f0',
overlay_bgcolor : '#dbe2f0',
border : '4px solid #dbe2f0',
showcaption : false
});
});
</script>
<script type="text/javascript" charset="utf-8">
jQuery(document).ready(function(){
jQuery('#postPagination a').live('click', function(e){
e.preventDefault();
var link = jQuery(this).attr('href');
jQuery('#page-wrap').fadeOut(500).load(link + ' #contentInner', function(){ jQuery('#page-wrap').fadeIn(500); });
});
});
</script>
Thanks for your help.
you could put the capslide command into a function and call it after each ajax load:
function addCappslide() {
$(".capslide_img").capslide({
caption_color : '#516077',
caption_bgcolor : '#dbe2f0',
overlay_bgcolor : '#dbe2f0',
border : '4px solid #dbe2f0',
showcaption : false
});
}
$(function() {
addCappslide(); // call it once the page has loaded
$('#postPagination a').live('click', function(e){
e.preventDefault();
var link = $(this).attr('href');
$('#page-wrap').fadeOut(500).load(link + ' #contentInner', function(){
jQuery('#page-wrap').fadeIn(500, addCappslide() ); // call it after each ajax load again after it faded in
});
});
});