jquery remove entire div tag - javascript

I have an image upload script that creates a hidden div tag when an image is uploaded and should remove the image tag if somebody deletes the photo.
When somebody uploads it, it creates a tag like this:
<input type="hidden" id="hidden_image_1903180_620338339358jpg"
name="ad_image[]" value="image_1903180_620338339358.jpg">
The photo can be deleted with:
<a onclick="delete_media('image_1903180_620338339358jpg', 1, 1903180);">
Delete Photo</a>
The problem is what when somebody clicks delete, it doesn't remove the entire tag, it only removes the value like this:
<input type="hidden" id="hidden_image_1903180_620338339358jpg"
name="ad_image[]" value="">
How can I make it so the entire <div> ... </div> is removed?
The delete_media function is like this:
function delete_media_async(box_id, media_type, id) {
var file_name = document.getElementById('hidden_' + box_id).value;
var xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert("Browser does not support HTTP Request");
return;
}
var url = relative_path + 'file.php';
var action = url + '?do=remove&file_name=' + file_name + '&id=' + id;
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
var response = xmlHttp.responseText;
document.getElementById('box_' + box_id).innerHTML = '';
document.getElementById('box_' + box_id).className = 'thumbnail_display_empty';
document.getElementById('hidden_' + box_id).value = '';
var nb_uploads = document.getElementById('nb_uploads_' + media_type).value;
nb_uploads--;
document.getElementById('nb_uploads_' + media_type).value = nb_uploads;
document.getElementById('btn_upload_' + media_type).disabled = false;
document.getElementById('item_file_upload_' + media_type).disabled = false;
document.getElementById('item_file_url_' + media_type).disabled = false;
document.getElementById('item_file_embed_' + media_type).disabled = false;
}
};
xmlHttp.open("GET", action, true);
xmlHttp.send(null);
}

$('#hidden_' + box_id).remove() will remove the input field. If the input field is enclosed in a div and you want to remove that:
$('#hidden_' + box_id).parent().remove()
Edit: this is using jQuery

Assuming that your hidden input has a div as its parent, you could remove that div using this:
var hidden_input = document.getElementById('hidden_' + box_id);
var parent_div = hidden_input.parentNode;
var parent_of__parent_div = parent_div.parentNode;
// now remove the parent div:
parent_of__parent_div.removeChild( parent_div );
Insert that in your function and it should remove your entire div.
I used only pure Javascript, since your code was the same way.

Related

Pass 2 Functions Through One OnChange Event - With HREF on both Functions

I have asked something similar in the past but was able to resolve it by separating the functions by events. I need to be able to pass 2 href events in one Onchange Event because it is a dropdown, OR I need to be able to tie the second function into another Event.
This works only when an alert() is inserted. Once I take the alert() out it does not work. I've tried to supress the alert while still keeping it in the code and it works fine. I do not want the alert but I want the results.
HTML Here:
<select id="PartList" class="form-control form-control-lg ml-0" onChange="SelectMain();">
JavaScript Here
function sList() {
var pl = document.getElementById("PartList");
var value = pl.options[pl.selectedIndex].value;
var text = pl.options[pl.selectedIndex].text;
str = 'URL1 HERE='+ "'" + text + "'" ;
//alert(value);
//alert(text);
window.location.href = str;
}
function SelectValue() {
var pv = document.getElementById("PartList");
var value = pv.options[pv.selectedIndex].value;
str = 'URL2 HERE' + value ;
alert(value);
window.location.href = str;
}
function SelectMain() {
sList();
SelectValue();
}
function alert(message) {
console.info(message);
}
This is resolved, for those that come to this question. The problem wasn't with the JavaScript it was because the device I was sending the commands to couldn't handle the commands that fast. I have incorporated the resolved code with troubleshooting techniques.
function sList() {
var pl = document.getElementById("PartList");
var value = pl.options[pl.selectedIndex].value;
var text = pl.options[pl.selectedIndex].text;
str = 'URL1='+ "'" + text + "'" ;
//str1 = 'http://google.com';
//alert(value);
//alert(text);
window.location.href = str;
//window.open(str1);
}
function SelectValue() {
setTimeout(function(){
var pv = document.getElementById("PartList");
var value = pv.options[pv.selectedIndex].value;
str = 'URL2=' + value ;
//str1 = 'http://aol.com';
//alert(value);
window.location.href = str;
//window.open(str1);
},1000);
}

How to fire cancel on open dialog file input on jquery

