Django and jQuery.formset, how to manipulate delete button position - javascript

I'm trying to set my formset in django, using the famous jQuery plugin
jQuery.formset.js
All works perfectly, but I have some problem to set the right position of the delete button.
Now it is set in the last column of my table, like in the following figure:
But my aim is to replace the delete button in the same line of the the add button (+).
I have found in the code the following instructions, but I don't now how could set it for my aim:
var delButtonHTML = '<a class="' + options.deleteCssClass + '" href="javascript:void(0)">' + options.deleteText +'</a>';
if (options.deleteContainerClass) {
// If we have a specific container for the remove button,
// place it as the last child of that container:
row.find('[class*="' + options.deleteContainerClass + '"]').append(delButtonHTML);
} else if (row.is('TR')) {
// If the forms are laid out in table rows, insert
// the remove button into the last table cell:
row.children(':last').append(deleteButtonHTML);
} else if (row.is('UL') || row.is('OL')) {
// If they're laid out as an ordered/unordered list,
// insert an <li> after the last list item:
row.append('<li>' + deleteButtonHTML + '</li>');
} else {
// Otherwise, just insert the remove button as the
// last child element of the form's container:
row.append(delButtonHTML);
}
How could I get this instruction to achive my aim?

add container class with same class:
deleteContainerClass: 'hapus',
addContainerClass: 'hapus',

Related

How to take an image from html table row

I face a problem, I can take the values from HTML table row and I can easily set them to another text box, but how we can take an image from HTML table row and how to set that into a div,
Summarize: I want to take an image from HTML Table row and set that to a div.
// For View data
$(document).ready(function() {
$("#dtBasicExample tbody").on('click', 'tr', function() {
$("#txtSelect").text("1 row selected");
var rowData = $(this).children("td").map(function() {
return $(this).text();
}).get();
$("#txtSId").val(rowData[0]);
$("#txtSName").val(rowData[1]);
$("#txtSPosition").val(rowData[2]);
$("#imgS").html(`<img src="images/'.rowData[3].'">`);
$("#txtSFacebook").val(rowData[4]);
$("#txtSTwitter").val(rowData[5]);
$("#txtSGoogleplus").val(rowData[6]);
});
});
You should rather be doing :
$("#imgS").html('<img src="images/'+rowData[3]+'">');
To concatenate in JS you need to use + and not .
You also need to use the character ' at the start and end of your string rather than using `

Need JQuery or JavaScript to use .contains() with && logic

I am attempting to build a simple narrow by filter using given key word buttons on an otherwise static list of items.
The buttons are in an unordered list and when selected get the class ".selected-tag-button" added to them.
The items are divs with class ".item" and get class ".included-item" when they are active. Inside the div is another UL with list items that contain key words that match the text node on the buttons.
Right now it is working, except, instead of using "buttonName" which contains only the key word for the clicked button, I would like to use "buttonArray" which contains an array of all the selected key words.
I assume I will need some kind of function, but I am not sure where to start. If more than one are selected I want the result to be limited to only items that contain ALL of the selected key words. All of the solutions I have been able to figure out will return the divs that contain ANY of the key words in the array.
$(document).ready(function() {
$("li.tag-button").on("click", function() {
// Toggle button
$(this).toggleClass("selected-tag-button");
// Remove included-item class from all items
$(".item" ).removeClass("included-item");
// Pass the button text into variable
var buttonName = $(this).text().slice(2);
// Create array with button text for all active buttons
var buttonArray = $(".selected-tag-button").map(function() {
return $(this).text().slice(2);
}).get();
console.log(buttonArray);
// Add included-item class to divs containing the button text
$('li:contains("' + buttonName + '")').parents().parents().addClass("included-item");
// If all buttons are inactive, add included-item class to all items
if ($(".selected-tag-button").length == 0 ) {
$(".item" ).addClass("included-item");
}
});
});
Consider this fiddle:
http://jsfiddle.net/6qavvth8/
for(i=0; i<buttonArray.length;i++){
contains += ':contains("' + buttonArray[i] + '")';
}
$('ul' + contains).parents().addClass("included-item");
Loop through your button array to build your jquery selector and keep adding :contains()
Slight modification of #bingo's solution. Works perfectly, thanks.
$(document).ready(function() {
$("li.tag-button").on("click", function() {
// Toggle button
$(this).toggleClass("selected-tag-button");
// Remove included-item class from all items
$(".item" ).removeClass("included-item");
// Create array with button text for all active buttons
var buttonArray = $(".selected-tag-button").map(function() {
return $(this).text().slice(2);
}).get();
// Add included-item class to divs containing the button text
var contains = "";
for(i = 0; i < buttonArray.length; i++){
contains += ':contains("' + buttonArray[i] + '")';
}
$('ul' + contains).parents().addClass("included-item");
// If all buttons are inactive, add included-item class to all items
if ($(".selected-tag-button").length == 0 ) {
$(".item" ).addClass("included-item");
}
});
});

JQuery get calling <script> tag when dynamically loaded

