dynamic add and delete input field jquery 1.10 - javascript

Hi I'm having trouble with this fiddle I found somewhere it works perfectly on 1.4 jquery
but I am using 1.10 version of Jquery.
I notice that live method is deprecated in 1.10 so I user on to replace live but still not doing as it supposed to do.
my toubled fiddle is here
I used to code back end so please spare me, could anyone help me with this?

You should use parent selector $("#content") with on() and use prop() to make button disable like,
$("#content").on("click", ".plus",function(){
var parent = $(this).closest(".iteration");// use closest
parent.append('<input type="text" value="Create a task for this iteration" />');
var nbinput = parent.find("input[type='text']").length;
if(nbinput == 5)
parent.find(".plus").prop("disabled",true);// use prop()
if(nbinput > 0)
parent.find(".moins").prop("disabled",false);
});
$("#content").on("click",".moins", function(){
var parent = $(this).closest(".iteration");// use closest
parent.children("input").last().remove();
var nbinput = parent.find("input[type='text']").length;
if(nbinput < 5)
parent.find(".plus").prop("disabled",false);// use prop()
if(nbinput == 0)
parent.find(".moins").prop("disabled",true);
});
Demo

To make on work like you wanted you need to specify an element that won't be changed as the main selector and pass the dynamic element selector as the second parameter:
$("#content").on("click", ".plus", function(){
Also, there was an error with the code that disabled the plus and minus buttons, instead of setting the disabled attribute to empty you want to remove it completely:
parent.find(".moins").removeAttr("disabled");
Finally, changed the .parent().parent().parent('.iteration') to
$(this).closest(".iteration");
As this is much simpler and less likely to be broken by changes to your html.
http://jsfiddle.net/infernalbadger/L3s3w/3/

Related

.replaceWith() is not working in jQuery 1.9+

I'm trying to clone a <textarea> and clone and replace the digit in the label <label> Number 1 <label> increasing by 1 each time the add button is pressed (So the first label will have Number 1, the label underneath Number 2 etc).
This works with jQuery 1.8 and below but anything above does not clone and add 1 to the digit.
HTML
<div>
<label for="number">Number <span class="one">1</span></label>
<textarea id="number"></textarea>
</div>
<button>Add</button>
jQuery
var $row = $('div').clone(),
cloneCount = 2;
$('button').click(function () {
$row.clone().insertBefore($("button"));
$('span').clone().attr('span', cloneCount++).replaceWith($('[class=one]:last')).text(cloneCount - 1);
});
JSFIDDLE: http://jsfiddle.net/wba6jvkj/
I don't know what you were attempting with .attr('span' and why it seemed to work in < 1.8, or why you are subtracting one from cloneCount, but this should do what you want:
var $row = $('div').clone(),
cloneCount = 2;
$('button').click(function () {
$row.clone().insertBefore($("button"));
$('span.one:last').text(cloneCount++);
});
jsFiddle example
(Answering to this old question, as Google led me here.)
The behavior of .replacewith() with disconnected nodes has been modified in jQuery 1.9. You may find the following explanation in the replaceWith() documentation (section "Additional Notes"), and also in the jQuery 1.9 upgrade guide:
Prior to jQuery 1.9, .replaceWith() would attempt to add or change nodes in the current jQuery set if the first node in the set was not connected to a document, and in those cases return a new jQuery set rather than the original set. The method might or might not have returned a new result depending on the number or connectedness of its arguments! As of jQuery 1.9, .after(), .before(), and .replaceWith() always return the original unmodified set. Attempting to use these methods on a node without a parent has no effect—that is, neither the set nor the nodes it contains are changed.
In your code, you are using .replaceWith() on a cloned element, thus which hasn't been inserted into the DOM yet.

Disable a text area by it's class (not id)

I have 2 text area's that are generated automatically, and I need to use JavaScript to disable both when the page has loaded. The catch is because they are generated automatically I can't give them an ID because they would both have the ID - a big no.
Attempted Javascript:
document.getElementByClassName('option_window-size').disabled=true;
I know this works because if I change getElementbyClassName to ID then it will work if I give the text areas the ID as well. But as I say it needs to work off class. Also it can't work of the Name attribute because that is automatically generated per product and per page...
I have tried this but it just doesn't work and I can't figure out why not because it should as the only thing I have changed is from ID to CLASS
Text Areas
<textarea name="willbeautogenerated" class="option_window-size" cols="40" rows="5">willbeautogenerated</textarea>
Additional note: I have tried to count and assign them different IDs using PHP but it gets far to complex. Also it is only these two that need disabling, thus I can't just disable all text area's on the page.
I know this works because if I change getElementByClassName to ID then it will work if I give the text areas the ID as well. But as I say it needs to work off class.
getElementsByClassName returns a NodeList rather than a Node itself. You'll have to loop over the list, or if you expect just 1 item, choose index 0.
var nodes = document.getElementsByClassName("option_window-size"),
i = 0, e;
while (e = nodes[i++]) e.disabled = true;
jQuery makes this pretty simple:
$(".selector").prop("disabled", true);
ALTHOUGH! It should be noted that this note appears on the man pages for $.prop() and $.attr():
Note: Attempting to change the type property (or attribute) of an input element created via HTML or already in an HTML document will result in an error being thrown by Internet Explorer 6, 7, or 8.
This doesn't apply directly to your question, but you are changing prop/attrs on an input element, so be aware.
But it's still possible with plain old JS:
var els = document.getElementsByClassName("selector"); // note: Elements, not Element
for(var e = 0; e < els.length; e++)
{
els[e].disabled = true;
}
getElementsByClassName returns an NodeList, you just have to iterate over each element within.
You can use class selector,
$('.option_window').attr('disabled', true);
OR
$('.option_window')[0].disabled = true;
With Jquery you can do:
//make sure to use .prop() and not .attr() when setting properties of an element
$('.option_window').prop('disabled', true);
Disable textarea using jQuery:
$('.option_window-size').attr('disabled', true);
your missing a s in elements and the index where the element is like [0], for the first element.
document.getElementsByClassName('option_window-size')[0].disabled=true;
or
document.getElementsByName('willbeautogenerated')[0].disabled=true;
Disabel texarea using .prop() methode in jquery...
$('.option_window-size').prop('disabled', true);
You can use CSS:
.option_window-size{display:none;}

Display number of checked checkboxes in jQuery

I am quite new to jQuery, I think this might be quite easy for many of you, but I can't seem to make it work. How can I display the number of checkboxes so that the value increases or decreases.
i tried the following but with the number in the span tag remains 0: http://jsfiddle.net/yunowork/NTwxc/
Thanks
You should listen to the change event:
$('input[type=checkbox]').on('change', function(){
var number = $('input[type=checkbox]:checked').length;
$('.totalchecked').text(number);
});
http://jsfiddle.net/NTwxc/7/
Note that val is used for getting/setting values of form elements, for other elements like span element, text or html methods should be used.
Number of checked checkboxes:
$(":checkbox:checked").length
http://api.jquery.com/checked-selector/
edit: I see in your fiddle that you already had that. I'll leave it there, since that's actually the answer to "how to display the number of checked checkboxes"...
The problem is that you're not updating and looking to see how many are checked. You need to re-run that function whenever any of the items are checked.
$(":checkbox").change(function () {
// update the span with $(":checkbox:checked").length ...
});
You shouldn't be setting .val of a span, but .text.
Also, you need to update it every time the checked state changes.
function calc() {
$('.totalchecked').text($(':checkbox:checked').length);
}
$(calc);
$(':checkbox').change(calc);
Demo
Here we are!
$('input[type="checkbox"]').change(function() {
$('.totalchecked').empty().text($('input[type="checkbox"]:checked').size());
});
http://jsfiddle.net/toroncino/PTvG8/
Problems: .val() is for form elements only. To set the content of an element, use .text() or .html() if you are inserting HTML. Second problem is that you need to register a listener to "change" events. Otherwise, the value won't update.
Updated solution: http://jsfiddle.net/NTwxc/4/
$("input[type=checkbox]").change(function(){
var number = $('input[type=checkbox]:checked').length;
$(".totalchecked").text(number);
});
​
By the way, I would personally prefer input[type=checkbox]rather than :checkbox. The former works for both CSS and jQuery.

Jquery binding to keyup

I'm having some problems binding to the keyup event of a textarea control. I'm trying the below
var shortDescInput = $('nobr:contains("Short Description")').closest('tr').find($('textarea[title="Short Description"]'));
// this doesn't work
shortDescInput.bind('keyup', function () {
countShortDescChars();
});
// Nor this
shortDescInput.keyup(function () {
countShortDescChars();
});
Am I missing something here that's really obvious? This is working for other controls, for example binding events to radiobuttons. I've checked and I'm defiantly selecting the right textarea with
var shortDescInput = $('nobr:contains("Short Description")').closest('tr').find($('textarea[title="Short Description"]'));
I just never seem to get the keyup event....
find($('textarea[title="Short Description"]')) is highly inefficient. For your purposes, find should take a selector as it's argument.
When you pass in a jQuery object to find, jQuery first queries the DOM from the top and finds all elements that match that selector. Then, find loops through all of these results until it finds one that matches the specified parents.
You should, instead, use:
find('textarea[title="Short Description"]')
Also, use .on instead of .bind. .bind is set to be deprecated in future releases for it's inefficiency.
shortDescInput.on("keyup", countShortDescChars);
And the revised code:
$(function () {
var shortDescInput = $('nobr:contains("Short Description")').closest('tr').find('textarea[title="Short Description"]');
shortDescInput.on("keyup", countShortDescChars);
});
To verify that a selector is working use .length with a console.log() or old fashioned alert() :
var shortDescInput = $('nobr:contains("Short Description")').closest('tr').find('textarea[title="Short Description"]');
alert(shortDescInput.length);
You can also go step by step to identify the one not returning anything :
alert($('nobr:contains("Short Description")').length);
alert($('nobr:contains("Short Description")').closest('tr').length);
alert($('nobr:contains("Short Description")').closest('tr').find('textarea[title="Short Description"]').length);
Second try. using .on() instead of .bind() :
shortDescInput.on('keyup',function(){countShortDescChars();});
So I played along with your fiddle and...
There IS something wrong with your selector.
First I remove the script tags from the js part.
then remove the script tag in your html cause it broke the fiddle.
Switched to jQuery 1.8.0 cause MooTools is not what we want.
added shortDescInput = $('textarea'); after your giant selector, event is triggered!
Added again shortDescInput = $('textarea'); in your function to make the counter work.
So again, let's now try to figure why your selector is not working :-)
Edit:
Found it!
I replaced your .closest() with .parent().next() because I kind of think .closest() was targeting the parent .
var shortDescInput = $('nobr:contains("Short Description")').parent().next().find('textarea[title="Short Description"]');
The problem is that at least in the fiddle, the <tr> wasn't in a <table>and so it was removed from the DOM by the browser. Wrapping the <tr> in a <table> made the fiddle work.
Demo: http://jsfiddle.net/kNkXE/9/

I want to check if `id` has no content

I want check between id that get in var span, if empty was between it put css for input but it not work. how can fix it?
var span = '#'+$('.valid').closest('.auto_box').find('span').attr('id');
if ($(span+':empty').length != 0) {
//alert('ok')
(this).closest('.auto_box').find('input').css('background-color','#000');
}
See here my full code: http://jsfiddle.net/Pjqv2/2/
You are using (this) instead of $('.valid') or whatever you meant with it. Also, you are doing this the wrong way; .find('span') returns the jQuery objects set for that span.
You don't need to get it's ID and then check on that ID again. More importantly, your code seems the need to run on multiple instances of .auto_box. For that, you need to iterate on the set found by (".valid").closest(".auto_box"), which you can do with the jQuery .each() (.each() in jQuery docs) like this:
var autoBoxes = $(".valid").closest(".auto_box");
autoBoxes.each(function(){
if ($(this).find("span").is(":empty")) {
$(this).find("input").css("background-color", "#000");
}
});
Your updated jsfiddle with this script: http://jsfiddle.net/dvir_azulay/Pjqv2/4/
Change (this) to $(span). I updated your fiddle to reflect this change.

Categories