jquery div not respnding to other javascript/jquery methods - javascript

I have added one div inside a div using $(select).append() method but the I want it to close it on click on image so i hav added image and an another $(select).button().click( { $(select).hide() }); but on clicking the close image nothing happens....
$(document).ready(function() {
$("#subCre").click(function() {
cust = $("#customer").val();
address = $('#address').val();
phone = $('#phone').val();
amt = $('#initamount').val();
user = '<%= session.getAttribute("user").toString()%>';
type = '<%=session.getAttribute("type").toString()%>';
alert(cust + address + phone + amt + user + type);
$.post("../processor/proc2.jsp",
{
customer: cust,
address: address,
phone: phone,
initamount: amt,
user: user,
type: type
},
function(data, status) {
if (status === "success") {
if(data.length == 11) {
$("#SystemMessages").append('<div class="Msg draggable"><img class="close" src="../mime/close.png">Account Added</div>'); // **Here one div
} else {
$("#SystemMessages").append('<div class="errorMsg draggable"><img class="close" src="../mime/close.png">'+ data + '</div>'); //** here 2nd div
}
$("#customer").val("");
$('#address').val("");
$('#phone').val("");
$('#initamount').val("");
}
});
$(".close").button().click(function() {
$(".close").parent().css("visibility", "hidden");
});
});

You need to use event delegation for dynamically appended elements
$('#SystemMessages').on('click','.close',function(){
$(this).parent().css("visibility", "hidden");
});
Event delegation ---> https://learn.jquery.com/events/event-delegation/

Since you have dynamically added .close element to the existing HTML, you need to delegate it using on event handler
$(".close").button();
$("#SystemMessages").on('click', ".close", function() {
$(".close").parent().css("visibility", "hidden");
});

Simply use the following code
$('.close').live('click',function(){
$(this).parent().hide();
});
It will definitely work, let me know if it worked.
.live() being deprecated in jQuery version 1.7 and removed in version 1.9, so you can use .on() method in the following manner
$(document).on('click','.close',function(){
$(this).parent().hide();
});

Related

Extra click after dynamically added HTML elements via jQuery

I add some html dynamically in data.html
<div class="d-flex " id="deviceSeearchRecords">
<div class="p-2 flex-grow-1 ">
<button type="button" class="btn deviceName " data-href="#Url.Content(string.Format(" ~/Devices/Details/{0} ", #item.ID))">
#item.FullName
</button>
</div>
</div>
After this I assume to use click event like this.
$('#searchResultContainer').html('');
$.getJSON('#Url.Action("Search", "Devices")', {
s: $('#searchStr').val()
},
function(data) {
if (data.success === true) {
$('#searchResultContainer').append(data.html);
$(document).on('click', '.deviceName', function(e) {
e.preventDefault();
e.stopPropagation();
// console.log('deviceName ' + $(this).data('href'));
window.location.href = $(this).data('href');
});
}
});
But when I click first time then nothing happens. On second click it works as it should.
I have tried to use focus() on div but if does not help.
This approach does not help as well jquery functions inside of dynamically generated html not working
What do I missing here?
Move your code to the outside
$(document).on('click', '.deviceName', function(e) {
e.preventDefault();
e.stopPropagation();
// console.log('deviceName ' + $(this).data('href'));
window.location.href = $(this).data('href');
});
Thanks to all!
I found my solution here
Is it possible to focus on a <div> using JavaScript focus() function?
So I just use a regular <a> within data.html and after this focus on the div with dynamically added data. And one click works!
$('#searchResultContainer').html('');
$.getJSON('#Url.Action("Search", "Devices")', {
s: $('#searchStr').val()
},
function(data) {
if (data.success === true) {
if (data.success === true) {
$('#searchResultContainer').html(data.html);
window.location.hash = '#searchResultContainer';
}
}
});

Codeigniter cart remove a single element using jQuery

i have been trying to remove a single element from my cart using jQuery so it doesn't load the page but i am unable to detect where i am missing something. Its removing the element , but looks like something is wrong with jQuery so its loading the page.
Here are the code snaps -
View-
<td class="remove">
<?php echo anchor('home/remove_cart/'.$item['rowid'],'X',$item['rowid']); ?>
</td>
Controller-
public function remove_cart($rowid) {
$this->cart->update(array(
'rowid'=>$rowid,
'qty' => 0
));
redirect(base_url().'home/purchase_order');
}
js-
$("td.remove").live("click", function() {
var rem = $('a.removecart').data();
alert(rem+"f");
$.get(link + "home/remove_cart", {rowid : rem} ,function(data) {
$.get(link + "home/show_cart", function(home) {
$("#cart_content").html(home);
});
});
return false;
});
Thanks.
You're assigning a click event to the link's parent. So you must first of all cancel the default bahaviour of the link when you click on it. Then the click event will naturally bubble up to its parent: td.remove. The link will not be followed, and the click handler for the td will be executed.
$("td.remove a").live("click", function(e) {
e.preventDefault();
});
$("td.remove").live("click", function() {
var rem = $('a.removecart').data();
alert(rem+"f");
$.get(link + "home/remove_cart", {rowid : rem} ,function(data) {
$.get(link + "home/show_cart", function(home) {
$("#cart_content").html(home);
});
});
If this won't work, provide with more information, since there's a return false at the end that I don't know where it comes from.

Why is my JQuery function not triggered on a cloned element when the event becomes "true"?

I have been making this form that must enable the back-end user to create new questions for users to answer. The form is cloned and appended to a div (selector #content) successfully after the first .on(click) event, but it won't duplicate the form again if the cloned button is pressed. The .on(change) event applied to my drop-down selection does change the content of respective divs like it is supposed to, but only on the original form.
Here's the JQuery code:
$(document).ready(function () {
$('.addAnswer').on("click", function () {
var idx = $('#mp div[name^="antwoord"]:last').index() + 1;
$clone = $('#mp div[name^="antwoord"]:first').clone(true, true).attr('class', 'answer content_' + idx);
$('.removeAnswer').show;
$('#mp').append($clone);
$('.answer:last').each(function () {
$('b:last').empty();
$('b:last').prepend(String.fromCharCode(64 + idx) + ". ")
$('.addAnswer').on("click", function () {
idx++;
});
});
if (idx == 2) {
$('.removeAnswer').show();
}
});
$('.nextq').click(function () {
var newqid = $('#content form:last').index() + 1;
$('.done, .nextq, .remove').hide();
$('#content').append('<hr>');
$('#content').append($('form').html()).attr('class', 'q_' + newqid);
$('.nextq').on("click", function () {
newqid++;
});
$('.done:last, .nextq:last, .remove:last').show();
return false;
});
$('.group').hide();
$('#text:last').show();
$('.select:last').on("change", function () {
$('.group').hide();
$('#' + $(this).val() + ':last').fadeIn();
$('button.' + $(this).val() + ':last').fadeIn();
});
});
Because I thought posting the whole HTML template would be a tad bit too much, I provided a JSFiddle for you people.
One extra question for the ones that are feeling kind: In the JQuery code it is seen that the contents of the HTML are being parsed using .html() and appended with .append.(Line 33 on the JSFiddle) As the .on(change) function switches the contents of the divisions it should change, .html() sees those changes and takes those along with it. I'd like the .on(click) function to append the div's content in its original state, unchanged by the changes made beforehand by the back-end user. Any help with this would be much obliged.
In order to have jQuery trigger on new elements you would do something like
$( document ).on( "click", "<your id or class>", function() {
//Do stuff
});

create stackoverflow tagging system?

I am trying to create a tagging system just like SO has.
I have added the tags,now I want to remove them.
MyQuestion:
How do I remove the tags appended?
how do I make the cross button(a span) look identical to that in SO tagging system?
SO TAGGING
var tags = [];
$("#textBox").keypress(function (e) {
if (e.which === 13) {
$(".target").append("X</span>'+ "");
function remove_tag(){
//what to do here?
}
tags.push(this.value);
this.value = "";
}
});
Here's my JSFiddle: http://jsfiddle.net/Wky2Z/11/
Basically, listen on the .cross to be clicked, and then remove from array and delete element
//enter something in textbox and press enter....
var tags = [];
$("#textBox").keypress(function (e) {
if (e.which === 13) {
$(".target").append("X</span>'+ "");
tags.push(this.value);
this.value = "";
}
});
$('body').on('click','.cross',function(){
tags.splice($(this).parent('a').html(), 1);
$(this).parent('a').remove();
});
As for the look of the cross, SO use a CSS Sprite, so you can do the same by making a png or gif or jpeg of the two states, off(grey) and hover(red) and switch the background-position to red with css eg: .cross:hover { background-position:0px -20px }
You can delete elements making use of remove().
Also, i would recommend you to make use of jQuery events instead of using inline events. (if you take a look at the source code of stackoverflow you will notice there are no inline javascript calls)
In this case you would need to add an event handler to the document object as you want to assign the events to elements which are not loaded in the DOM from the start.
$(document).on('click', '.tag span', function(){
$(this).parent().remove();
});
Living example: http://jsfiddle.net/Wky2Z/7/
Update
I updated the example removing the element from the list of tags too:
http://jsfiddle.net/Wky2Z/8/
Added a data-value for the tag links:
$(".target").append("X</span>'+ "");
And modified the click event:
$(document).on('click', '.tag span', function(){
$(this).parent().remove();
var removeItem = $(this).parent().data('value');
tags = $.grep(tags, function(value) {
return value != removeItem;
});
});
For a full jQuery solution you can remove the inline remove_tag function and use jQuery on function. it works for dynamically created elements too.
Attach an event handler function for one or more events to the
selected elements.
Here you can get the parent element of the deleted element and remove it from the DOM using remove.
To "sync" the array with the current situation you can use grep to delete the item from the array; note the removedItem variable used to get the text only of the parent excluding the children from the text.
Code:
//enter something in textbox and press enter....
var tags = [];
$(document).ready(function () {
$('body').on('click', 'span.cross', function () {
var removedItem = $(this).parent().contents(':not(span)').text();
$(this).parent().remove();
tags = $.grep(tags, function (value) {
return value != removedItem;
});
});
$("#textBox").keypress(function (e) {
if (e.which === 13) {
$(".target").append("X</span>' + "");
tags.push(this.value);
this.value = "";
}
});
});
Demo: http://jsfiddle.net/IrvinDominin/pDFnG/
Here's the updated link: http://jsfiddle.net/Wky2Z/6/
Move remove_tag outside of keypress event handle and pass a this pointer to it for quick solution:
//enter something in textbox and press enter....
var tags = [];
function remove_tag(x) {
$(x).parent('a').remove();
}
$(function () {
$("#textBox").keypress(function (e) {
if (e.which === 13) {
$(".target").append("X</span>' + "");
tags.push(this.value);
this.value = "";
}
});
});

Using jquery to monitor form field changes

Trying to learn some jquery to implement an autosave feature and need some assistance. I have some code to monitor the status of form fields to see if there has been any change. Everything works, but I need to only monitor the changes in a specific form, not all form inputs on the page. There is a search box and a newsletter form on the same page and when these form fields are changed, they are detected as well, which I need to filter out somehow or better yet, only target the specific form.
$(function(){
setInterval("CheckDirty()",10000);
$(':input').each(function() {
$(this).data('formValues', $(this).val());
});
});
function CheckDirty()
{
var isDirty = false;
$(':input').each(function () {
if($(this).data('formValues') != $(this).val()) {
isDirty = true;
}
});
if(isDirty == true){
alert("isDirty=" + isDirty);
}
}
Just add a class to the form and use it to filter
$('.form :input').each(function() {
$(this).data('formValues', $(this).val());
});
EDIT
Just a suggestion, you can attach the change event directly to the form
live demo here : http://jsfiddle.net/jomanlk/kNx8p/1/
<form>
<p><input type='text'></p>
<p><input type='text'></p>
<p><input type='checkbox'></p>
</form>
<p><input type='text'></p>
<div id='log'></div>
$('form :input').change(function(){
$('#log').prepend('<p>Form changed</p>')
});
You can easily improve this by adding a timer and making it save every xx seconds.
var $jq= jQuery.noConflict();
$jq(function() { $jq('#extensibleForm').data('serialize',$jq('#extensibleForm').serialize());
});
function formHasChanged(){
if($jq('#extensibleForm').serialize()!=$jq('#extensibleForm').data('serialize')){
alert("Data Changed....");
return (false);
}
return true;
}
what's your form's id?
you just need to make your selector more specific :)
instead of $(':input').each(function() {
use
$('#yourFormId').find(':input').each(function() {
You can use the .change() function and then use $(this) to denote you want to work with just the field that is actively being changed.
$('#myForm input[type="text"]').change(function() {
$(this)...
});
Edit: #myForm is your form ID so you can target a specific form. You can even specify just type="text" fields within that form, as in my example.
Here you can see it working: http://jsfiddle.net/paska/zNE2C/
$(function(){
setInterval(function() {
$("#myForm").checkDirty();
},10000);
$("#myForm :input").each(function() {
$(this).data('formValues', $(this).val());
});
$.fn.checkDirty = function() {
var isDirty = false;
$(this).find(':input').each(function () {
if($(this).data('formValues') != $(this).val()) {
isDirty = true;
}
});
if(isDirty == true){
alert("isDirty=" + isDirty);
}
};
});
I think you can use a class to select the type of input you want.
<input class="savethis" ... />
Then in jQuery use this.
$(':input .savethis').each(function() { ...
You can specify an id attribute (say theForm) to your form element and then select only those input fields inside it.
then try selecting with
$(':input', '#theForm')
I respect all the working answers but for me I think using the focus event might be much better than change event. This is how I accomplished my watchChange() function is JS:
var changeInterval = 0;
var changeLength = 0; //the length of the serverData
var serverData = {value:''}; //holds the data from the server
var fieldLength = 0; //the length of the value of the field we are tracking
var frequency = 10000;
function watchChange() {
$input.on('focus', function() {
var $thisInput = $(this);
//we need the interval value so that we destroy
//setInterval when the input loses focus.
changeInterval = setInterval(function() {
changeLength = serverData.value.length;
fieldLength = $thisInput.val().length;
//we only save changes if there is any modification
if (changeLength !== fieldLength) {
$.ajax({
url: 'path/to/data/handler',
dataType: 'json',
data: "data=" + $thisInput.val(),
method: 'post'
}).done(function(data) {
serverData = data;
}); //end done
} //end if
}, frequency); //end setInterval
//and here we destroy our watcher on the input
//when it loses focus
}).on('blur', function() {
clearInterval(changeInterval);
});
}
Even though this approach seems to be naive but it gave me what I wanted!

Categories

Resources