How can I locate the tag which calls a JQuery script, when
the tag is dynamically loaded, so won't be the last
tag on the page?
I'm using the MagicSuggest autosuggest library. I want to give certain suggested items a different background color depending on their contents, which I'm currently doing by adding JQuery inside a tag, which I'm adding on to the String which is returned to be rendered inside the selection div. Then, to get the div the item is suggested in, I need to essentially get the parent() of the tag, and change it's css() properties. How can I get this current script tag however?
I'm currently assigned each new tag an id generated from incrementing a JS variable - which works, but isn't very 'nice'! Is there anyway I can directly target the tag with JQuery?
If it perhaps makes it clearer, here is my current selectionRenderer function.
selectionRenderer: function(a){
var toRet = a.english;
var blueBgScript = "<script id=ft" + freeTextFieldID + ">$('#ft" + freeTextFieldID + "').parent().css('background', 'blue');</script>"
if(a.id==a.english){
toRet += blueBgScript;
freeTextFieldID++;
}
return toRet;
},
Why don't you add some code at afterrender event instead? Add some tag to flag the options that need a different background, then detect the parents and add a class (or edit the bg property) or whatever you like:
var newMS = $('#idStr').magicSuggest({
data: 'states.php',
displayField: 'english',
valueField: 'id',
selectionRenderer: function(a){
var toRet = a.english;
if(a.id==a.english) toRet = "<span class='freetext'>" + toRet + "</span>";
return toRet;
},
});
$(newMS).on('selectionchange', function(event,combo,selection){
var selDivs = $(event.target._valueContainer[0].parentNode).children('div'); //Get all the divs in the selction
$.each(selDivs,function(index,value){ //For each selected item
var span = $(value).children('.freetext'); //It if contains a span of class freetext
if(span.length == 1) $(value).css('background','blue'); //Turn the background blue
});

javascript button click function not working

I have a website where user can select an item, the detail is then displayed, including the quantity. I have also included a button inside the div so that when clicked, it should decrease the quantity by 1.
$("#btnBuy1").click(function()
{
if (!sessionStorage['quantity1'])
{
sessionStorage['quantity1']=1;
}
else
{
sessionStorage['quantity1']++;
}
$("#dropbox").html('<div id = "1"><img class = "thumb" id = "t1" src="../images/birthday_metoyou.jpg" />' + teddy[1].desc + ", Price £"
+ teddy[1].price + ", Quantity: " + sessionStorage.getItem('quantity1') + "<button id = 'btnRemove1'>Remove</button></div><br/>");
updateBasket();
sessionStorage["total1"] = parseInt(sessionStorage.getItem('quantity1')) * teddy[1].price;
updateSubtotal();
if (Modernizr.sessionstorage)
{ // check if the browser supports sessionStorage
myids.push(teddy[1].partnum); // add the current username to the myids array
sessionStorage["ids"]=JSON.stringify(myids); // convert it to a string and put into sessionStorage
}
else
{
// use cookies instead of sessionStorage
}
});
$("#btnRemove1").click(function()
{
alert(remove);
});
I put in an alert message to see if the button is working properly, but when I click the btnRemove1 button, nothing happens.
Since the button is dynamically added, can you try:
$(document).on('click', '#btnRemove1', function() {
{
alert("remove"); //I dont know what remove was is the example, added quotes around it.
});
That is because the button is added later (dynamicly). You will have to use a delegate.
You don't have to use body for this. Any non dynamicly inserted element that is a parent of #btnRemove1 will do.
$('body').on('click','#btnRemove1',function(){
alert(remove);
});
The reason is that you bind the event before the element #btnRemove1 is present on your page. Therefore there is nothing to bind the event to. The body element however - will be present on the page and delegate your event to #btnRemove1.
You can either tie the event to the document (what jQuery live used to do before it was deprecated)
now it is:
$(document).on("click", "#btnRemove1", function(){})
or you can rebind the event after #btnRemove1 is added to the Dom.
Most likely, your Remove button isn't in the DOM before you try to attach the click event to it. It is hard to tell from your code snippets, but if the Buy button action hasn't completed successfully, then Remove won't exist.
At the point that you attach the click event to Remove, try console logging $("#btnRemove1").length to see if it exists, or use break points.
An improvement to your code would be to cache in a variable $("#dropbox") and then look for your buttons within it, as in:
var $dropBoxNode = $("#dropbox");
$dropBoxNode.find("#btnRemove1");
And you should use .on() instead of the deprecated .click().
Try putting the remove button click handler addition after you create the remove button
///Code snippit
$("#dropbox").html('<div id = "1"><img class = "thumb" id = "t1" src="../images/birthday_metoyou.jpg" />' + teddy[1].desc + ", Price £"
+ teddy[1].price + ", Quantity: " + sessionStorage.getItem('quantity1') + "<button id = 'btnRemove1'>Remove</button></div><br/>");
$("#btnRemove1").click(function()
{
alert(remove);
});
updateBasket();
///Code snippit
$('a.edit').on('click','a.edit',function(){
if (confirm("Are you sure you want to Edit this Photo?"))
{
....
....
}
});
Not Working When Data is Loading with AJAX on a DIV Area
Just Like
EDIT

cloning form fields are populated with value from previous fields

This function clones a set of text input fields inside a div, when the user clicks the add button:
function addRows(label, maxRows, minRows) {
$('.add-' + label).live('click', function() {
if ($("." + label + "-group").length < maxRows) {
$('#' + label + '-template')
.clone()
.removeAttr('id')
.insertAfter($(this).closest('.' + label + '-group'))
.find('.minus')
.show();
}
});
}
When the user fills in a field, then clicks the add button, it displays a new row of fields, but they are populated with the values the user entered in the previous row.
What is the best way to resolve this problem? I am thinking I could empty all input text fields for that instance of rows.
I just don't know how I'll clear the appropriate rows.
The field names are: first_name[], last_name[], phone[]
So when it clones those three fields to a new row, they will have the same name as the fields above.
When the user submits, I'll loop through each value in first_name[], last_name[], phone[]
try this, call val() after other methods like appendTo or insertAfter
$('#' + label + '-template').clone().val("")...
http://jsfiddle.net/pnQhh/

Categories