Hi all i have code for multiple upload image, but i want only one image per upload. so I create the input file every time I clicked the upload button with the dynamic id. however I have problems checking whether the user chooses the file to upload or press the cancel button. because if the user pressed the cancel button I want to delete the input file I have created. for full sourcenya as below:
$(document).ready(function () {
$("#btnimg").click(function () {
//check input file id number
var counter = $("input[id^='upload']").length;
//add input file every btnimg clicked
var html = "<input type='file' id='upload_" + counter + "' style='display:none;'/>";
$("#result").append(html);
//trigger to dialog open file
var upload = $('#upload_' + counter);
upload.trigger('click');
upload.on('change', function () {
console.log('change fire...');
var inputFiles = this.files;
var inputFile = inputFiles[0];
var reader = new FileReader();
reader.onload = function (evt) {
var imghtml = "<img id='img_upload_" + counter + "' src='" + evt.target.result + "' width='50px;' height='50px;'/>";
$('#previewimage').append(imghtml);
};
reader.onerror = function (event) {
alert("something: " + event.target.error.code);
};
reader.readAsDataURL(inputFile);
});
//if file not selected or user press button cancel on open dialog
//upload.remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="result"></div>
<button id="btnimg">upload image</button>
<div id="previewimage">
</div>
</body>
thank you in advance,
You can check the .length of <input type="file"> element .files property to determine if a file is selected by user
That all sounds like an xy-problem to me.
I have not (yet) got a response from you about the why you want to do it, so I will base my answer on two probable situations:
If you want to keep track of the selected Files, in order to be able to do anything with them later (e.g send them through AJAX), then use a single <input>.
At every change event, you will store the new File in an Array, from where you will also be able to do something with later on:
(function() {
// this Array will hold our files, should be accessible to the final function 'doSomething'
var savedFiles = [];
var counter = 0;
var upload = $('#upload');
upload.on('change', onuploadchange);
$("#btnimg").click(function routeClick() {
upload.trigger('click');
});
$('#endbtn').click(function doSomething() {
console.log(savedFiles);
});
function onuploadchange() {
var inputFiles = this.files;
var inputFile = inputFiles[0];
if (!inputFile) { return; } // no File ? return
savedFiles.push(inputFile); // save this File
// don't use a FileReader here, useless and counter-productive
var url = URL.createObjectURL(inputFile);
var imghtml = "<img id='img_upload_" + counter + "' src='" + url + "' width='50px;' height='50px;'/>";
$('#previewimage').append(imghtml);
$('#endbtn').removeAttr('disabled');
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result">
<!-- A single input to save them all-->
<input type='file' id='upload' style='display:none;' />
</div>
<button id="btnimg">upload image</button>
<div id="previewimage">
</div>
<button id="endbtn" disabled>do something with saved files</button>
If, for an obscure reason, you absolutely need to keep all the filled <input> elements in your document, then create a new one only if the last one is itself filled.
$(document).ready(function() {
$("#btnimg").click(function() {
// grab previous ones
var inputs = $("input[id^='upload']");
// get the last one we created
var last = inputs.last();
var counter = inputs.length;
console.log(counter);
var upload;
// if there is no input at all, or if the last one is already filled with a File
if (!last.length || last[0].files.length) {
console.log('create new input');
upload = makeNewInput();
} else {
// use the last one
upload = last;
}
//trigger to dialog open file
upload.trigger('click');
function makeNewInput(counter)  {
var html = "<input type='file' id='upload_" + counter + "' style='display:none;'/>";
var el = $(html);
el.on('change', onuploadchange);
$('#result').append(el);
return el;
}
function onuploadchange() {
var inputFiles = this.files;
var inputFile = inputFiles[0];
var url = URL.createObjectURL(inputFile);
var imghtml = "<img id='img_upload_" + counter + "' src='" + url + "' width='50px;' height='50px;'/>";
$('#previewimage').append(imghtml);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
<button id="btnimg">upload image</button>
<div id="previewimage">
</div>

Kendo Grid - Window template button with update functionality

Right now I am using a window to view details that are not shown in the grid. I have made my own custom editor in the window as well which hides the details and replaces them with inputs.
Unfortunately I cannot get the Update button to have the same functionality as an update button in the kendo toolbar.
I am using transport and parameter map for my create which works perfectly. I just need to be able to hit the update, which I haven't been able to.
Here is a snippet of code for the template:
<li><b>Change Control Objective</b></li>
<li><textarea type="text" class="k-textbox k-input" data-bind="value:ChangeControlObjective">#= ChangeControlObjective #</textarea></li>
<li><b>Change Control Specifics</b></li>
<li><textarea type="text" class="k-textbox k-input" data-bind="value:ChangeControlSpecifics">#= ChangeControlSpecifics #</textarea></li>
<span class="k-update k-icon k-i-tick"></span>Save
I can't show my JS code but it is based off this dojo: http://dojo.telerik.com/abUHI
UPDATE:
I am able to hit the update in the parametermap off of my save button click but it's sending the old data to the update instead of the new. Here is the button click code:
$("#saveChanges").click(function () {
dataItem.dirty = true;
$("#ccrGrid").data('kendoGrid').saveChanges();
});
Each input has a data-bind attribute and the parametermap looks like this:
case "update":
var changeControlRequestId = options.ChangeControlRequestID;
var changeControlObjective = options.ChangeControlObjective;
var changeControlSpecifics = options.ChangeControlSpecifics;
var productAssociation;
if (options.AccountChangeInfo.ProductAssocation == undefined) {
productAssociation = "";
} else { productAssociation = options.ProductAssocation; }
var amortization;
if (options.AccountChangeInfo.Amortization == undefined) {
amortization = "";
} else { amortization = options.Amortization; }
var productType;
if (options.ProductChangeInfo.ProductType == undefined) {
productType = "";
} else { productType = options.ProductType; }
var productName;
if (options.ProductChangeInfo.ProductName == undefined) {
productName = "";
} else { productName = options.ProductName; }
var productDescription;
if (options.ProductChangeInfo.ProductDescription == undefined) {
productDescription = "";
} else { productDescription = options.ProductDescription; }
var productContract;
if (options.ProductChangeInfo.ProductContractualFeatures == undefined) {
productContract = "";
} else { productContract = options.ProductContractualFeatures; }
var productBehavior;
if (options.ProductChangeInfo.ProductBehavioralAssumptions == undefined) {
productBehavior = "";
} else { productBehavior = options.ProductBehavioralAssumptions; }
var evaluationBehavior;
if (options.ProductChangeInfo.ProductEvaluationBehavior == undefined) {
evaluationBehavior = "";
} else { evaluationBehavior = options.ProductEvaluationBehavior; }
var productStratification;
if (options.ProductChangeInfo.ProductStratificationRoutines == undefined) {
productStratification = "";
} else { productStratification = options.ProductStratificationRoutines; }
if (content.isreadonly == "True") {
alert("you have readonly access");
}
else {
var urlString = "env=" + content.env + "&allyid=" + content.userId + "&changeRequestID" + changeRequestID + "&changeControlObjective=" + changeControlObjective + "&changeControlSpecifics=" + changeControlSpecifics +
"&productAssociation" + productAssociation + "&amortization" + amortization +
"&productType" + productType + "&productName" + productName + "&productDescription" + productDescription +
"&productContract" + productContract + "&productBehavior" + productBehavior + "&evaluationBehavior" + evaluationBehavior +
"&productStratification" + productStratification;
return urlString;
I've been going through this a couple months ago. Per my extensive research there are 2 key sources for doing custom popup editing in Kendo in entire Internet ;) :
Custom editor template
I aslo created a simplified version of this for you here: http://jsbin.com/qudotag/
to cut the elements which can be expanded once you grap the key concepts. Note that this does not work fully as changes are not persisted. It is expected behaviour, as you would need to define the CRUD operations for the grid (what happens when save, cancel etc. is done).
How to deal with CRUD is available in the second source:
Crud with external form
Some heavy studying of these 2 along with going into some more depths of MVVM (which might be intimidating at first, but then really useful for much smoother work with Kendo) will get you going.
Edit: actually you could do with just first approach, which is easier and retain the state by refreshing the grid after cancel.

Jquery Click send doesn't work

Hi everyone i have one question about jquery click send function. I have created this demo from jsfiddle. So if you visit the demo then you can see there is one smiley and textarea. When you write some text and press enter then the message sending successfully. But i want to add also when you click the smiley then it need to send (w1) from the image sticker="(w1)" like click to send. But click send function doesn't work. What is the problem on there and what is the solution ? Anyone can help me in this regard ?
JS
$('.sendcomment').bind('keydown', function (e) {
if (e.keyCode == 13) {
var ID = $(this).attr("data-msgid");
var comment = $(this).val();
if ($.trim(comment).length == 0) {
$("#commentload" + ID).text("Plese write your comment!");
} else {
$("#commentload" + ID).text(comment);
$("#commentid" + ID).val('').css("height", "35px").focus();
}
}
});
/**/
$(document).ready(function() {
$('body').on("click",'.emo', function() {
var ID = $(this).attr("data-msgid");
var comment = $(this).val();
if ($.trim(comment).length == 0) {
$("#commentload" + ID).text("nothing!");
} else {
$("#commentload" + ID).text(comment);
$("#commentid" + ID).val('').css("height", "35px").focus();
}
});
});
$('body').on('click', '.sm-sticker', function(event) {
event.preventDefault();
var theComment = $(this).parents('.container').find('.sendcomment');
var id = $(this).attr('id');
var sticker = $(this).attr('sticker');
var msg = jQuery.trim(theComment.val());
if(msg == ''){
var sp = '';
} else {
var sp = ' ';
}
theComment.val(jQuery.trim(msg + sp + sticker + sp));
});
HTML
<div class="container one">
<div class="comments-area" id="commentload47">comments will be come here</div>
<div class="user-post" id="postbody47">
<textarea class="sendcomment" name="comment" id="commentid47" data-msgid="47"></textarea>
<div class="stiemo">
<img src="http://d.lanrentuku.com/down/png/1009/networking/emoticon_inlove.png" class="sm-sticker emo" sticker="(w1)"> click smiley to send (w1)</div>
</div>
</div>
</div>
try this :
just append below JS after the line theComment.val(jQuery.trim(msg + sp + sticker + sp));
var e = $.Event("keydown");
e.keyCode = 13; // # Some key code value
$('.sendcomment').trigger(e);
Demo
you should use this:
$('body').on("click",'.emo', function() {
var ID = $('.sendcomment').attr("data-msgid");
var comment = $('.sendcomment').val();
if ($.trim(comment).length == 0) {
$("#commentload" + ID).text("nothing!");
} else {
$("#commentload" + ID).text(comment);
$("#commentid" + ID).val('').css("height", "35px").focus();
}
});
so basically instead of this you have to use input and get msgid and val from there, use same approach for rest.
So when you are attaching event on some button and you want to use data from some other dom element you have to get that element by using $(selector) under your delegated function, really simple approach.

How to display images one at a time through loop with HTML/Javascript?

I'm not one of those people that grew up with programming, or have experienced in high school. I just recently started the basics in College. What I have below is my javascript/html that I have been working on Visual Studio 2012. My goal for it is to display the images one at a time by pressing a button called "Next Name" (as you can see I created a "form" at the bottom of my code). But as I have it now, it prints out all the images in my "hw1.txt" at the same time. Under my for loop, I tried "result = "";" and then "displayList.innerHTML = result;" hoping to just print out one image at least. I tried other things, but it just left my code messy. Please I need help. Any advice, pointers, or whatever is good. Can you also explain your answers in a way that I'll understand too? Just think of me as you're talking to a child or something haha. Thanks.
Note: in "hw1.txt" every 3rd index (starting from index 0) is the name of people, and the index next to it (myArray[i + 1]) is the image file (inside the .txt it goes like 1.jpg, 2.jpg, 3.jpg, and so on...)
<br/>
<span id="displayList">Photo here.</span>
<script type=text/javascript>
if (typeof ActiveXObject != "undefined") // IE
var req = new ActiveXObject("Microsoft.XMLHTTP");
else // Other browsers
var req = new XMLHttpRequest();
req.open('GET', 'hw1.txt', false);
req.send(null);
s = req.responseText;
var myArray = s.split(";");
var result = "";
function nextItem() {
for (i = 3; i < myArray.length; i = i + 3)
result = result + "<img src='" + myArray[i + 1] + "'/>";
displayList.innerHTML = result;
}
</script>
<form name="ClickNext">
<input type="button" value="Next Name" onclick="nextItem()" />
</form>
<span id="displayList">Photo here.</span>
<script type=text/javascript>
if (typeof ActiveXObject != "undefined") // IE
var req = new ActiveXObject("Microsoft.XMLHTTP");
else // Other browsers
var req = new XMLHttpRequest();
req.open('GET', 'hw1.txt', false);
req.send(null);
s = req.responseText;
var myArray = s.split(","); //if images are comma(,) seperated then just split it from comma
var index = 0;
function nextItem() {
if(typeof myArray[index] !== 'undefined') {
displayList.innerHTML = "<img src='" + myArray[index] + "'/>";
index += 1;
}
}
</script>
<form name="ClickNext">
<input type="button" value="Next Name" onclick="nextItem()" />
</form>
First off you don't need the form around that input since you don't really send a form.
Secound you should add an id to your input ( or <a></a> or <button></button> ) such as id="next_name" or I guess you can keep the old way of calling an event. :P
Then, you should:
var position = 0;
var result = '';
document.getElementById('next_name').onclick = function(){
if(position < myArray.length){
result = result + "<img src='" + myArray[position + 1] + "'/>";
displayList.innerHTML = result;
position++;
}
};
The idea is to use a variable to memorize your position within your list of image srouces. Once you use one, you increment your position within the list so next time a user clicks that button you add a different image.

Categories